Python operation data List in loop - python

I want to solve my programming problem, the problem goes like so:
input: 3 #if i input as first input example 3, output is [1, 2, 3]
[1, 2, 3]
input: 2 #2nd input example 2 output is [1, 2] + [1, 2, 3] = [2, 4, 6]
[2, 4, 3]
input: 6 #3rd input [2, 4, 6] + [1, 2, 3, 4, 5, 6] = [3, 6, 6, 4, 5, 6]
[3, 6, 6, 4, 5, 6]
My code:
while True:
a = input('Input : ')
n = range (1,a+1,1)
print n
Outputs:
Input : 3
[1, 2, 3]
Input : 2
[1, 2]
Input : 6
[1, 2, 3, 4, 5, 6]
How can I solve this problem?

Building on your existing code, I would use itertools.izip_longest (Python 2, for 3 use zip.longest):
>>> import itertools
>>> nxt = []
>>> while True:
a = input('Input : ')
n = range(1, a+1, 1) # could change to range(1, a+1)
nxt = map(sum, itertools.izip_longest(n, nxt, fillvalue=0))
print nxt
Which yields:
Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]

You can use map
result = []
while True:
a = input('Input : ')
n = range(1, a+1)
result = [(x or 0) + (y or 0) for x,y in map(None, n, result)]
print result
and result would be:
Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]

but i can not use external code
Then you can write some code that does exactly what izip_longest does with the zero padding when the new entry is lengthier than the previous result.
The sums are performed in a list comprehension where the values and indices from the input list are gotten by applying enumerate on the entry in the comprehension. Values from the accumulated list are indexed and added to new values at the same index:
tot = []
while True:
a = input('Input : ')
n = range (1,a+1,1)
x, y = len(tot), len(n)
if y > x:
tot[x:y] = [0]*(y-x) # pad the tot list with zeros
tot[:y] = [tot[i]+v for i, v in enumerate(n)]
print tot
Output:
Input : 3
[1, 2, 3]
Input : 2
[2, 4, 3]
Input : 6
[3, 6, 6, 4, 5, 6]
Input : 1
[4, 6, 6, 4, 5, 6]
Input : 0
[4, 6, 6, 4, 5, 6]

Related

how to input list dynamic in python

1 ) input: 3 , return [1, 2, 3]
then continue
2) input: 2, return [2, 4, 3]
then continue
3) input: 6, return [3, 6, 6, 4, 5, 6]
then continue
4) input: 1, return [4, 6, 6, 4, 5, 6]
then continue
5) input: 1, return [5, 6, 6, 4, 5, 6]
My code :
1)
list_num = [ int(i) for i in input('enter numbers divided by space ').split()]
print(list_num)
lst = []
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element
print(lst)
test_list1 = []
n2 = int(input("Enter number of elements2 : "))
for i2 in range(0, n2):
ele2 = int(input())
test_list1.append(ele2) # adding the element
print(test_list1)
res_list = [lst[i] + test_list1[i2] for i in range(len(lst))]
print(res_list)
but not dynamic
Your code 2 seems to be doing a pair-wise list addition.
But the computation of your res_list is using the i2 index, it should be just i.
Without the fix : [4, 5] plus [0, 1] gives [5, 6].
With the fix : [4, 5] plus [0, 1] gives [4, 6].

Find pairs of consecutive integers in array PYTHON

I'm trying to loop through an array and return an integer every time it shows up twice --- I've been trying to figure this out for days and really need some help
example:
input = [3, 4, 4, 4, 5, 6, 6, 5, 4, 4]
result = [4,6,4]
result=[]
def findPairs(input):
i = 0
while i < len(input):
for j in input:
if input[1]==input[2]:
result.append(j)
i += 1
print(result)
print (findPairs(input))
In response to the more recent clarifications:
def find_pairs(xs):
result = []
i = 0
while i < len(xs) - 1:
if xs[i] == xs[i + 1]:
result.append(xs[i])
i += 1
i += 1
return result
Testing:
>>> xs = [3, 4, 4, 4, 5, 6, 6, 5, 4, 4]
>>> find_pairs(xs)
[4, 6, 4]
Update: Minor off-by-one bug fix.
Try this method with list comprehensions -
import itertools
inp = [3, 4, 4, 4, 5, 6, 6, 5, 4, 4]
l = [i for i in zip(inp, inp[1:]) if i[0]==i[1]] #first get consecutive repeats
out = [k[0] for k, g in itertools.groupby(l)] #sequential grouping of repeated groups to count more than 2 occurances as a single one as well
print(out)
[4, 6, 4]

Count the number of times the positions of two lists have the same element

If you have two lists,
a = [1, 2, 3, 4, 5]
b = [1, 3, 2, 4, 7]
how can you count the number of times elements at a certain position coincide? For example 1 and 4 in the above example would have 2 cases of elements coinciding.
sum(a_ == b_ for a_, b_ in zip(a, b))
zip can give you the elements that share a position, and you can use sum to count the number of times they match:
a = [1, 2, 3, 4, 5]
b = [1, 3, 2, 4, 7]
print(sum(x == y for x, y in zip(a, b))) # 2
You can use below code and you will get positions which coincide and get sum of them as well.
a = [1, 2, 3, 4, 5]
b = [1, 3, 2, 4, 7]
print(len([i for i,val in enumerate(zip(a,b)) if val[0]==val[1]]))
to get positions you can use
print([i for i,val in enumerate(zip(a,b)) if val[0]==val[1]])
one more version:
a = [1, 2, 3, 4, 5]
b = [1, 3, 2, 4, 7]
print(sum(a[i] == b[i] for i in range(len(a))))
How about this?
# lists:
a = [1, 2, 3, 4, 5]
b = [1, 3, 2, 4, 7]
# initialize variables:
number_of_collisions = 0
# iterate over each element:
for i in range(len(a)):
if a[i] == b[i]:
number_of_collisions += 1
print(number_of_collisions)

how to create a list of values based on a index python

I have a list
input :
value = [1,2,2,1,1,3,1,3,4,4,5,5,4,6,6]
expected output:
[[1,2,3,1,1,3,1],[3],[4,4,5,5,4],[6,6]]
Explanation:
1) once i iterate over value list first element would we 1 index's of one are
[0 3 4 6] . i want to store start and end number of a index eg (value[ 0 : 6 ]) to a new list and remove from Existing one list looks like value= [3,4,4,5,5,4,6,6]
2) once i iterate on value next input would be 3 index of value 3 is [0] store it in a list and as follows
I have tried few lines of code
1) i have iterated a list with index and value with numpy i have found the index stored in a table
import numpy as np
final_list=[]
top_list=[1,2,2,1,1,3,1,3,4,4,5,5,4,6,6]
matched_input=[]
for i,j in enumerate(top_list):
if(len(matched_input)==0):
values = np.array(top_list)
matched_input= np.where(j == values)[0]
matched_input=np.array(matched_input).tolist()
final_list.append(top_list[matched_input[0]:matched_input[-1]+1])
#print matched_input
elif(len(matched_input)>0 and i not in range(matched_input[-1]+1)):
values= np.array(top_list[matched_input[-1]+1:])
matched_input_updated= np.where(j == values)[0]
matched_input_updated=np.array(matched_input_updated).tolist()
final_list.append(top_list[matched_input_updated[0]:matched_input_updated[-1]+1])
try this:
input = [1, 2, 2, 1, 1, 3, 1, 3, 4, 4, 5, 5, 4, 6, 6]
result = []
while len(input) > 0: # can be just while input
first_element = input[0]
last_index_of_first_element = len(input) - (input[::-1].index(first_element) + 1)
result.append(input[:last_index_of_first_element + 1])
input = input[last_index_of_first_element + 1:]
print(result)
Output:
[[1, 2, 2, 1, 1, 3, 1], [3], [4, 4, 5, 5, 4], [6, 6]]
basically, as long as there is input, I take the first element, then find it's last index (by reversing the list, finding the first index, and subtracting from the len), and then use slicing to extract the correct sublist and append to result.
Slight variation on the other answer, without modifying the input list:
value = [1, 2, 2, 1, 1, 3, 1, 3, 4, 4, 5, 5, 4, 6, 6]
next_idx = 0
value_rev = value[::-1]
result = []
while next_idx < len(value):
prev_idx = next_idx
next_idx = len(value) - value_rev.index(value[prev_idx])
result.append(value[prev_idx:next_idx])
print(result)
# [[1, 2, 2, 1, 1, 3, 1], [3], [4, 4, 5, 5, 4], [6, 6]]
from collections import defaultdict
value = [1,2,2,1,1,3,1,3,4,4,5,5,4,6,6]
d = defaultdict(list)
[d[v].append(i) for i, v in enumerate(value)]
i, out = 0, []
while i < len(value):
i2 = d[value[i]][-1]
out.append(value[i:i2+1])
i = i2 + 1
print(out)
Prints:
[[1, 2, 2, 1, 1, 3, 1], [3], [4, 4, 5, 5, 4], [6, 6]]

Algorithm to return a reordered range for data rendering

Here are examples:
given: 1,2,3 [list or range of numbers]
return: 2,1,3 [reordered list]
given: 1,2,3,4,5
return: 3 1 5 2 4
given: 1,2,3,4,5,6,7
return: 4 1 7 2 6 3 5 OR 4 7 1 5 3 2 6 or similar
given: 1,2,4,5,6,7,8,9
return: 5,1,9,3,7,2,8,4,6 or similar
In rendering you start with the center, then the most extreme cases, and become more and more detailed. This is NOT random. I'm in python, but theres got to be a name for this in comp sci. Help appreciated.
Edit to add
even case -
given: 1234
return: 2,1,4,3 OR 3,1,4,2 OR 2,4,1,3 OR 3,4,1,2
A valid, although ungraceful solution:
def sigorder(lst):
result = []
l = len(lst)
if l <= 2:
return lst
if l > 2:
result.append(lst[l/2])
result.append(lst[0])
result.append(lst[-1])
right = sigord(lst[l/2+1:-1])
left = sigord(lst[1:l/2])
result.extend(slicezip(left, right))
return result
Inner, recursive function:
def sigord(lst):
result = []
if len(lst) < 3:
return lst
else:
l = len(lst)
result.append(lst[l/2])
left = sigord(lst[0:l/2])
right = sigord(lst[l/2 + 1:len(lst)])
result.extend(slicezip(left, right))
return result
slicezip() (Note: conveniently handles the potential unevenness of the left/right lists automagically)
def slicezip(a, b):
result = [0]*(len(a)+len(b))
result[::2] = a
result[1::2] = b
return result
Outputs for lists length 4-9 :
[3, 1, 4, 2]
[3, 1, 5, 2, 4]
[4, 1, 6, 2, 5, 3]
[4, 1, 7, 2, 5, 3, 6]
[5, 1, 8, 3, 6, 2, 7, 4]
[5, 1, 9, 3, 7, 2, 6, 4, 8]
This should do it:
def extreme_cases(upd_itrr, new_itrr):
new_itrr.append(min(upd_itrr))
new_itrr.append(max(upd_itrr))
upd_itrr.remove(min(upd_itrr))
upd_itrr.remove(max(upd_itrr))
if len(upd_itrr) >= 2:
extreme_cases(upd_itrr, new_itrr)
return upd_itrr, new_itrr
def reordered_range(itr):
new_itr = []
center = 0
if len(itr) % 2 != 0:
center = itr[len(itr) // 2]
elif len(itr) % 2 == 0:
center = itr[(len(itr) // 2) - 1]
new_itr.append(center)
upd_itr = itr[:]
upd_itr.remove(center)
upd_itr, new_itr = extreme_cases(upd_itr, new_itr)
if upd_itr:
new_itr.append(upd_itr[0])
return new_itr
print(reordered_range([1, 2, 3]))
print(reordered_range([1, 2, 3, 4]))
print(reordered_range([1, 2, 3, 4, 5]))
print(reordered_range([1, 2, 3, 4, 5, 6, 7]))
print(reordered_range([1, 2, 4, 5, 6, 7, 8, 9]))
Output:
[2, 1, 3]
[2, 1, 4, 3]
[3, 1, 5, 2, 4]
[4, 1, 7, 2, 6, 3, 5]
[5, 1, 9, 2, 8, 4, 7, 6]
Another solution:
import numpy as np
from copy import copy
def bisecting_order(lst):
# bisecting order of an unordered list
result = []
l = len(lst)
if l < 3:
return lst
result.append(closest(lst,np.mean(lst)))
result.append(min(lst))
result.append(max(lst))
# get bisections
while len(result)!=len(lst):
temp_list = copy(result)
temp_list.sort()
for i in xrange(len(temp_list)-1):
newnum = closest(lst,np.mean([temp_list[i],temp_list[i+1]]))
if newnum in result:
continue
else:
result.append(newnum)
return result
def closest(mylist,mynum):
return min(mylist, key=lambda x:abs(x-mynum))

Categories