I want to update the list used in the for loop statement as it is being appended with new values within the loop.I know this code wont update the list but I am not able to find a way to do so. I hope to required output might explain it better
INPUT
list=[1,2,3]
count=0
for x in list:
if int(len(list))>10:
break
else:
count=count+1
x=x+10
if x>3:
list=list+[x]
print "list = %r" %list
print "count = %r" %count
OUTPUT
list = [1, 2, 3, 11, 12, 13]
count = 3
Required OUTPUT
list = [1, 2, 3, 11, 12, 13, 21, 22, 23, 31]
count = 10
I suggest you use a while loop instead of a for, which saves the need of the break keyword :
l=[1,2,3]
count = len(l) # There are already len(l) elements in the list
pos = 0
while len(l) < 10:
count += 1
x = l[pos]
l.append(x+10)
pos += 1
print "list = %r" %l
print "count = %r" %count
Which gives the output :
list = [1, 2, 3, 11, 12, 13, 21, 22, 23, 31]
count = 10
Also, you can notice that i renamed the list variable to l, to prevent any confusion between the type list and the variable itself.
I used append to add elements at the end of the list.
Hope it'll be helpful.
two problems here:
first: the if x>3: test. (Why did you include that?)
second when you have a for statement, it loops on the values present initially only.
This should work:
l = [1,2,3]
count = 0
while len(l) < 10:
l.append(l[count]+10)
count += 1
Related
I have the following code:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
for num in my_list:
val = num
ans = val*128
highest = (ans)
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
I need to have code where if the answer is greater than the answer already stored in highest, it is overwritten. With the final return being just the highest result, in this case it would be the 11th result.
You need a few things:
Make sure to move the highest variable outside the loop. If not, it would be replaced each time the loop runs, and you never find out what is the highest value in your list.
And the second, which might not be completely necessary in your case, but it might be helpful, is to use float("-inf") as the first assigning value to the highest variable. This makes sure that you have not ignored any element in your list (there might have been negative values in the list, too)
Make sure that return is out of the for loop and at the end of the function.
Here is what I have come up with:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
highest = float("-inf")
for num in my_list:
val = num # This is not necessary. You can simply replace `num` with `val` in the for loop itself.
ans = val*128
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
Output
10240
The output is as it should be: The highest value in your list is 80. Mutliplying this number by 128 results in 10240.
To find the highest number you should create a variable to store the highest result so far and compare to it every new result.
Here I defined the variable highest before the loop and set its value to 0
I'm not sure why you're doing the multiply by 128 but I left it there for you.
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128():
highest = 0
for num in my_list:
ans = num*128
if ans > highest:
highest = ans
return highest
print(multiplied128())
BTW, the same result can be achieved with the built-in function max:
print(128*max(my_list))
Suppose I have a list:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
I want to write a program that prints out all the elements of the list that are less than 10.
Actually its pretty simple I got this program but, I need to do it in a single line and I've no idea how to do that. Need some help with this.
print [x for x in a if x < 10]
Take a further look at lambda functions, I feel this is what you are looking for.
So in order to print something out of a list that is less than 10 In the same line, first you need to create a list:
numbers = []
loop through every single element of the list
for i in a:
And then you need a If statement to check if the element is less than 10
if i < 10:
Append the number to the list
numbers.append(str(i))
Join the results together:
result = " ".join(numbers)
And lastly printing it out
print(result)
And if you combine everything together, this is what you should get:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numbers = []
for i in a:
if i < 10:
numbers.append(str(i))
result = " ".join(numbers)
print(result)
The result should be:
1 1 2 3 5 8
Assume I have a list [12,12,12,12,13,13,13,13,14,14,14,14,14,14,14,15,15,15, etc]
I would like my result to be the following:
[12,12,12,13,13,13,14,14,14,15,15,15]
The number of identical numbers in the first list can vary, but I want to get triplets for each range of the identical numbers. I assume I could iterate through the list starting from the first number (12) and get the first 3 identical numbers (12,12,12), and then compare the numbers and once the number 12 changes to 13, get the next 3 numbers (13,13,13), and so on. But I cannot think of a good approach to do it correctly. Thank you for any suggestions.
I would use itertools.groupby() to isolate the strings of identical numbers, then use a list comprehension to create the triplets:
import itertools
some_list = [12,12,12,12,13,13,13,13,14,14,14,14,14,14,14,15,15,15,]
updated_list = [i for k,_ in itertools.groupby(some_list) for i in [k]*3]
assert updated_list == [12,12,12,13,13,13,14,14,14,15,15,15]
updated_list = []
curr_number = some_list[0]
curr_count = 0
for n in some_list:
if n == curr_number
curr_count += 1
if not (curr_count > 3):
updated_list.append(n)
else:
curr_number = n
curr_count = 1
updated_list.append(n)
Seems as a set approach is a bit faster than itertools. If you need it sorted, less but still faster.
A = [12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15]
def with_set(A):
A = set(A)
return list(A) * 3
import itertools
def with_iter(A):
return [i for k,_ in itertools.groupby(A) for i in [k]*3]
import timeit
print("Result with set: ", timeit.timeit(lambda:with_set(A),number = 1000))
print("Result with iter: ", timeit.timeit(lambda:with_iter(A),number = 1000))
Result with set: 0.008438773198370306
Result with iter: 0.018557160246834882
Below line of code is self explanatory:
A = [1, 2, 3, 4, 1, 4]
A = list(set(A)) #removes duplicates
A *= 3 #multiplies the unique list 3 times
print sorted(A) # makes a new sorted list
I would like to remove elements which are multiples of 5 from a list.
In my code below "######" I tried >> number_list.pop(i) and it showed index out of range error. I also tried >> return number_list.pop(i) and it only seems to remove the first number which is 25. Codes in main() is given and I need to complete the function. I could easily do it by creating another list and store the numbers that are not multiples of 5 however it appears that I have to use the given list "numbers" to figure it out. I would be appreciated if I can get some help with this coding. Thank you.
ps. using python 3.5
def main():
numbers = [25, 5, 9, 10, 15, 8]
print(numbers)
remove_multiples(numbers, 5) # remove multiples of 5
print("Numbers left", numbers)
def remove_multiples(number_list, multiples_of):
for i in range(len(number_list)):
if number_list[i] % multiples_of == 0:
###################
return number_list
main()
def remove_multiples(number_list, multiples_of):
pivot = 0
for i,value in enumerate(number_list):
if value % multiples_of != 0:
number_list[pivot] = value
pivot += 1
del number_list[pivot:]
return number_list
move the available element to front, and delete the rest
def main():
numbers = [25, 5, 9, 10, 15, 8]
print(numbers)
remove_multiples(numbers, 5) # remove multiples of 5
print("Numbers left", numbers)
def remove_multiples(number_list, multiples_of):
for i in number_list:
if i % multiples_of == 0:
number_list.remove(i)
return number_list
main()
Hope that's what you're looking for.
Removing an element from a list you're currently iterating over is never a good idea.
Instead, create and return a new list without the unnecessary elements using list comprehension:
def remove_multiples(number_list, multiples_of):
return [num for num in number_list if num % multiples_of != 0]
print remove_multiples([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2)
>> [1, 3, 5, 7, 9]
I have a list defined as:
pad = [unhexlify('00' * (16-j) + ('%02d' % j) * j) for j in range(1, 17)]
This constructs a pad list for a padding oracle attack. Due to how this attack works I need to cycle through elements 2-16, then if I don't get a hit go back and try the 1st element. Here is the loop:
for padsel in pad: #increment pad
print(str(hexlify(padsel)) + "- selected pad")
for i in range(256): #increment guess
g = unhexlify("000000000000000000000000000000" + "{:02x}".format(i))
print(str(hexlify(g)) + "- guess")
if attack(g,padsel,ct_prev, ct_target):
m2 += "{:02x}".format(i)
print(m2)
break
else:
continue
m2 = m2[::-1]
print(m2 + "- m2")
How do I change the outer loop definition to do this?
Pseudo code:
for padsel in pad (items 2-16):
do stuff until hitting a break condition
else:
do stuff on element 1
Thanks.
Rather than use an else clause on the for loop, just modify the iterable (list) that you iterate over:
for padsel in (pad[1:16] + [pad[0]]):
print(str(hexlify(padsel)) + "- selected pad")
for i in range(256): #increment guess
g = unhexlify("000000000000000000000000000000" + "{:02x}".format(i))
print(str(hexlify(g)) + "- guess")
if attack(g,padsel,ct_prev, ct_target):
m2 += "{:02x}".format(i)
print(m2)
break
else:
continue
m2 = m2[::-1]
print(m2 + "- m2")
Using an else clause would require duplication of the code in the body of the for loop, or refactoring the body into a function so that duplication is not required. But, since the first item is processed in the same way as the other items, the simplest way is to organise for it to be processed last by iterating over items 2 through 16 and then item 1 if required.
>>> l = range(1,16+1)
>>> print l
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print l[1:16] + [l[0]]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1]
The last statement effectively moved the first element of the list to the end of the list. If you don't mind if the list is modified, or even prefer it, you can do this:
>>> l = range(1,16+1)
>>> l.append(l.pop(0))
>>> print l
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1]
If you need to keep original list untouched, try:
for item in items[1:16]: # iterate through elements 1-17 (list indexes starts at 0
do stuff
if condition:
break
else: # else in for loops will be run if loop ended normally (w/o `break`)
do stuff with items[0]
Keep in mind, that slicing lists (list[x:y]) will create a copy of existing list. This can become a memory issue, when used with huge lists.