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
Related
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
I have a String like below
line="10,20,30,40,100-200,500,1000-10000"
Iterate each value in the list and check for some if it is between min and max value and return False if not
Current code look like
for i in line.strip().split(','):
if '-' not in i:
if not 0 <= int(i) <= 50000:
return False
elif len(i.split('-')) == 2:
for value in i.split('-'):
if not 0<= int(value) <= 50000:
return False
else:
return False
return True
I need to optimize it better to remove the nested if statements and more return statements.
Violation:
Refactor this code to not nest more than 3 "if", "for", "while", "try"
and "with" statements.
I tried to extract to a different methods but for some permutations didn't work.
Thanks
You can replace the inner for with a generator expression:
for i in list.strip().split(','):
if '-' not in i:
if not 0 <= int(i) <= 50000:
return False
elif len(i.split('-')) == 2:
return all(0 <= int(value) <= 50000 for value in i.split('-'))
else:
return False
return True
you can combine the first two ifs, and get rid of the second for cycle since you only iterate over two elements. Also shouldn't return True be outside of the for loop. With the current code it will return True after it checks only the first integer (I am not sure if that's what you want)
for i in line.strip().split(','):
if '-' not in i and not 0 <= int(i) <= 50000:
return False
elif '-' in i and len(i.split('-')) == 2 and not (0<= i.split('-')[0] <= 50000 and 0<= i.split('-')[1] <= 50000):
return False
else:
return False
return True
Some nesting reductions could be achieved through:
for i in line.strip().split(','):
if '-' not in i:
return 0 <= int(i) <= 50000
# The following will fail if there are more than one hyphen
# if a different error should be thrown, try-catch it
str_val1, str_val2 = i.split('-')
value1, value2 = int(str_val1), int(str_val2)
return 0 <= value1 <= value2 <= 50000
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.
I started learning Python through Codecademy and pondered upon an exercise that required me to write a program that determined if a number was a prime number or not.
When my original code did not work, I did some research and found code that did work. I looked through both of them and it looked like there was no difference between them except the fact I had used for loops to loop through a list when the working code used a while loop to loop through the objects one by one, so I was wondering if that was indeed the case (and if so, what difference it would make) or if my code had a logical error.
Sorry for the block of text, below I will provide both my code (that did not work) and the answer code (which did work)
My code here:
def primer(x):
if x < 2:
return False
elif x > 2:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
else:
return True
and the code that did work here:
def is_prime(x):
if x < 2:
return False
elif x > 2:
n = 2
while n < x:
if x % n == 0:
return False
n += 1
else:
return True
else:
return True
Thank you for even taking the time to read this, and have a nice day.
You immediately return True when you find that the number is not divisible, before trying all the possible divisors. Remove the else block:
def primer(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
# else:
# return True
return True