I want to limit the size of a list in python 2.7 I have been trying to do it with a while loop but it doesn't work
l=[]
i=raw_input()//this is the size of the list
count=0
while count<i:
l.append(raw_input())
count=count+1
The thing is that it does not finish the loop. I think this problem has an easy answer but I can't find it.
Thanks in advance
I think the problem is here:
i=raw_input()//this is the size of the list
raw_input() returns a string, not an integer, so comparisons between i and count don't make sense. [In Python 3, you'd get the error message TypeError: unorderable types: int() < str(), which would have made things clear.] If you convert i to an int, though:
i = int(raw_input())
it should do what you expect. (We'll ignore error handling etc. and possibly converting what you're adding to l if you need to.)
Note though that it would be more Pythonic to write something like
for term_i in range(num_terms):
s = raw_input()
l.append(s)
Most of the time you shouldn't need to manually keep track of indices by "+1", so if you find yourself doing it there's probably a better way.
That is because i has a string value type, and int < "string" always returns true.
What you want is:
l=[]
i=raw_input() #this is the size of the list
count=0
while count<int(i): #Cast to int
l.append(raw_input())
count=count+1
You should try changing your code to this:
l = []
i = input() //this is the size of the list
count = 0
while count < i:
l.append(raw_input())
count+=1
raw_input() returns a string while input() returns an integer. Also count+=1 is better programming practice than count = count + 1. Good luck
Related
The function should accept a single list as a parameter. The function should return an integer value as the result of calculation. If there are no positive and even integer values in the list, your function should return 0.
My current code:
def main():
print (sum_positive_even([1,2,3,4,5]))
print (sum_positive_even([-1,-2,-3,-4,-5]))
print (sum_positive_even([1,3,5,7,9]))
def sum_positive_even(list):
for num in list:
if num < 0:
list.remove(num)
for num in list:
if num % 2 == 1:
list.remove(num)
result = sum(list)
return result
main()
The output should be like:
6
0
0
I'm confused where I should put the 'return 0'.
Thanks TA!
Deleting from a list while you iterate over it is a Bad Idea - it's very easy to get hard-to-track-down bugs that way. Much better would be to build a new list of the items you want to keep. You don't need a special case of returning 0; the general approach should be able to handle that.
Also, it's better not to use list as a variable name in Python, because that's the name of a built-in.
A modification of your approach:
def sum_positive_even(lst):
to_keep = []
for num in lst:
if num > 0 and num % 2 == 0:
to_keep.append(num)
return sum(to_keep)
Since the sum of an empty list is 0, this covers the case where there are no positive even numbers.
I've tried to solve my problem by googling, but every time someone has the same problem also has complicated code. I a noob and I have no idea why It keeps having an error called "TypeError: not all arguments converted during string formatting" Even though I tried converting some of the variables to int. (I'm probably solving it the wrong way). Can someone give a heads up without giving me the answer?
x = range(2, 20)
number = 0
y = raw_input()
flag = True
while flag == True:
for elem in x:
if y % elem == 0:
print elem
else:
flag = False
All you need to do is convert the raw_input() into integer using int() function. That's will solve the program. You can do this by:
y = int(raw_input())
The problem is that, when you read an input with raw_input(), you receive a string, and you are treating the variable y later on your code as an integer (at if y % elem == 0:). You need to cast the input to an integer, which can be done substituting this line
y = raw_input()
for this line:
y = int(raw_input())
def bruteForce( dictionary = {}):
key = 0
for i in range(len(dictionary)):
keyRank = 0
for k in range(68719476736):
attempt = decrypt(dictionary[i], k)
if(i != attempt):
keyRank = 0
break
else:
keyRank += 1
key = k
print 'key attempt: {0:b}'.format(key)
if(keyRank == len(dictionary)):
print 'found key: {0:b}'.format(key)
break
The key is 36 bits
I get a memory error on the for k in range() line of code
Why is this a memory issue? Does python build an actual list of ints before running this line? Is there a better way to write this loop?
I'm brand new to Python and this wouldn't be a problem in C or Java.
This is a known-plaintext/ciphertext attack. dictionary is a mapping of P:C pairs.
Its on a VM, I can up the memory if needed, but want to know both why its failing and a code-based workaround or better idiomatic approach.
In python 2, range() will build the entire list in memory.
xrange() is a sequence object that evaluates lazily.
In python 3, range() does what xrange() did.
I am having a problem with an xor search.
I have an array composed of binary values. My list contains 1000 distinct binary values, and I want to time how long it takes for a double loop to find an element in the list. Therefore for a double loop search, I expect it to go through the loop [(1) + (2) +(3)+...+(1000)] = 500500 times. [n(n+1) / 2]
I use the bitwise_xor in the following code
from numpy import bitwise_xor
count = 0
for word1 in listOutTextnoB:
for word2 in listOutTextnoB:
count+=1
if bitwise_xor(word1,word2)==0:
break
print "count"
Unfortunately, when I print count, I get count = 1,000,000
If I change the if statement to
if bitwise_xor(word1,word2):
break
count is 1000
I also tried to do:
if word1^word2==0:
break
but it gives me "TypeError: unsupported operand type(s) for ^: 'str' and 'str'"
A working example would be:
1101110111010111011101101110110010111100101111001 XOR 1101110111010111011101101110110010111100101111001
it should give me 0 and exit the inner loop
What is wrong with code?
^ works on integers, not arrays, so that is not surprising.
I don't know why you used strings but:
from numpy import bitwise_xor
listOutTextnoB = range(1000)
count = 0
for word1 in listOutTextnoB:
for word2 in listOutTextnoB:
count+=1
if bitwise_xor(word1,word2)==0:
break
print "count", count
prints
count 500500
as you predict.
EDIT: yes, you should be doing
if int(word1) ^ int(word2) == 0:
break
bitwise_xor is actually returning 'NotImplemented' for every string, string input.
Your error shows the problem: the values in your list are strings, not numbers. I'm not sure what bitwise_xor does to them, but I'm pretty sure it won't convert them to numbers first. If you do this manually (bitwise_xor (int (word1), int (word2))), I think it should work.
based on this function. I'm trying to create two empty arrays (one for x and other for y), which later I will use to plot in python. But before anything this is what I have so far...
import math
x1=-2.0
x2=2.0
arr1 = []
arr2 = []
i=0
n=10
delta=(x2-x1)/n
for i in range (0,n+1):
x=x1+delta*i
arr1.append(x)
print arr1
# I have not called the w function yet
the code above creates a list of 10 numbers for now to keep it simple. Then it will send the elements of the array to the function below and compute the equation with certain numbers(infinite loop).
#This function will create the array list for y
import math
def w(x, limit):# the limit here to compare when the number is really small
suma = 0.0
sumb = 0.0
m=1
x=0
suma=suma+((1/(math.pow(2,m))*(math.sin(math.pow(2,m)*x)))
sumb=suma+((1/(math.pow(2,m+1))*(math.sin(math.pow(2,m+1)*x))) # I'm having a
#syntax error
#here
x+=0
if (abs (suma-sumb)<limit):
break:
else m+=1:
if (m<20):
break:
I will appreciate any help with my syntax errors or any suggestion. I just hope I was clear enough.
Thanks ahead of time
The syntax error is actually on the previous line, where the parenthesis are not balanced. You need an extra ) at the end of that line (and at the one you indicated as giving an error too btw).
There are also a few other issues
suma is set to zero, so suma = suma + ... is the same as suma = ..., but I'm guessing you still need to add while loop before this line.
On the line indicated, you have sumb = suma +, which is probably a copy/paste mistake.
The code block starting at x+=0 is indented by only 3 spaces instead of 4. This is probably not the case in your actual code, but if it is, Python will complain about that too.
else m+=1: should be else: m+=1 (colon directly after else, not at the end of the line.
break: should just be break (without to colon).