This question already has answers here:
Prime Numbers python
(5 answers)
Closed 5 years ago.
I am supposed to write a program to change a string if that position number is not a prime number but I can't seem to figure out how to make the first position, for example position 2, prime, and make the rest of the positions that can be divisible by 2, turn into N. Below is what I currently have and I am an int error. If anyone can help me out, I would really appreciate it. Thank you
while True:
number = int(input("Enter a number greater than 10: "))
if number < 10:
print("Invalid input. Try again")
else:
break
n_list = ["P"] * (number + 1)
n_list[0] = "N"
n_list[1] = "N"
for i in range(n_list):
if int(n_list[i]) % 2 == 0:
n_list[i] = "N"
print(n_list)
Firstly, you probably get an error because range takes an integer, not a generator, try instead for i in n_list or for i in range(len(n_list)). As for the approach of the problem, you dont need to loop from 2 to n, there is a smarter way. But we are not here to solve that problem for you, only to guide you to find eventual errors that you may present us. With that said, best of luck to you!
PS:
A little more guidance
Sieve of Eratosthenes
EDIT:
The error i'm referring to is
TypeError: 'list' object cannot be interpreted as an integer
I don't want to give you the answer to your homework, but I do want to help so I will guide you a little.
I see 2 issues with what you've provided. First, you are using the incorrect variable for your range. You want a number, not a list.
Second, you cannot compare if "P" is evenly divisible 2. You can only check if a number is.
Hope this helps and good luck.
EDIT: To clarify, there are more issues, but these 2 will give errors.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
A number that equals to the sum of its own digits, where each digit raised to the power of number of digits. For example, 153 is an armstrong number
because 1^3+3^3+5^3=153
at here user enters a number
number=int(input("please enter a number: "))
Here in a while loop it puts the digits of the given number in numbers class
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
and then we want to put their qubes in qubes class
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
and now we calculate the sum of the qubes class members
result = sum(i for i in qubes)
I dont know why the if_code below doesnt work it just gives me false output I dont know why??
even when i enter 153 it prints false
if result==number:
print("true")
else:print("false")
To sum-up all suggestions from the comments:
Your main problem is:
When you create the numbers list you use number = int(number/10). This changes the number variable itself until it is equal to zero. This means that, as you experienced, result == number will always be False.
Some redundant parts of your code:
See Splitting integer in Python? to get a list of a number's digits. Most commonly you can just do numbers = [int(i) for i in str(number)]. This will actually solve the problem above as you don't change number this way.
The digits are already integers so no need for an int conversion. It is also more readable to use direct loop in Python rather than looping over indices:
qubes = []
for num in numbers:
qubes.append(num**len(numbers))
sum(i for i in qubes) is just an overly explicit way of saying sum(qubes).
You are printing either "true" or "false" according to a boolean result. There is no need for a condition and you can simply print(result == number).
Putting together all the above, you can achieve this with a single line of code:
print(number == sum(int(digit)**len(str(number)) for digit in str(number)))
This is where you are wrong. you should iterate over the integer not the iterator given by range function
Use this
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
instead of
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
Also you are referencing the number to itself number=(int(number/10)) so your result value will be 153 but number value will be 0 at the end because you have reduced the value of number. So copy the value of number to another variable (num1 in below code).
Full code:
number=int(input("please enter a number: "))
num1 = number
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
result = sum(i for i in qubes)
print(result == int(num1))
This question already has answers here:
Ordering of string representations of integers [duplicate]
(6 answers)
Closed 2 years ago.
Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing? Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing?
import time
t=time.localtime()
msttime=time.strftime("%H",t)
if(msttime < '2'):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
This code will give you the expected result:
import time
t = time.localtime()
msttime = time.strftime("%H", t)
if (int(msttime) < 2):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
The reason is that "18" < "2" lexographically, but 18 > 2 numerically. This is because the lexographical comparison has no regard for the second digit. Since 1 is before 2, the comparison ends there. In the numerical comparison, all digits are accounted for.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
This is supposed to be a random number guessing game. It is supposed to say whether the number was guessed correctly or not at the end but it will always display "Wrong" even if the number has been guessed correctly.
I've only been learning python for a couple of days and this is doing my head in.
import random
odds = [1,2]
rNum=(random.choice(odds))
print ('The odds are:',odds)
gNum=input('What is your guess?')
print ('You Guessed:',gNum)
print ('The number was:',rNum)
if (rNum == gNum):
(print("Correct!"))
if (rNum != gNum):
(print("Wrong"))
Its as if it can't compare if the number is the same or not and always interprets it as wrong, as it only will give the != result
Forgive me if I sound foolish I am only beginning
Many thanks :)
I imagine the types are different. One is an int, the other a str which happens to contain an integer. Try"
gNum=int(input('What is your guess?'))
This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 4 years ago.
everybody!
I am currently learning Python (no prior coding skills - at least not enough to mention them) and I am struggling with a for loop in a lottery machine we are supposed to do for homework.
I have spent the past two hours googling this, but I wasn't able to find anything that would hint me in the right direction.
I want the loop to create a list with random numbers. The amount of random numbers printed to the user should be defined by user input and it should not use duplicates. Every time a duplicate is created it should simply pick a different number. Any hints on where i screwed up here? (Pls note it's Python 2.x)
Thank you all! :)
Code:
from random import randint
lotterylist = []
print "Welcome to the lottery machine!"
mynumbers = int(raw_input("How many numbers should be drawn?\n"))
for i in range(0, mynumbers):
lottery_numbers = randint(0, 48)
if lottery_numbers not in lotterylist:
lotterylist.append(lottery_numbers)
else:
mynumbers += 1
continue
print lotterylist
print "End"
You could do it like this because honestly the current code doesn’t make much sense.
for _ in range(0, num):
snum = randint(0, 48)
while snum in numlist:
snum = randint(0, 48)
numlist.append(snum)
This will keep on creating a new number until a number not in the list is selected and then it exits the while loop and appends the number to your list of generated numbers. No need to keep on incrementing the range; going forward you should understand that if your logic requires something like that then it means it is flawed. Your current approach doesn’t make sense.
This question already has answers here:
Function for factorial in Python
(10 answers)
Closed 6 years ago.
So these are the instructions:
"Given a number “n,” if I were to multiply all positive integers up to and including
“n,” I would get a product. This product is called the factorial of “n,” which is
denoted n! (read as n factorial). It is also given that 0! = 1. Your task is to write a
Python script that implements the factorial of a number “n.” For example if “n” is
initialized with the value 5, then your script should print out the following.
The factorial of 5 is 120"
I'm stuck on how exactly to structure the while and for loop along with the range variable. Can any one help me here. It doesn't have to be the exact answer. Just a clue or something please :D
I hope this is not a homework question...
Here is pseudocode:
Create a variable to store your answer, and initialize it as 1
Loop through the numbers from 1 to n inclusive, multiplying your answer
variable by each number
Print out the answer in the desired format
Thats all!
This simple for loop works:
prod = 1 # solution variable
for i in range(1, n+1):
prod *= i # do the work, i.e., make the solution
print("The factorial of %s is %s" % (n, prod))
We don't need to check for zero as the loop is skipped if so.
Hope this helps!
(Alternatively, you could use math.factorial(n), but you aren't learning anything if you use builtins)
Tell me if you have more questions.