I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line if x == a[i]: when a number is not in the list.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
If there is no element in the list, then your i gets bigger and bigger until it becomes i = len(a). At this point a[i] throws an IndexError since you went above the list size. Simple fix would be to use while i < len(a): instead of while found == false: since you break the loop at x == a[i] anyway.
That's because you are going outside the bounds of the list.
You should add a check so you can return when i > len(a).
You can also use a for loop to avoid the index error, try this
def is_member(x):
a = [1,5,3,9,4,100]
for i in range(len(a)):
if x == a[i]:
return True
return False
You need to add a condition that if (i == len(a)-1): return False.
Because the index can not exceed the length of list a.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
found = False
while found == False:
if i >= len(a):
return False # end of list reached
if x == a[i]:
found = True
break
i += 1
if found == True:
return "True"
else:
return "False"
to handle end of list, a piece of code has been added
In fact you do not another variable like Found, you can do it in below way.
def is_member(x):
a = [1,5,3,9,4,100]
i = 0
while True:
if i >= len(a):
print 'test'
return False # end of list reached
if x == a[i]:
return True
i += 1
Try something like this instead:
def is_member(x):
a = [1,5,3,9,4,100]
for i in a:
if i == x:
return "True"
return "False"
Here we iterate over a, and if any member == x we return "True" right away. If we have not returned by the end of the loop then the element is not present.
Related
I'm trying to finish an assignment but everything I have tried so far has failed.
def valid_format(s):
pass
z = introcs.count_str(s,',')
x = introcs.split(s,',')
y = introcs.find_str(s,',')
if len(s) >= 2:
if s[0] == '0':
return False
if len(s) <= 3:
if introcs.isdigit(s):
x = int(s)
if x >= -1 and x <= 999:
if z == 0:
return True
else:
return False
else:
return False
if len(s) >= 4 and len(s)<= 7:
if introcs.isdigit(s):
x = int(s)
if x >= 999 and x <= 1000000:
return True
else:
return False
else:
return False
It looks like I'm not very good with if's statements since every time I try something new, it ends up giving me the same result. The code works(?) until I try numbers with comma (1,230 for example). Any tips and explanations of what I'm doing wrong or what I should change will be greatly appreciated!
Edit: Sorry for not providing enough details. The function needs to return True if s is a valid numerical string and it has to be less than 7 characters. I'm having difficulty with the commas. I get the opposite answer(either True or False)
For example:
I get True when It should be False
valid_format('2389')
True
But False when it should be True
valid_format('2,389')
False
I need this type of result:
valid_format('2,389')
True
valid_format('32,45')
False
count=0
for i in range(len(s)-1,-1,-1):
count+=1
if count%4==0: #make sure every 4th char is a ','
if s[i]==',':
pass
else:
return False
else:
if ord(s[i])-ord('0')<0 or ord(s[i])-ord('0')>9: #check if char is valid 0-9 using ascii arithmetic
return False
else:
pass
if i==0:
if ord(s[i])-ord('0')>9 or ord(s[i])-ord('0')<1: #check first digit is valid 1-9
return False
return True
have 2 functions. first one generates a list and the second one checks if theres duplicates. if theres duplicates it returns True
so i want to call function 2 from function 1 and if it returns true do something
heres my code
import random
def x(list):
for i in range(len(list)):
count = 0
for k in range(len(list)):
if list[i] == list[k]:
count += 1
if count > 1:
return True
if count == 1:
return False
def generated_list(N):
list = []
for i in range(N):
list.append(random.randint(1, 365))
x(list)
if generated_list(25) is True:
print('is true')
There were some logical errors, check this one :
import random
def check_duplicate(numbers):
for i in range(len(numbers)):
count = 0
for k in range(len(numbers)):
if i == k:
continue
if numbers[i] == numbers[k]:
count += 1
if count > 1:
return True
return False
def generated_list(n):
numbers = []
for i in range(n):
numbers.append(random.randint(1, 365))
return check_duplicate(numbers)
if generated_list(25) is True:
print('is true')
Also, avoid reserved keyword for naming your variables.
For context, I am trying to solve Project Euler problem 3 using Python:
What is the largest prime factor of the number 600851475143?
As a first step to this, I am trying to write a function that returns whether or not a number is prime as a Boolean. I made a first attempt, and checked out how this has been written previously. I have ended up with the following code:
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i = i + 1
else:
return True
For some reason, the code above does not work perfectly. For example, isprime(99) would return True.
Please, can someone help me understand why this isn't working? I am trying to avoid just copying and pasting someone else's code, as I want to understand exactly what is going on here.
To me, it looks like the issue is with the final else statement. I say this because the logic reads "in the event that x%i == 0, this number is not prime" but it doesn't explicitly say what to do in the event that no x%i iterations == 0.
Any help on this would be appreciated! I'm not necessarily looking for the cleanest, neatest way of doing this, but more just trying to first make this code work.
Just to show an alternative, what you could do is checking from number 2 to your number if the operation (x % i) is equal to zero. If it never happend, it will be a prime.
def isprime(x):
# check for factors
for i in range(2,x):
if (x % i) == 0:
return False
else:
return True
print(isprime(99))
Try this :
def isprime(x):
limit = x**0.5
i = 2
if x <= 2:
return False
while i <= limit:
if x%i == 0:
return False
i = i + 1
return True
I've changed many things. have this point in your mind that there is no need to else clauses when you return at the end of if block.
you need to tell what happens when x%i==0 condition not met and the value of i remain constant and also need to see when all conditions not met, then it is a prime
# your code goes here
def isprime(x):
limit = x**0.5
i = 2
if x < 2:
return False
elif x == 2:
return True
else:
while i <= limit:
if x%i == 0:
return False
i+=1
return True
print(isprime(144)) # false
print(isprime(99)) # false
print(isprime(131)) # true
I'm doing a python challenge and I cannot go further...
I need to verify if the numbers in the vetor are primes.
Like:
vetor = [2,5,12]
2 is prime(TRUE)
5 is prime(TRUE)
12 not prime(FALSE)
This is my code until now:
vetor = [ ]
def is_prime():
x = vetor
if x == 1:
return False
elif x == 2:
return True
for i in range(x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
return is_prime()
print(number())
But doing this, Python returns me:
TypeError: 'list' object cannot be interpreted as an integer
What could I do to manipulate that data inside my list?
Try this:
vetor = [ ]
def is_prime(x):
if x == 1:
return False
elif x == 2:
return True
for i in range(1, x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
for x in vetor:
if is_prime(x):
print(x, 'is prime')
else:
print(x, 'is not prime')
print(number())
You're trying to evaluate the value of a 'whole' list (datatype) against an integer (datatype) value (1 or 2), and then you're using the whole list as it were a single integer value again. You should address every single value in the list and check it separately.
You can do it, per example, with a for-each loop:
for value in vetor:
#do wahtever you want with 'value'
I would recommend making is_prime accept an integer as an argument. Then it's just a pure function that takes in an integer and outputs a boolean value.
I also notice a problem in your is_prime implementation. In your if-else statement, the function returns no matter what during that statement, so the for loop will always stop after only one iteration. You should only return False if all of the divisors you check do note divide the number:
import math
def is_prime(n):
if n <= 1:
return False
for d in range(2, int(math.sqrt(n))+1):
if n % d == 0:
return False
return True
# >>> is_prime(7)
# True
# >>> is_prime(8)
# False
I also think it would be clearer to write your program iteratively, rather than recursively (your number function currently calls itself). This might look like
vector = []
while True:
value = int(input('Write an integer bigger than 1: '))
if value == 0:
break
elif value > 0:
vector.append(value)
for n in vector:
print(n, is_prime(n))
# prints something like:
#
# 1 False
# 2 True
# 11 True
After looking around on SO for similair questions and not finding any, I will give it a shot by asking it here. I'll try to be as specific as possible.
Using Python, I am trying to make a piece of code that runs through all possible Harshad numbers and give back an [i] amount of Harshad numbers in a list. To do this, I first made a method isHarshad, which figures out if a number in a list is a Harshad number. Afterwards, I implement this method to print only Hardshad numbers in a list.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
top = 999999999
for x in (range (1,top)):
if isHarshad(x):
a = a + [x]
count += 1
if count == i:
print(a)
ithHarshad(25)
Running this code returns the first 25 Harshad numbers, which is what I want it to do.
Now my question is: Is it possible to form a loop where it checks a range for Harshad numbers, without making a "top" variable as performed in my code? It feels messy to loop to an arbitrary number like 999999.
I hope my question is a bit clear, and thanks in advance for any input!
Try replacing it with while True: And break the loop when enough numbers are generated. In your code you are running through all the possible numbers which is highly inefficient.
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x = 0
while True:
x += 1
if isHarshad(x):
a = a + [x]
count += 1
if count == i: # Breaks when enough numbers are generated.
break
print(a)
ithHarshad(25)
This will keep adding 1 to x until your count terminates it.
I'm not really sure about what do you mean "checks a range". Did you means you want to show all Hardshad numbers between start to end? Is that true, you can do this:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(start, end):
a = []
count = 0
for x in (range (start,end)):
if isHarshad(x):
a = a + [x]
print(a)
ithHarshad(50,100)
Thanks for the feedback, using a while True: worked for me.
Here is my solution:
def isHarshad(i):
l = list(str(i))
a = sum([int(e) for e in l])
if a == 0:
return False
if i % a == 0:
return True
else:
return False
def ithHarshad(i):
a = []
count = 0
x=1
while True:
if isHarshad(x):
a = a + [x]
count += 1
x+=1
if count == i:
print(a)
else:
x+=1
ithHarshad(25)
My way is literally the easiest and smallest way
#get Nums
def getHarshadNums(i):
return [i for i in range(whatever_the_range_is) if isHarshad(i)]