How should I write the code with the following problem?
Implement the function reverse_print(lst) that prints out the contents of the given list ‘lst’
in reverse order. For example, given a list [3, 6, 2, 1], the output should be 1, 2, 6, 3 (vertical
printout allowed). For this code, you are only allowed to use a single for-loop. Without String Method
Also Not using Print[::-1]
Assuming you are not allowed to just call list.reverse() you can use range with a negative step to iterate the list in reverse order:
def reverse_print(lst):
out = []
for i in range(len(lst) - 1, -1, -1):
out.append(lst[i])
print(*out, sep=", ")
inp = [1, 2, 3, 4]
reverse_print(inp)
Output: 4, 3, 2, 1
You may try something like this
def reverse_print(lst):
rev = [lst[abs(i-l)-1] for i in range(l)]
return rev
lst = [3,6,2,1]
l = len(lst)
print(reverse_print(lst))
Related
I found this code from stackoverflow ... and wondering how can I move index position that I want.
I tried to use for loop and [::1]. And by making, len(a)*[0]...I couldn't make it.
Is there any way to fix items on its position in list?
Second, without using method below, is there another way to reorder items in list?
'''
mylist=['a','b','c','d','e']
myorder=[3,2,0,1,4]
'''
a = [1,2,3,4,5,6,7]
b = ((a+a[:0:-1])*len(a))[::len(a)][:len(a)]
[1, 7, 2, 6, 3, 5, 4] <=b
[7, 1, 6, 2, 5, 3, 4] <= the result i want
Thanks in advance.
I'm not sure if this is what you want:
someList = [1,2,3,4,5,6,7]
orderedList = sorted(someList)
reversedOrderedList = orderedList[::-1]
finalList = []
for i in range(len(someList)):
if i % 2 == 0:
finalList.append(reversedOrderedList[i//2])
else:
finalList.append(orderedList[i//2])
print(finalList)
output:
[7, 1, 6, 2, 5, 3, 4]
if so, you can write it in shorter way (without reversedOrderedList):
someList = [1,2,3,4,5,6,7]
orderedList = sorted(someList)
finalList = []
for i in range(len(someList)):
if i % 2 == 0:
finalList.append(orderedList[-1-i//2])
else:
finalList.append(orderedList[i//2])
print(finalList)
and from here you can write it without if statement:
someList = [1,2,3,4,5,6,7]
orderedList = sorted(someList)
for i in range(len(someList)):
finalList.append(orderedList[((-1)**(i%2+1)-1)//2 + ((- 1)**(i%2+1))*(i//2)])
print(finalList)
It is not pretty but after that you can easily write a generator.
Zip the list with its reversed version, flatten it and take the first half:
from itertools import chain
a = [1,2,3,4,5,6,7]
b = list(chain.from_iterable(zip(a[::-1], a)))
print(b[:len(b) // 2])
Output
[7, 1, 6, 2, 5, 3, 4]
I am trying to go through a list and have each object in that list compared with the others, and all repetitions of it replaced with something else.
>>> t = [1, 2, 1, 1, 2, 2, 4, 4]
>>> for i in range(len(t)):
num = t[i]
if num in t[i+1:]:
num = 'cherry'
This is not turning the repeated ints into 'cherry'. I know that I am referring to them correctly as I put print(num) in place of num = cherry and it is printing what I want. It will not reassign them, though. What am I doing wrong?
You should make the list a set because sets are unordered collections of unique elements and are great for removing duplicates from a sequence
To make a set use either the set() function like in the code below or use curly braces {} like the output
t = [1, 2, 1, 1, 2, 2, 4, 4]
x = set(t)
print(x)
#Output
{1, 2, 4}
I have a list that only includes positive integers:
my_list = [1, 2, 4, 7, 9, 10, 15, 16]
The list is sorted.
What would be the most "pythonic" way to check whether the list contains any sequence of x consequtive number? It shouldn't matter whether the sequence starts at the beginning of the list, or ends at the end of the list - as long as it's in the list, it should return true. For instance, if I wanted to check if the following list contains a 4-number sequence:
my_list = [1, 3, 4, 5, 6, 8, 10]
It should return true due to [3, 4, 5, 6]
I have seen multiple StackOverflow questions about "finding number sequences in lists", however none of them dealt with looking for a sequence in only a portion of the list. (What I found was useful only if the goal was to check whether the entire list is sequential.)
Here's a one liner:
def has_sequence(L, seq_len):
return any(list(L[i:i+seq_len]) == list(range(L[i],L[i]+seq_len))
for i in range(len(L)-seq_len+1))
def findRun(L, n):
runlen = 0
for i in range(1, len(L)):
if L[i] == L[i-1]+1:
runlen += 1
else:
runlen = 0
if runlen == n-1:
print("Found a run starting at", i-n+1)
Output:
In [451]: L = [1, 3, 4, 5, 6, 8, 10]
In [452]: findRun(L, 4)
Found a run starting at 1
You can try this:
after grouping them with the difference, you just check if any of the groups contains your preferred number of consecutive sequence(in this case 4).
from itertools import groupby
from operator import itemgetter
my_list = [1, 3, 4, 5, 6, 8, 10]
check = False
for key, group in groupby(enumerate(my_list), lambda (i, val): i - val):
g = map(itemgetter(1), group)
if len(g) == 4:
check = True
print(check)
True
I hope this is what you looking for.
I was trying to print a list in backwards order using a for loop, however my code only prints of a 1, any ideas why?
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(len(sorted_list)-2,-3,-1):
des_list.append(sorted_list[i-2])
des_list.append(sorted_list[i - 1])
des_list.append(sorted_list[i])
des_list.append(sorted_list[i+1])
print(des_list)
It would probably be easier to store the chunks of data into objects. That way, you can just call reversed() on the list of objects and handle the data that way.
If you want to keep the list in the format you have, you can loop through the list in "chunks", like this: for i in range(0, len(sorted_list), 4):.
So, for every 4 elements in the list, grab the chunk of of data using list slicing notation: sorted_list[i:i+4] and insert it to the front of the destination list.
Putting that together, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
des_list.insert(0, sorted_list[i:i+4])
print(des_list)
That will output this: [['sod', 3, 1, 0], ['tim', 5, 3, 1], ['bob', 0, 0, 10], ['jill', 4, 1, 0], ['jack', 4, 3, 1]].
Keep in mind that that code will give you a list of lists, because sorted_list[i:i+4] returns a list, which is why it might be easier to use objects instead.
If you don't want to have a list of lists, you can reverse the sliced list, loop through each element in the reversed sliced list, and insert it one at a time to the destination list.
Doing that, you get this code:
sorted_list = ["jack",4,3,1,"jill",4,1,0,"bob",0,0,10,"tim",5,3,1,"sod",3,1,0]
des_list = []
for i in range(0, len(sorted_list), 4):
for j in reversed(sorted_list[i:i+4]):
des_list.insert(0, j)
print(des_list)
Which outputs this: ['sod', 3, 1, 0, 'tim', 5, 3, 1, 'bob', 0, 0, 10, 'jill', 4, 1, 0, 'jack', 4, 3, 1]
for i in range(1, len(A)):
A[i] = A[i-1] + A[i]
You can't do that with a list comprehension as they don't allow assignments.
You can use a simple generator function:
def func(lis):
yield lis[0]
for i,x in enumerate(lis[1:],1):
lis[i] = lis[i-1] + x
yield lis[i]
>>> A = [1, 2, 3, 4, 5, 6, 7]
>>> list(func(A))
[1, 3, 6, 10, 15, 21, 28]
though less efficient, this does give the desired output. But I think I'm getting closer to O(n**2) on this one.
A = [sum(A[:i+1]) for i, _ in enumerate(A)]
afaik this can't be done with a list comprehension the way you want to. I would suggest using the for loop version you've provided. Even if it was possible with a list comprehension, there's no point when you can just modify the list in place.
Use B (another temporary variable).
This should do the trick.
def func(L):
it = iter(L)
v = it.next()
yield v
for x in it:
v += x
yield v
A = [1, 2, 3, 4, 5, 6, 7]
print list(func(A))
This creates an iterator that returns one value at the time. To get the full new list at once you need to use a list() call around the function call, like:
list(func(A))
This generator function should work on any iterable (also those that don't support getting value based on index, like L[0])
I don't think there's an efficient way to do this with a comprehension list.
A one-line solution use reduce:
>>> the_list = [1,2,3,4,5]
>>> reduce(lambda result, x: result+[result[-1] + x] ,the_list, [0])[1:]
[1, 3, 6, 10, 15]