-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblems.py
More file actions
1519 lines (1253 loc) · 54.2 KB
/
Copy pathproblems.py
File metadata and controls
1519 lines (1253 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import re
from classes import Problem
from utils import rnd_number, load_frequencies, _dict_path, load_dicts, _pick_word_list, words, fetch_gnews_headlines
from unidecode import unidecode
class WordList(Problem):
@classmethod
def create(cls, num_words=4, **kwargs):
wlist = _pick_word_list(num_words)
sample = random.sample(wlist, num_words)
memorize = ' '.join(sample)
prompt = random.choice(['>', '<'])
solution = ' '.join(sample[::1 if prompt == '>' else -1])
return Problem(cls.display_name(), memorize, prompt, solution, 4000, 'single line')
class WordPairs(Problem):
@classmethod
def create(cls, num_pairs=3, **kwargs):
wlist = _pick_word_list(2 * num_pairs)
sample = random.sample(wlist, 2 * num_pairs)
pairs = [(sample[2*i], sample[1 + 2 * i]) for i in range(num_pairs)]
memorize = ' '.join(f'{p[0]}:{p[1]}' for p in pairs)
chosen = random.randint(0, num_pairs - 1)
prompt = f'? {pairs[chosen][0]}'
solution = pairs[chosen][1]
return Problem(cls.display_name(), memorize, prompt, solution, 4000, 'matrix')
class WordNumberPairs(Problem):
@classmethod
def create(cls, num_pairs=3, number_length=4, **kwargs):
wlist = _pick_word_list(num_pairs)
sample = random.sample(wlist, num_pairs)
pairs = [(sample[i], rnd_number(number_length)) for i in range(num_pairs)]
memorize = ' '.join(f'{p[0]}:{p[1]}' for p in pairs)
chosen = random.randint(0, num_pairs - 1)
prompt = f'? {pairs[chosen][0]}'
solution = pairs[chosen][1]
return Problem(cls.display_name(), memorize, prompt, solution, 4000, 'matrix')
class Number(Problem):
@classmethod
def create(cls, number_length=6, **kwargs):
memorize = rnd_number(number_length)
prompt = random.choice(['>', '<'])
solution = ''.join(memorize[::1 if prompt == '>' else -1])
return Problem(cls.display_name(), memorize, prompt, solution, 3000, 'single line')
class NumberLong(Problem):
@classmethod
def create(cls, number_length=8, **kwargs):
prompt = '>'
memorize = rnd_number(number_length)
solution = memorize
return Problem(cls.display_name(), memorize, prompt, solution, 4000, 'single line')
class NumberList(Problem):
@classmethod
def create(cls, number_length=2, num_numbers=4, **kwargs):
sample = [rnd_number(number_length) for _ in range(num_numbers)]
memorize = ' '.join(sample)
prompt = random.choice(['>', '<'])
solution = ' '.join(sample[::1 if prompt == '>' else -1])
return Problem(cls.display_name(), memorize, prompt, solution, 2000, 'single line')
class NumberCalculate(Problem):
@classmethod
def create(cls, **kwargs):
a, b = random.randint(1, 20), random.randint(1, 20)
memorize = f'{a} {b}'
prompt = random.choice(['+', '-', '*'])
ops = {'+': a + b, '-': a - b, '*': a * b}
solution = str(ops[prompt])
return Problem(cls.display_name(), memorize, prompt, solution, 2000, 'single line')
class RandomLetters(Problem):
@classmethod
def create(cls, num_letters=8, **kwargs):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
memorize = ''.join([random.choice(alphabet) for _ in range(num_letters)])
prompt = '>'
solution = memorize
return Problem(cls.display_name(), memorize, prompt, solution, 2000, 'single line')
class RandomLettersAndNumbers(Problem):
@classmethod
def create(cls, size=8, **kwargs):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
numbers = '0123456789'
memorize = ''.join([random.choice(alphabet + numbers) for _ in range(size)])
prompt = '='
solution = memorize
return Problem(cls.display_name(), memorize, prompt, solution, 2000, 'single line')
class WordBackward(Problem):
@classmethod
def create(cls, **kwargs):
wlist = _pick_word_list(1)
memorize = random.choice(wlist)
prompt = '<'
solution = ''.join(memorize[::-1])
return Problem(cls.display_name(), memorize + ' >>', prompt, solution, 1000, 'single line')
class WordForward(Problem):
@classmethod
def create(cls, **kwargs):
wlist = _pick_word_list(1)
memorize = random.choice(wlist)[::-1]
prompt = '>'
solution = ''.join(memorize[::-1])
return Problem(cls.display_name(), memorize + ' <<', prompt, solution, 1000, 'single line')
class ArrowDirection(Problem):
@classmethod
def create(cls, **kwargs):
# Unicode arrows from range U+2190 to U+21FF
arrows = {
'left': '←', # U+2190
'up': '↑', # U+2191
'right': '→', # U+2192
'down': '↓' # U+2193
}
directions = ['left', 'up', 'right', 'down']
# Create a single line of 4-6 arrows
num_arrows = random.randint(4, 6)
# Generate random arrows for the line
arrow_line = []
arrow_directions = []
for i in range(num_arrows):
direction = random.choice(directions)
arrow_line.append(arrows[direction])
arrow_directions.append(direction)
# Create display string with spacing
memorize = ' '.join(arrow_line)
# Choose a random position to ask about (1-indexed for user)
ask_position = random.randint(1, num_arrows)
prompt = f"{ask_position}"
solution = arrow_directions[ask_position - 1] # Convert back to 0-indexed
return Problem(cls.display_name(), memorize, prompt, solution, 2500, 'single line')
class GeometricForms(Problem):
@classmethod
def create(cls, **kwargs):
# Unicode geometric shapes from range U+25A0 to U+25FF
shapes = {
'square': ['■', '□', '▪', '▫'], # U+25A0, U+25A1, U+25AA, U+25AB
'triangle': ['▲', '△', '▼', '▽'], # U+25B2, U+25B3, U+25BC, U+25BD
'circle': ['●', '○', '◉', '◯'] # U+25CF, U+25CB, U+25C9, U+25EF
}
form_names = ['square', 'triangle', 'circle']
# Create a line of 4-6 shapes
num_shapes = random.randint(4, 6)
# Generate random shapes for the line
shape_line = []
shape_forms = []
for i in range(num_shapes):
form_name = random.choice(form_names)
shape_char = random.choice(shapes[form_name])
shape_line.append(shape_char)
shape_forms.append(form_name)
# Create display string with spacing
memorize = ' '.join(shape_line)
# Choose a random position to ask about (1-indexed for user)
ask_position = random.randint(1, num_shapes)
prompt = f"{ask_position}"
solution = shape_forms[ask_position - 1] # Convert back to 0-indexed
return Problem(cls.display_name(), memorize, prompt, solution, 2500, 'single line')
class FlightInfo(Problem):
@classmethod
def create(cls, num_flights=1, **kwargs):
airlines = []
airlines_path = _dict_path('airlines.txt')
if airlines_path.exists():
with open(airlines_path) as f:
for line in f:
line = line.strip()
if ',' in line:
code, name = line.split(',', 1)
airlines.append((code.strip(), name.strip()))
if not airlines:
airlines = [('XX', 'Unknown')]
destinations = []
cities_path = _dict_path('cities.txt')
if cities_path.exists():
with open(cities_path) as f:
destinations = [line.strip() for line in f if line.strip()]
if not destinations:
destinations = ['Unknown']
flights = []
used_airlines = []
used_destinations = []
used_gates = []
def generate_random_gate():
gate_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letter = random.choice(gate_letters)
number = random.randint(1, 99)
return f"{letter}{number}"
for i in range(num_flights):
available_airlines = [a for a in airlines if a[0] not in used_airlines]
if not available_airlines:
available_airlines = airlines
airline_code, airline_name = random.choice(available_airlines)
used_airlines.append(airline_code)
available_destinations = [d for d in destinations if d not in used_destinations]
if not available_destinations:
available_destinations = destinations
destination = random.choice(available_destinations)
used_destinations.append(destination)
gate = generate_random_gate()
while gate in used_gates:
gate = generate_random_gate()
used_gates.append(gate)
flight_num = random.randint(100, 9999)
hour = random.randint(6, 23)
minute = random.choice([0, 15, 30, 45])
time_str = f"{hour:02d}:{minute:02d}"
flight_info = f"{airline_code} {flight_num} {destination} {gate} {time_str}"
flights.append(flight_info)
memorize = ""
for i, flight in enumerate(flights, 1):
if i > 1:
memorize += "\n"
memorize += f"{i}. {flight}"
ask_flight = random.randint(1, num_flights)
prompt = f"{ask_flight}"
solution = flights[ask_flight - 1] # Convert to 0-indexed
return Problem(cls.display_name(), memorize, prompt, solution, 5000, 'single line')
class TokyoMetro(Problem):
@classmethod
def create(cls, num_stations=3, **kwargs):
# Load Tokyo Metro lines and stations from file
metro_lines = {}
current_line_english = None
current_line_kanji = None
with open(_dict_path('tokyo_metro.txt')) as f:
for line in f:
line = line.strip()
if not line:
continue
# Check if this is a line name (format "English:Kanji")
if ',' not in line and ':' in line:
english_line, kanji_line = line.split(':', 1)
current_line_english = english_line.strip()
current_line_kanji = kanji_line.strip()
metro_lines[current_line_english] = {
'english': [],
'kanji': [],
'line_kanji': current_line_kanji
}
elif current_line_english and ',' in line:
# This is a station list for the current line in format "English:Kanji"
station_pairs = [station.strip() for station in line.split(',')]
for pair in station_pairs:
if ':' in pair:
english, kanji = pair.split(':', 1)
metro_lines[current_line_english]['english'].append(english.strip())
metro_lines[current_line_english]['kanji'].append(kanji.strip())
else:
# Fallback for stations without kanji
metro_lines[current_line_english]['english'].append(pair.strip())
metro_lines[current_line_english]['kanji'].append(pair.strip())
# Only use lines that have at least one station (avoid randint(0, -1))
lines_with_stations = {
k: v for k, v in metro_lines.items()
if len(v['english']) > 0
}
if not lines_with_stations:
raise ValueError("tokyo_metro.txt has no lines with stations")
itinerary = []
used_combinations = set()
start_hour = random.randint(7, 21)
start_minute = random.choice([0, 15, 30, 45])
current_minutes = start_hour * 60 + start_minute
for i in range(num_stations):
line_names = list(lines_with_stations.keys())
line_name = random.choice(line_names)
line_data = lines_with_stations[line_name]
station_index = random.randint(0, len(line_data['english']) - 1)
english_station = line_data['english'][station_index]
kanji_station = line_data['kanji'][station_index]
combo = (line_name, english_station)
attempts = 0
while combo in used_combinations and attempts < 50:
line_name = random.choice(line_names)
line_data = lines_with_stations[line_name]
station_index = random.randint(0, len(line_data['english']) - 1)
english_station = line_data['english'][station_index]
kanji_station = line_data['kanji'][station_index]
combo = (line_name, english_station)
attempts += 1
used_combinations.add(combo)
# Format time
hour = (current_minutes // 60) % 24
minute = current_minutes % 60
time_str = f"{hour:02d}:{minute:02d}"
itinerary.append((english_station, kanji_station, time_str))
# Add 5-15 minutes for next station
current_minutes += random.randint(5, 15)
# Create memorize string (using kanji for display)
memorize_parts = []
for i, (english_station, kanji_station, time) in enumerate(itinerary):
part = f"{kanji_station} {time}"
memorize_parts.append(part)
memorize = " → ".join(memorize_parts)
# Choose which station to ask about (1-indexed)
ask_position = random.randint(1, num_stations)
prompt = f"{ask_position}"
# Solution uses English (what they need to type)
solution = f"{itinerary[ask_position - 1][0]} {itinerary[ask_position - 1][2]}"
return Problem(cls.display_name(), memorize, prompt, solution, 4000, 'single line')
class Appointments(Problem):
@classmethod
def create(cls, num_appointments=3, **kwargs):
# List of possible appointment types
appointment_types = [
'Doctor', 'Dentist', 'Plumber', 'Car repair', 'Electrician',
'Hair', 'Vet', 'Lawyer', 'Accountant', 'Mechanic',
'Eye exam', 'PT', 'Massage', 'Interview',
'Bank', 'Grocery', 'Insurance', 'Tax',
'Computer', 'Inspection', 'Cleaning',
'Piano', 'Tutoring', 'Chiropractor', 'Orthodontist'
]
# Generate appointment times and types
appointments = []
used_times = set()
used_types = set()
# Generate starting time between 8:00 and 17:00 (office hours)
for i in range(num_appointments):
# Generate a unique time
attempts = 0
while attempts < 100: # Prevent infinite loops
hour = random.randint(8, 17)
minute = random.choice([0, 15, 30, 45]) # Quarter-hour intervals
time_str = f"{hour:02d}:{minute:02d}"
if time_str not in used_times:
used_times.add(time_str)
# Pick a unique appointment type
available_types = [t for t in appointment_types if t not in used_types]
if not available_types: # If all types used, reset
used_types.clear()
available_types = appointment_types
appointment_type = random.choice(available_types)
used_types.add(appointment_type)
appointments.append((time_str, appointment_type))
break
attempts += 1
# If we couldn't find a unique time, just use a random one
if attempts >= 100:
hour = random.randint(8, 17)
minute = random.choice([0, 15, 30, 45])
time_str = f"{hour:02d}:{minute:02d}"
appointment_type = random.choice(appointment_types)
appointments.append((time_str, appointment_type))
# Sort appointments by time for realistic scheduling
appointments.sort(key=lambda x: x[0])
# Create memorize string on one line
memorize_parts = []
for i, (time, apt_type) in enumerate(appointments, 1):
memorize_parts.append(f"{i}. {time} {apt_type}")
memorize = " ".join(memorize_parts)
# Choose which appointment to ask about (1-indexed)
ask_appointment = random.randint(1, num_appointments)
prompt = f"{ask_appointment}"
solution = f"{appointments[ask_appointment - 1][0]} {appointments[ask_appointment - 1][1]}"
return Problem(cls.display_name(), memorize, prompt, solution, 3500, 'single line')
class Anagram(Problem):
@classmethod
def create(cls, **kwargs):
# Use existing word lists from dictionaries (length 4-6)
if not words:
load_dicts(4, 6) # Load words of length 4-6
# Only use English (index 1) and French (index 2) common word dictionaries
# dict_paths[1] = 'dicts/common_english_words.txt'
# dict_paths[2] = 'dicts/common_french_words.txt'
available_dicts = []
dict_languages = {}
if len(words) > 1 and len(words[1]) > 0: # English dictionary
available_dicts.append(1)
dict_languages[1] = 'English'
if len(words) > 2 and len(words[2]) > 0: # French dictionary
available_dicts.append(2)
dict_languages[2] = 'French'
if not available_dicts:
try:
wlist = _pick_word_list(1)
original_word = random.choice(wlist)
dict_index = 0
language = 'English'
except ValueError:
return Problem(cls.display_name(), 'No words available', '>', 'error', 2000, 'single line')
else:
dict_index = random.choice(available_dicts)
language = dict_languages[dict_index]
original_word = random.choice(words[dict_index])
# Create anagram by shuffling letters
anagram_word = create_anagram(original_word)
# Make sure anagram is different from original
attempts = 0
while anagram_word.lower() == original_word.lower() and attempts < 20:
anagram_word = create_anagram(original_word)
attempts += 1
# Combine anagram and language in prompt
memorize = f"{anagram_word} ({language})"
# Create a custom Anagram instance to store language info
problem = Anagram(cls.display_name(), memorize, '>', original_word, 3000, 'single line')
# Store additional info for evaluation
problem._dict_index = dict_index
problem._language = language
return problem
def evaluate_solution(self, user_input):
"""Custom evaluation that accepts valid anagrams from the dictionary"""
if user_input is None:
return 0.0
# Normalize with unidecode to remove accents
user_normalized = unidecode(str(user_input).lower().strip())
solution_normalized = unidecode(self.solution.lower())
# First check exact match
if user_normalized == solution_normalized:
return 1.0
# Check if it's a valid anagram and in the dictionary
if self._is_valid_anagram(user_normalized, solution_normalized):
return 1.0
# Fall back to standard evaluation (Levenshtein distance)
return super().evaluate_solution(user_input)
def _is_valid_anagram(self, user_word, original_word):
"""Check if user_word is a valid anagram of original_word and exists in dictionary"""
# Check if letters match (anagram test) - both should already be normalized
if sorted(user_word) != sorted(original_word):
return False
# Check if the anagram exists in the appropriate dictionary
if not hasattr(self, '_dict_index'):
return False
# Ensure words are loaded
if not words:
load_dicts(4, 6)
# Check if user's word exists in the same dictionary that was used
# Normalize dictionary words with unidecode for comparison
dict_index = getattr(self, '_dict_index', 1)
if dict_index < len(words) and len(words[dict_index]) > 0:
normalized_dict_words = [unidecode(w.lower()) for w in words[dict_index]]
return user_word in normalized_dict_words
return False
def create_anagram(word):
"""Create an anagram by shuffling the letters of a word"""
letters = list(word.lower())
random.shuffle(letters)
return ''.join(letters)
class SequenceRecognition(Problem):
@classmethod
def create(cls, **kwargs):
"""Generate a sequence recognition problem with the first 5 elements"""
# Dictionary of sequence generators - easy to add new ones!
sequence_generators = {
'arithmetic': SequenceRecognition._generate_arithmetic,
'geometric': SequenceRecognition._generate_geometric,
'fibonacci': SequenceRecognition._generate_fibonacci,
'squares': SequenceRecognition._generate_squares,
'powers_of_2': SequenceRecognition._generate_powers_of_2,
'triangular': SequenceRecognition._generate_triangular,
'cubes': SequenceRecognition._generate_cubes,
'primes': SequenceRecognition._generate_primes,
'factorial': SequenceRecognition._generate_factorial,
'alternating': SequenceRecognition._generate_alternating,
'recursive': SequenceRecognition._generate_recursive,
'exponential': SequenceRecognition._generate_exponential,
'lucas': SequenceRecognition._generate_lucas,
'padovan': SequenceRecognition._generate_padovan,
'catalan': SequenceRecognition._generate_catalan,
}
# Randomly select a sequence type
sequence_type = random.choice(list(sequence_generators.keys()))
generator = sequence_generators[sequence_type]
# Generate the sequence (first 6 elements)
sequence = generator()
# Show first 5, ask for 6th
shown_sequence = sequence[:5]
next_element = sequence[5]
# Format the problem
memorize = ' '.join(map(str, shown_sequence))
prompt = '>'
solution = str(next_element)
return Problem(cls.display_name(), memorize, prompt, solution, 3000, 'single line')
@staticmethod
def _generate_arithmetic():
"""Arithmetic sequence: a, a+d, a+d*2, ..."""
start = random.randint(1, 20)
diff = random.randint(2, 10)
return [start + i * diff for i in range(6)]
@staticmethod
def _generate_geometric():
"""Geometric sequence: a, a*r, a*r^2, ..."""
start = random.randint(1, 5)
ratio = random.choice([2, 3]) # Keep numbers manageable
return [start * (ratio ** i) for i in range(6)]
@staticmethod
def _generate_fibonacci():
"""Fibonacci-like sequence: a, b, a+b, a+2b, 2a+3b, ..."""
a, b = random.randint(1, 5), random.randint(1, 5)
sequence = [a, b]
for i in range(4): # Generate 4 more elements
sequence.append(sequence[-1] + sequence[-2])
return sequence
@staticmethod
def _generate_squares():
"""Perfect squares: 1^2, 2^2, 3^2, ..."""
start = random.randint(1, 8)
return [(start + i) ** 2 for i in range(6)]
@staticmethod
def _generate_powers_of_2():
"""Powers of 2: 2^1, 2^2, 2^3, ..."""
start_power = random.randint(0, 4)
return [2 ** (start_power + i) for i in range(6)]
@staticmethod
def _generate_triangular():
"""Triangular numbers: 1, 3, 6, 10, 15, ..."""
start = random.randint(1, 5)
sequence = []
for i in range(6):
n = start + i
triangular = n * (n + 1) // 2
sequence.append(triangular)
return sequence
@staticmethod
def _generate_cubes():
"""Perfect cubes: 1^3, 2^3, 3^3, ..."""
start = random.randint(1, 6)
return [(start + i) ** 3 for i in range(6)]
@staticmethod
def _generate_primes():
"""Prime numbers sequence"""
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
start_idx = random.randint(0, len(primes) - 6)
return primes[start_idx:start_idx + 6]
@staticmethod
def _generate_factorial():
"""Factorial sequence: 1!, 2!, 3!, ..."""
start = random.randint(1, 4)
sequence = []
for i in range(6):
n = start + i
factorial = 1
for j in range(1, n + 1):
factorial *= j
sequence.append(factorial)
return sequence
@staticmethod
def _generate_alternating():
"""Alternating arithmetic sequence: a, a+d, a+2d, a+3d, a+4d, a+5d with alternating signs"""
start = random.randint(1, 10)
diff = random.randint(2, 8)
sequence = []
for i in range(6):
if i % 2 == 0:
sequence.append(start + i * diff)
else:
sequence.append(-(start + i * diff))
return sequence
@staticmethod
def _generate_recursive():
"""Recursive sequence: a(n) = a(n-1) + a(n-2) + c"""
a, b = random.randint(1, 5), random.randint(1, 5)
c = random.randint(1, 3)
sequence = [a, b]
for i in range(4):
sequence.append(sequence[-1] + sequence[-2] + c)
return sequence
@staticmethod
def _generate_exponential():
"""Exponential sequence: a * b^n"""
a = random.randint(1, 3)
b = random.choice([2, 3, 4])
return [a * (b ** i) for i in range(6)]
@staticmethod
def _generate_lucas():
"""Lucas sequence: L(n) = L(n-1) + L(n-2) with L(0)=2, L(1)=1"""
sequence = [2, 1]
for i in range(4):
sequence.append(sequence[-1] + sequence[-2])
return sequence
@staticmethod
def _generate_padovan():
"""Padovan sequence: P(n) = P(n-2) + P(n-3) with P(0)=1, P(1)=1, P(2)=1"""
sequence = [1, 1, 1]
for i in range(3):
sequence.append(sequence[-2] + sequence[-3])
return sequence
@staticmethod
def _generate_catalan():
"""Catalan numbers: C(n) = (2n)!/(n!(n+1)!)"""
def catalan(n):
if n <= 1:
return 1
return catalan(n-1) * (4*n - 2) // (n + 1)
start = random.randint(0, 3)
return [catalan(start + i) for i in range(6)]
class Metar(Problem):
@classmethod
def create(cls, **kwargs):
"""Generate a METAR/TAF aviation weather report memorization problem"""
# Airport codes (mix of major international airports)
airports = ['KJFK', 'KLAX', 'KORD', 'KATL', 'KDEN', 'KDFW', 'KSEA', 'KLAS',
'KMIA', 'KBOS', 'KPHX', 'KSFO', 'KIAD', 'KMSP', 'KDTW', 'KPHL',
'EGLL', 'LFPG', 'EDDF', 'EHAM', 'LIRF', 'LEMD', 'LOWW', 'ESSA',
'RJTT', 'VHHH', 'WSSS', 'YSSY', 'NZAA', 'OMDB', 'OTHH', 'RKSI',
'CYYZ', 'CYVR', 'SBGR', 'SAEZ', 'FACT', 'HECA', 'VIDP', 'UUEE']
# Generate METAR components
airport = random.choice(airports)
# Date/time (DDHHMMZ format)
day = random.randint(1, 31)
hour = random.randint(0, 23)
minute = random.choice([0, 30]) # Usually on the hour or half-hour
datetime_str = f"{day:02d}{hour:02d}{minute:02d}Z"
# Wind (direction/speed)
wind_dir = random.randint(1, 36) * 10 # Wind direction in 10-degree increments
wind_speed = random.randint(5, 25)
is_variable = random.random() < 0.1 # 10% chance of variable winds
if is_variable:
wind = "VRB"
else:
wind = f"{wind_dir:03d}"
wind += f"{wind_speed:02d}KT"
# Visibility
visibility = random.choice(['10SM', '7SM', '5SM', '3SM', '1SM', '1/2SM'])
# Weather phenomena (optional)
weather_phenomena = ['', '-RA', 'RA', '+RA', '-SN', 'SN', 'FG', 'BR', 'HZ']
weather = random.choice(weather_phenomena)
# Cloud layers
cloud_types = ['FEW', 'SCT', 'BKN', 'OVC']
cloud_altitudes = ['008', '015', '025', '035', '050', '080', '120']
if random.random() < 0.2: # 20% chance of clear skies
clouds = 'CLR'
else:
cloud_type = random.choice(cloud_types)
cloud_alt = random.choice(cloud_altitudes)
clouds = f"{cloud_type}{cloud_alt}"
# Temperature/Dewpoint
temp = random.randint(-10, 35)
dewpoint = temp - random.randint(0, 15) # Dewpoint is always <= temperature
temp_str = f"{temp:02d}" if temp >= 0 else f"M{abs(temp):02d}"
dewpoint_str = f"{dewpoint:02d}" if dewpoint >= 0 else f"M{abs(dewpoint):02d}"
temp_dewpoint = f"{temp_str}/{dewpoint_str}"
# Altimeter setting
altimeter = f"A{random.randint(2800, 3100)}"
# Build complete METAR
metar_parts = [airport, datetime_str, wind, visibility]
if weather:
metar_parts.append(weather)
metar_parts.extend([clouds, temp_dewpoint, altimeter])
full_metar = ' '.join(metar_parts)
# Choose what to ask for
question_types = [
('airport', airport, 'Airport code?'),
('wind_direction', "VRB" if is_variable else f"{wind_dir:03d}", 'Wind direction?'),
('wind_speed', f"{wind_speed}", 'Wind speed (knots)?'),
('visibility', visibility, 'Visibility?'),
('clouds', clouds, 'Cloud coverage?'),
('temperature', str(temp), 'Temperature (°C)?'),
('altimeter', altimeter, 'Altimeter setting?')
]
question_type, answer, prompt = random.choice(question_types)
return Problem(cls.display_name(), full_metar, prompt, answer, 6000, 'single line')
class Atc(Problem):
_airlines = None
_frequencies = None
@classmethod
def _load_airlines(cls):
if cls._airlines is None:
path = _dict_path('airlines.txt')
cls._airlines = []
if path.exists():
with open(path) as f:
for line in f:
if ',' in line:
cls._airlines.append(line.strip().split(',', 1)[0].strip())
if not cls._airlines:
cls._airlines = ['XX']
@classmethod
def _load_frequencies(cls):
if cls._frequencies is None:
cls._frequencies = load_frequencies()
@classmethod
def create(cls, **kwargs):
"""Generate ATC IFR departure/landing instructions"""
Atc._load_airlines()
Atc._load_frequencies()
# Aircraft callsigns (mix of airlines and general aviation)
flight_numbers = [f"{random.choice(Atc._airlines)}{random.randint(100, 9999)}" for _ in range(5)]
ga_callsigns = [f"N{random.randint(100, 999)}{random.choice(['AB', 'CD', 'EF', 'GH'])}" for _ in range(3)]
callsigns = flight_numbers + ga_callsigns
# Runways (common runway numbers)
runways = ['09L', '09R', '27L', '27R', '04L', '04R', '22L', '22R',
'01L', '01R', '19L', '19R', '16L', '16R', '34L', '34R',
'08L', '26R', '06R', '24L', '12L', '30R', '15L', '33R',
'03L', '21R', '05L', '23R', '07L', '25R', '10L', '28R',
'13L', '31R']
# Instruction type (departure, arrival, or vector)
instruction_type = random.choice(['departure', 'arrival', 'vector'])
callsign = random.choice(callsigns)
runway = random.choice(runways)
if instruction_type == 'departure':
# Generate departure instruction
squawk = ''.join([str(random.randint(0, 7)) for _ in range(4)])
if squawk[0] == '0': # Ensure first digit is 1-7
squawk = str(random.randint(1, 7)) + squawk[1:]
departure_heading = random.randint(1, 36) * 10
initial_altitude = random.choice([3000, 4000, 5000, 6000, 8000, 10000])
# Departure frequencies (fallback if dict missing or empty)
approach_list = Atc._frequencies.get('approach') or []
departure_freq = random.choice(approach_list) if approach_list else '121.00'
instruction = f"{callsign}, runway {runway}, cleared for takeoff, fly heading {departure_heading:03d}, climb and maintain {initial_altitude}, squawk {squawk}, contact departure {departure_freq}"
# Choose what to ask for
questions = [
('callsign', callsign, 'Aircraft callsign?'),
('runway', runway, 'Departure runway?'),
('heading', f"{departure_heading:03d}", 'Initial heading?'),
('altitude', str(initial_altitude), 'Initial altitude?'),
('squawk', squawk, 'Squawk code?'),
('frequency', departure_freq, 'Departure frequency?')
]
elif instruction_type == 'arrival':
# Generate arrival instruction
approach_type = random.choice(['ILS', 'RNAV', 'VOR', 'GPS'])
final_altitude = random.choice([2000, 2500, 3000, 3500, 4000])
speed_restriction = random.choice([180, 200, 210, 220, 250])
# Tower frequencies (fallback if dict missing or empty)
tower_list = Atc._frequencies.get('tower') or []
approach_freq = random.choice(tower_list) if tower_list else '118.00'
instruction = f"{callsign}, descend and maintain {final_altitude}, reduce speed {speed_restriction} knots, cleared {approach_type} approach runway {runway}, contact tower {approach_freq}"
# Choose what to ask for
questions = [
('callsign', callsign, 'Aircraft callsign?'),
('runway', runway, 'Landing runway?'),
('altitude', str(final_altitude), 'Final altitude?'),
('speed', str(speed_restriction), 'Speed restriction (knots)?'),
('approach_type', approach_type, 'Approach type?'),
('frequency', approach_freq, 'Tower frequency?')
]
else: # vector
# Generate vector instruction
vector_types = [
'traffic',
'spacing',
'final_approach',
'navigation',
'weather_deviation'
]
vector_type = random.choice(vector_types)
vector_heading = random.randint(1, 36) * 10
if vector_type == 'traffic':
instruction = f"{callsign}, turn left heading {vector_heading:03d}, vector for traffic"
reason = "traffic"
elif vector_type == 'spacing':
instruction = f"{callsign}, turn right heading {vector_heading:03d}, vector for spacing"
reason = "spacing"
elif vector_type == 'final_approach':
instruction = f"{callsign}, turn left heading {vector_heading:03d}, vector to final approach course runway {runway}"
reason = "final approach"
elif vector_type == 'navigation':
waypoints = ['STAR1', 'FIXME', 'ABCDE', 'POINT', 'NAVPT', 'INTER']
waypoint = random.choice(waypoints)
instruction = f"{callsign}, turn right heading {vector_heading:03d}, vector direct {waypoint}"
reason = waypoint
else: # weather_deviation
instruction = f"{callsign}, turn left heading {vector_heading:03d}, vector for weather deviation, advise when able to resume course"
reason = "weather"
# Choose what to ask for
questions = [
('callsign', callsign, 'Aircraft callsign?'),
('heading', f"{vector_heading:03d}", 'Vector heading?'),
('turn_direction', 'left' if 'left' in instruction else 'right', 'Turn direction?'),
('reason', reason, 'Vector reason?')
]
if vector_type == 'final_approach':
questions.append(('runway', runway, 'Runway?'))
question_type, answer, prompt = random.choice(questions)
return Problem(cls.display_name(), instruction, prompt, answer, 5000, 'single line')
class FlightPlan(Problem):
_vors = None
_frequencies = None
@classmethod
def _load_vors(cls):
if cls._vors is None:
path = _dict_path('vors.txt')
cls._vors = []
if path.exists():
with open(path) as f:
cls._vors = [line.strip() for line in f if line.strip()]
if not cls._vors:
cls._vors = ['VOR1']
@classmethod
def _load_frequencies(cls):
if cls._frequencies is None:
cls._frequencies = load_frequencies()
@classmethod
def create(cls, num_waypoints=5, **kwargs):
FlightPlan._load_vors()
FlightPlan._load_frequencies()
vor_list = FlightPlan._vors
freqs = FlightPlan._frequencies
approach_freqs = freqs.get('approach') or []
tower_freqs = freqs.get('tower') or []
ground_freqs = freqs.get('ground') or []
_fallback_freq = '121.00'
waypoints = []
used_vors = set()
for i in range(num_waypoints):
available_vors = [v for v in vor_list if v not in used_vors]
if not available_vors:
available_vors = vor_list
vor = random.choice(available_vors)
used_vors.add(vor)
heading = random.randint(0, 359)
altitude = random.choice([3000, 5000, 7000, 9000, 11000, 13000, 15000, 17000, 19000, 21000, 23000, 25000, 27000, 29000, 31000, 33000, 35000, 37000, 39000, 41000])
freq_type = random.choice(['approach', 'tower', 'ground'])
if freq_type == 'approach':
freq = random.choice(approach_freqs) if approach_freqs else _fallback_freq
contact = 'Approach'
elif freq_type == 'tower':
freq = random.choice(tower_freqs) if tower_freqs else _fallback_freq
contact = 'Tower'
else:
freq = random.choice(ground_freqs) if ground_freqs else _fallback_freq
contact = 'Ground'
waypoint = f"{vor} {heading:03d}° {altitude:,}ft {freq}MHz {contact}"
waypoints.append(waypoint)
memorize = '\n'.join(waypoints)