Every number from 1,2,5,6,9,10... is divisible by 4 with remainder 1 or 2.
>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'
Answer from Aleksei astynax Pirogov on Stack OverflowEvery number from 1,2,5,6,9,10... is divisible by 4 with remainder 1 or 2.
>>> ','.join(str(i) for i in xrange(100) if i % 4 in (1,2))
'1,2,5,6,9,10,13,14,...'
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'
That was a quick and quite dirty solution.
Now, for a solution that is suitable for different kinds of progression problems:
def deltas():
while True:
yield 1
yield 3
def numbers(start, deltas, max):
i = start
while i <= max:
yield i
i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))
And here are similar ideas implemented using itertools:
from itertools import cycle, takewhile, accumulate, chain
def numbers(start, deltas, max):
deltas = cycle(deltas)
numbers = accumulate(chain([start], deltas))
return takewhile(lambda x: x <= max, numbers)
print(','.join(str(x) for x in numbers(1, [1, 3], 100)))
I have this very specific problem and not many ideas. I'm looking for some help to try to approach it. Here's the problem:
Given a sequence of no more than 8 '+' and '-' (strings), I need to form the smallest number possible following the rule: A '+' dictates that the next number is bigger than the current. A '-', that it's smaller. For example: if my string is '- - -', my number will be 4321, as all numbers are smaller than the one on their left, since the string is made only of '-'.
I forgot an important rule: The numbers have to be different! I can't have 1212 as a result, for example.
If I understand correctly, if I have a string with 'n' characters my number will be made of 'n+1' numbers. Now, I'm really out of ideas about how to implement a code for that. It's worth noting that I'm on a very basic level of learning python, the maximum i know is recursion (on a basic level, still). All I tried was using 'if/else' statements, but I'm not sure how to compare the numbers. Is using lists a good idea? And should I try recursion to go through the string?
Here's the code i have so far. Works only for the example i gave here.
def crypto(code:str):
numbers = []
# We start our list of numbers filling it with numbers equal to the length of the string. The idea is to decrease or increase these numbers accordingly with the srting
for i in range(len(code)):
numbers.append(len(code)+1)
# Here we decrease/increase. I'm not sure how to compare the numbers for cases like '-+-+', fro example.
pos = 0
for j in code:
if j == '+':
numbers[pos] += 1+pos
pos += 1
elif j == '-':
numbers[pos] -= 1+pos
pos += 1
numbers.insert(0, len(codigo)+1)
return print(numbers)
crypto('---')