Мартин обнови решението на 03.04.2015 04:40 (преди над 9 години)
+last_fib = []
+last_prime = 0
+last_letter = 0
+
+
+def fibonacci(end=0):
+ global last_fib
+ if not last_fib:
+ init1 = 0
+ init2 = 1
+ last_fib.append(init1)
+ last_fib.append(init2)
+ else:
+ init1 = last_fib[0]
+ init2 = last_fib[1]
+ counter = 0
+ while counter < end or not end:
+ yield init2
+ init2 += init1
+ init1 = init2 - init1
+ last_fib[0] = init1
+ last_fib[1] = init2
+ counter += 1
+ raise StopIteration
+
+
+def primes(end=0):
+ counter = 0
+ global last_prime
+ if not last_prime:
+ prime = 2
+ yield 2
+ last_prime = prime
+ counter += 1
+ else:
+ prime = last_prime
+ if counter < end or not end:
+ while counter < end or not end:
+ prime += 1
+ if is_prime(prime):
+ yield prime
+ last_prime = prime
+ counter += 1
+ raise StopIteration
+
+
+def is_prime(number):
+ for i in range(2, number // 2 + 2):
+ if number % i == 0:
+ return False
+ return True
+
+
+def alphabet(code='', letters='', end=0):
+ counter = 0
+ if not (letters is ''):
+ for cur_let in letters:
+ if counter < end or not end:
+ yield cur_let
+ counter += 1
+ elif not (code is ''):
+ if code == "bg":
+ cur_let = 1072
+ while cur_let < 1099:
+ if counter < end or not end:
+ yield chr(cur_let)
+ counter += 1
+ cur_let += 1
+ cur_let += 1
+ if counter < end or not end:
+ yield chr(cur_let)
+ counter += 1
+ cur_let += 2
+ while cur_let < 1104:
+ if counter < end or not end:
+ yield chr(cur_let)
+ counter += 1
+ cur_let += 1
+ elif code == "lat":
+ cur_let = 97
+ while cur_let < 123:
+ if counter < end or not end:
+ yield chr(cur_let)
+ counter += 1
+ cur_let += 1
+ raise StopIteration
+
+
+def intertwined_sequences(iterable, generator_definitions=0):
+ return_list = []
+ for sequence in iterable:
+ for key, value in sequence.items():
+ if key == 'sequence' and value == 'fibonacci':
+ return_list.extend(list(fibonacci(sequence['length'])))
+ elif key == 'sequence' and value == 'primes':
+ return_list.extend(list(primes(sequence['length'])))
+ elif key == 'sequence' and value == 'alphabet':
+ try:
+ return_list.extend(
+ list(
+ alphabet(
+ sequence['code'],
+ sequence['letters'],
+ sequence['length']
+ )
+ )
+ )
+ except KeyError as err:
+ if err.args[0] == 'letters':
+ return_list.extend(
+ list(
+ alphabet(
+ sequence['code'],
+ '',
+ sequence['length']
+ )
+ )
+ )
+ elif err.args[0] == 'code':
+ return_list.extend(
+ list(
+ alphabet(
+ '',
+ sequence['letters'],
+ sequence['length']
+ )
+ )
+ )
+ global last_fib
+ global last_letter
+ global last_prime
+ last_fib = []
+ last_letter = 0
+ last_prime = 0
+ return return_list
- Опитваш се да върнеш списък вместо да yield-ваш стойности.
- Ползваш
global
което е меко казано ужасно. - Плашещо многото нива на влагане трябва да те наведат на мисълта, че нещо странно се случва и има по-лесен начин.
-
iterable
може да бъде безкраен и тогава тозиfor
никога няма да приключи.