Creating a "snake" counter - python

I'm just trying to get the logic straight and using Python to help me do it. Ultimately, I need to solve this problem using ImageJ macro language.
I have no idea if I'm using the right term, but I'd like to create a "snake" counter.
x = 1
number = 12
maxVal = 3
minVal = 1
for i in xrange(number):
%do something
x = incrementSnakeCounter(x, maxVal, minVal)
print("i = ", i)
print("x = ", x)
The "snake" part is making the counter go up only to the maxVal, repeating that number on the next iteration, counting down to the minVal, repeating that value on the next iteration, and repeating the process.
For instance, in the above
I'd like the following to happen :
i = 0
x = 1
i = 1
x = 2
i = 2
x = 3
i = 3
x = 3
i = 4
x = 2
i = 5
x = 1
i = 6
x = 1
i = 7
x = 2
i = 8
x = 3
i = 9
x = 3
i = 10
x = 2
i = 11
x = 1

You will find some useful utils in itertools:
from itertools import chain, cycle
def snake(lower, upper):
return cycle(chain(range(lower, upper+1), range(upper, lower-1, -1)))
> s = snake(1,3)
> [next(s) for _ in range(10)]
[1, 2, 3, 3, 2, 1, 1, 2, 3, 3]

Here's a silly mathematical solution:
def snake(low, high, x):
k = (high-low+1)
return k - int(abs(x % (2*k) + low - k - 0.5))
[snake.snake(1,3,x) for x in range(8)]
[1, 2, 3, 3, 2, 1, 1, 2]

Add a conditional to determine if x should be increasing or decreasing at any given point within the loop.
x = 1
number = 12
maxVal = 3
minVal = 1
for i in xrange(number):
%do something
if(xIsIncreasing)
x = incrementSnakeCounter(x, maxVal, minVal)
else
x = decrementSnakeCounter(x, maxVal, minVal)
print("i = ", i)
print("x = ", x)
Then inside your incrementSnakeCounter() change the value of xIsIncreasing to false when x == maxVal and inside your decrementSnakeCounter() to true when x == minVal (you'll have to do some work to make sure that you're staying at the same value twice in a row, I don't have time right now to solve that part for you).

You can write a little custom generator.
The key is to create a list of the pattern you want to repeat [1, 2, 3, 3, 2, 1] and then index that with the modulo of the length to get the repeating behavior:
def snake(x, max_v=3, min_v=1):
cnt=0
sn=list(range(min_v, max_v+1,1))+list(range(max_v, min_v-1,-1))
while cnt<x:
yield cnt, sn[cnt%len(sn)]
cnt+=1
Then:
for i,x in snake(12):
print("i=",i)
print("x=",x)
print()
Prints:
i= 0
x= 1
i= 1
x= 2
i= 2
x= 3
i= 3
x= 3
i= 4
x= 2
i= 5
x= 1
i= 6
x= 1
i= 7
x= 2
i= 8
x= 3
i= 9
x= 3
i= 10
x= 2
i= 11
x= 1

Related

Find index of less or equal value in list recursively (python)

Got task to find indexes of value and double that value in input list.
In input first line we get list range, second - list of values, third - value to find.
The output is 2 numbers - indexes of equal or higher value and double the value. If there is none, return -1
Example input:
6
1 2 4 4 6 8
3
Example output:
3 5
What i got so far is standart binary search func, but i dont get how to make it search not only for exact number but nearest higher.
def binarySearch(arr, x, left, right):
if right <= left:
return -1
mid = (left + right) // 2
if arr[mid] >= x:
return mid
elif x < arr[mid]:
return binarySearch(arr, x, left, mid)
else:
return binarySearch(arr, x, mid + 1, right)
def main():
n = int(input())
k = input().split()
q = []
for i in k:
q.append(int(i))
s = int(input())
res1 = binarySearch(q, s, q[0], (n-1))
res2 = binarySearch(q, (s*2), q[0], (n-1))
print(res1, res2)
if __name__ == "__main__":
main()
The input is:
6
1 2 4 4 6 8
3
And output:
3 4
Here's a modified binary search which will return the base zero index of a value if found or the index of the next highest value in the list.
def bsearch(lst, x):
L = 0
R = len(lst) - 1
while L <= R:
m = (L + R) // 2
if (v := lst[m]) == x:
return m
if v < x:
L = m + 1
else:
R = m - 1
return L if L < len(lst) else -1
data = list(map(int, '1 2 4 4 6 8'.split()))
for x in range(10):
print(x, bsearch(data, x))
Output:
0 0
1 0
2 1
3 2
4 2
5 4
6 4
7 5
8 5
9 -1

List Comprehension nested in Dict Comprehension

I want to create a dict with lists as values, where the content on the lists depends on whether or not the key (numbers 1 to 100) is dividable by 3,5 and/or 7
The output would be like this:
{
1: ['nodiv3', 'nodiv5', 'nodiv7'],
3: ['div3', 'nodiv5', 'nodiv7'],
15: ['div3', 'div5', 'nodiv7'],
}
Similar questions where about filtering the list/values, not creating them.
dict_divider = {}
for x in range(0,101):
div_list= []
if x % 3 == 0:
div_list.append('div3')
else:
div_list.append('nodiv3')
if x % 5 == 0:
div_list.append('div5')
else:
div_list.append('nodiv5')
if x % 7 == 0:
div_list.append('div7')
else:
div_list.append('nodiv7')
dict_divider[x] = div_list
This works just fine, but is there a way to do this with a pythonic one-/twoliner?
Something along like this: d = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3'])
Pythonic is not about one or two liners. In my opinion is (mainly) about readability, perhaps this could be considered more pythonic:
def label(n, divisor):
return f"{'' if n % divisor == 0 else 'no'}div{divisor}"
def find_divisors(n, divisors=[3, 5, 7]):
return [label(n, divisor) for divisor in divisors]
dict_divider = {x: find_divisors(x) for x in range(1, 101)}
print(dict_divider)
You don't actually need to do all these brute-force divisions. Every third number is divisible by three, every seventh number is divisible by seven, etc:
0 1 2 3 4 5 6 7 8 9 ... <-- range(10)
0 1 2 0 1 2 0 1 2 0 ... <-- mod 3
0 1 2 3 4 5 6 7 8 9 ... <-- range(10)
0 1 2 3 4 5 6 0 1 2 ... <-- mod 7
So the best approach should take advantage of that fact, using the repeating patterns of modulo. Then, we can just zip the range with however many iterators you want to use.
import itertools
def divs(n):
L = [f"div{n}"] + [f"nodiv{n}"] * (n - 1)
return itertools.cycle(L)
repeaters = [divs(n) for n in (3, 5, 7)]
d = {x: s for x, *s in zip(range(101), *repeaters)}
There is actually a one liner that isnt even that complicated :)
my_dict = {}
for i in range(100):
my_dict[i] = ['div' + str(n) if i % n == 0 else 'nodiv' + str(n) for n in [3,5,7]]
you could write a second loop so that you only have to write if...else only once
dict_divider = {}
div_check_lst = [3, 5, 7]
for x in range(0,101):
div_list= []
for div_check in div_check_lst:
if x % div_check == 0:
div_list.append(f'div{str(div_check)}')
else:
div_list.append(f'nodiv{str(div_check)}')
dict_divider[x] = div_list
or
dict_divider = {x:[f'{'no' * x % div_check != 0}div{str(div_check)}' for x in range(0,101) for div_check in div_check_lst]}

How do I fix this program that adds up all the integers in a list except the one that equals said sum?

I am trying to solve a problem where I have to enter several integers as an input (seperated by a whitespace), and print the integer that is the sum of all the OTHER integers.
So e.g.:
1 2 3 would give: 3, because 3 = 1 + 2
1 3 5 9 would give: 9, because 5 + 3 + 1 = 9
This is the code I currently have:
x = input().split(" ")
x = [int(c) for c in x]
y = 0
for i in range(len(x)-1):
y += x[i]
del x[i]
z = sum(x)
if y == z:
print(y)
break
else:
x.insert(i,y)
As the output, it just gives nothing no matter what.
Does anyone spot a mistake? I'd be ever greatful as I'm just a beginner who's got a lot to learn :)
(I renamed your strange name x to numbers.)
numbers = input().split()
numbers = [int(i) for i in numbers]
must_be = sum(numbers) / 2
if must_be in numbers:
print(int(must_be))
The explanation:
If there is an element s such that s = (sum of other elements),
then (sum of ALL elements) = s + (sum of other elements) = s + s = 2 * s.
So s = (sum of all elements) / 2.
If the last number entered is always the sum of previous numbers in the input sequence. Your problem lies with the x.insert(i, y) statement. For example take the following input sequence:
'1 2 5 8'
after the first pass through the for loop:
i = 0
z = 15
x = [1, 2, 5, 8]
y = 1
after the second pass through the for loop:
i = 1
z = 14
x = [1, 3, 5, 8]
y = 3
after the third pass through the for loop:
i = 2
z = 12
x = [1, 3, 8, 8]
y = 8
and the for loop completes without printing a result
If it's guaranteed that one of the integers will be the sum of all other integers, can you not just sort the input list and print the last element (assuming positive integers)?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])
I think this is a tricky question and can be done in quick way by using a trick
i.e create a dictionary with all the keys and store the sum as value like
{1: 18, 3: 18, 5: 18, 9: 18}
now iterate over dictionary and if val - key is in the dictionary then boom that's the number
a = [1, 3, 5, 9]
d = dict(zip(a,[sum(a)]*len(a)))
print([k for k,v in d.items() if d.get(v-k, False)])

Given an array find element pairs whose sum is equal to the given sum and return the sum of their indices

Hey guys as you've read in the question i am trying to find the element pairs in an array equal to the given sum and return the sum of their respective indices.
I was able to return the element pairs for the given sum but failed to return the sum of their indices. Here is my code:
arr = [1, 4, 2, 3, 0 , 5]
sum = 7
x = min(arr)
y = max(arr)
while x < y:
if x + y > sum:
y -= 1
elif x + y < sum:
x += 1
else:
print("(", x, y, ")")
x += 1
My output:
( 2 5 )
( 3 4 )
This is what i need to do further:
2 + 5 = 7 → Indices 2 + 5 = 7;
3 + 4 = 7 → Indices 3 + 1 = 4;
7 + 4 = 11 → Return 11;
Thanks in Advance!
you can try using a nested loop :
arr = [1, 4, 2, 3, 0 , 5]
sums = 7
tlist = []
for i in range(len(arr)):
for j in range(len(arr)-1):
if (i!=j) and ((arr[i] + arr[j+1]) == sums):
if (i,j+1) not in tlist and (j+1,i) not in tlist:
tlist.append((i,j+1))
print("index ->",i," ",j+1)
print("sum=", i+j+1)
output:
index -> 1 3
sum= 4
index -> 2 5
sum= 7
You could use itertools for easily checking sum for combinations like,
>>> import itertools
>>> num = 7
>>> for a,b in itertools.combinations(arr, 2):
... if a + b == num:
aindex, bindex = arr.index(a), arr.index(b)
... indices_sum = aindex + bindex
... print('[element sum]: {} + {} = {} [indices sum]: {} + {} = {}'.format(a, b, a + b, aindex, bindex , indices_sum))
...
[element sum]: 4 + 3 = 7 [indices sum]: 1 + 3 = 4
[element sum]: 2 + 5 = 7 [indices sum]: 2 + 5 = 7
>>> arr
[1, 4, 2, 3, 0, 5]
You could take a different approach by calculating the difference then checking if each element is present in the first array or not.
arr = [1, 4, 2, 3, 0, 5]
the_sum = 7
diff = [the_sum - x for x in arr]
for idx, elem in enumerate(diff):
try:
index = arr.index(elem)
sum_of_indices = idx + index
print("{} + {} = {}".format(idx, index, sum_of_indices))
except ValueError:
pass
output
1 + 3 = 4
2 + 5 = 7
3 + 1 = 4
5 + 2 = 7
To remove the duplicates, its always easy to take a frozenset of the indices tuple
a = [(2,1), (1,2), (3,2), (2,3)]
{frozenset(x) for x in a} # {frozenset({2, 3}), frozenset({1, 2})}

python inward number spiral going backwards

I am trying to make a spiral that looks like this
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
this is my code and it prints out a matrix but the numbers start on the outside and work in which is the opposite of what I want. How can I change this?
def main():
spiral = open('spiral.txt', 'r') # open input text file
dim = int(spiral.readline()) # read first line of text
num = int(spiral.readline()) # read second line
spiral.close()
print(dim)
if dim % 2 == 0: # check to see if even
dim += 1 # make odd
print(dim)
print(num)
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, 1
m = [[0 for i in range(dim)] for j in range(dim)]
for i in range(dim + dim - 1):
for j in range((dim + dim - i) // 2):
x += dx[i % 4]
y += dy[i % 4]
m[x][y] = c
c += 1
print(m)
print('\n'.join([' '.join([str(v) for v in r]) for r in m]))
print(num)
main()
replace
m[x][y] = c
by
m[x][y] = dim**2 + 1 - c
which basically counts backwards. Also you might want to have proper spacing with:
print('\n'.join([' '.join(["{:2}".format(v) for v in r[::-1]]) for r in m]))

Categories