I'm trying to create a code that will print every number in a range set by the user, and then identify how many numbers in that range are odd numbers and how many are even.
I've tried a few different formats, but I'm very much a beginner and can't seem to nail down where I'm going wrong. I'm trying to keep the code as simple as possible.
for i in range(x,y+1):
print(i)
range = (x,y+1)
count_odd = 0
count_even = 0
for n in range:
if n%2==0:
count_even = count_even+1
else:
count_odd = count_odd+1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Currently when I run this, even numbers always comes to 0 and odd to 2.
On line 4 you have:
range = (x,y+1)
This is the tuple (x, y+1) not the range between them. So when you loop through it you are only looping through those two numbers. I assume in your case they are both odd. I would recommend removing that line and starting your second for loop like this:
for n in range(x, y + 1):
range is a builtin function, which returns an iterable from [start, end). You likely want something like:
count_odd = 0
count_even = 0
for n in range(x,y+1):
if n % 2 == 0:
count_even = count_even + 1
else:
count_odd = count_odd + 1
print("Number of even numbers :", count_even)
print("Number of odd numbers :", count_odd)
There's no point for a loop. If your range consists of even elements, then half of values is even and half is odd. If it consists og odd elements and starts from odd value then half+1 is odd and half-1 is even. It starts with even value then it's opposite.
Related
My code it generates a random number it checks if it is in the list if it is it generates another random number and then it checks if it is equal or not and shows the result and repeats the process. But when I start the code it generated the normal number but it repeats the numbers and it shouldn't repeat the number. What do I do?
from random import randint
import os
n = 0
numsort = 14564487
attempt = 0
numbers = []
while n < 100:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
attempt += 1
if num == numsort:
print(f'{num}' + '\033[32m' + ' Right number' + '\033[0m')
print(f'After {attempt} attempts it was')
break
if num != numsort:
print(f'{num}' + '\033[31m' + ' Wrong number' + '\033[0m')
print(f'Attempt # {attempt}')
os.system('clear')
The issue here is a simple one. The primary problem is with this code snippet:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
Translating this to English, we have:
Generate a random seven-digit integer
If the integer is in our list of numbers then regenerate it and add it to the list
The problem you have here is that you have no guarantee that the regenerated number won't also be in the list. The chance of this happening will grow as the list grows. And, since your loop variable is never updated, this list will grow infinitely.
To fix this problem, you have two possible solutions. For small lists, you can continue on with your strategy of regenerating numbers and replace the if with a while:
num = randint(1000000, 9999999)
while num in numbers:
num = randint(1000000, 999999999)
numbers.append(num)
Note that this will only work while the desired size of your list is much smaller than the range of possible values being generated. As you fill up the list, the chance of collisions between the range of possible values and actual values will increase, causing the while loop to run longer.
Alternatively, you can use sample to choose your values, which would replace the entire loop:
numbers = random.sample(range(1000000, 10000000), n)
Note here that the use of range means that this is actually just as space efficient as the previous solution and will guarantee unique values.
I am attending a course on Udemy and one of the exercises is to return all the prime numbers from a range of numbers (for example all prime numbers before 100)
This is the query that the teacher made
def count_primes2(num):
#Check for 1 or 0
if num < 2:
return 0
######################
#2 or greater
#Store our prime numbers
primes = [2] #I start my list with 2 that is a prime number
#Counter going up to the input num
x = 3 #I create a variable on which I will continue adding until I reach num
# x is going through every number up to the input num
while x <= num:
#Check if x is prime
for y in range(3,x,2): # for y in range from 3 to x in even steps, we only wantto check odd numbers there
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
count_primes2(100)
However, I came up with the one below that is not working. My idea is:
Given each number i between between 3 and num+1 (for example 100 would be 101 so that 100 can be included in the calculation):
Open a for loop in which I divide i by each number g before i (including i) and I have a counter checking when this division gives no remainder. This implies that in case of prime numbers the counter should always be 2 (for example 3--> 3:1 and 3:3 would give remainder 0).
If the counter is equal to 2, then i is a prime and I want to append it to the list.
I am not using any while loop in my query. Can you help me to identify why my query is not working?
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
return list_prime
count_prime(100)
Kudos to Khelwood for the help. Below the working query:
def count_prime(num):
counter=0
list_prime=[2]
if num<2:
return 0
for i in range(3,num+1):
for g in range(1,i+1):
if i%g==0:
counter+=1
if counter==2:
list_prime.append(i)
counter=0
return list_prime
count_prime(100)
you may do this :
for i in range(2,num):
if (num % i) == 0:`
Instead of using two for loops, you can simply eliminate one of the for loop and do this, I hope this may work for you.
thankyou.
Recently I was given a challenge to my coding skills by my teacher since he saw that I was already knowledgeable in what he was teaching. The question is as follows.
Create a program that prompts the user for 2 numbers. The program will then display all the prime numbers in between the two given numbers, including the given numbers. Note: You cannot assume the first input is bigger than the second input.
So I took this question and built a fairly simple algorithm and ran it and it worked. I opened it today to find out for some reason my output is occasionally wrong, for example when you input 8 and 29 I get 27. I am looking for HINTS as to what is wrong with my logic because I cannot for the life of me figure out what Im doing wrong. I dont want straight up fixes because I would like to learn as much from this and doing it as much as possible by myself.
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
numList = []
#Removing Even Numbers
for num in range(numbers[0],numbers[1] + 1):
if num % 2 != 0:
numList.append(num)
#Checking For Prime Numbers
for currNum in numList:
#Set Start number to divide
i = 2
while i < currNum:
#Checks if the currNum can be divisble by i and is a whole number
if currNum % i != 0:
i = i + 1
else :
numList.remove(currNum)
break
print(numList)
From what I have learned from testing this out it seems like 27 is never checked during my for loop or while loop even though it is in the numList array.
Never remove items form a list you are iterating over.
Instead create a new list:
numbers = [int(input("First Number")), int(input("Second Number"))]
numbers.sort()
primes = []
for num in range(numbers[0], numbers[1] + 1):
#Set Start number to divide
i = 2
while i < num:
#Checks if the currNum can be divisble by i and is a whole number
if num % i == 0:
break
i += 1
else:
primes.append(num)
print(primes)
I have a problem where I need to find the number of unique numbers. No digits in the number would have been repeated.
Number like 11, 1123, 41124 wont qualify.
Numbers should be 1234, 12, or 987 like these would qualify.
My code works fine. But when the range go beyond 10^6. The code takes lots of time to execute. How can I optimize the same.
for i in xrange(10000000):# pow(10, n) 10, 100, 10000,...
j = str(i)
if j != j[::-1]:
for k in range(len(j)):
if j.count(j[k]) == 1:
if k == len(j)-1:
count += 1
#print j
else:
break
if len(j) == 1:
count += 1
print count
You are going about this in possibly the least efficient way possible, and the longer the number gets, the longer it will take. Your code should look more like this:
for i in xrange(10000000):
j = str(i)
if len(set(j)) == len(j):
count += 1
# print j
print count
This takes advantage of the fact a Python set can't contain duplicates (duplicates are eliminated). So, if the length of the set of the digits in the number is the same as the length of the original string of digits, we know no digits were duplicated.
You can even write it in one line:
print sum(len(set(j)) == len(j) for j in (str(i) for i in xrange(10000000)))
Others have suggested collections.counter which is useful if you want to know which digits were duplicated.
for homework in an introductory python class, one of the questions is to count the number of even numbers in n. here's my code so far:
def num_even_digits(n):
i=0
count = 0
while i < n:
i+=1
if n%2==0:
count += 1
return count
print(num_even_digits(123456))
Pythonic answer:
def num_even_digits(x):
return len([ y for y in str(x) if int(y) % 2 == 0])
print(num_even_digits(123456))
Disclaimer: I recognized that, for an introductory Python class, my answer may not be appropriate.
you are comparing the whole number every time. you need to convert it to a string and then loop over every number in that string of numbers, cast it back to an integer and see if its remainder is 0
def num_even_digits(numbers):
count = 0
numbers = str(numbers)
for number in numbers:
try:
number = int(number)
except ValueError:
continue
if number % 2 == 0:
count += 1
return count
print(num_even_digits(123456))
if you want to actually loop through every possible number in the range of 0 to your large number you can do this.
def num_even_digits(numbers):
count = 0
for number in range(0, numbers):
if number % 2 == 0:
count += 1
return count
print(num_even_digits(10))
problems with your current function:
def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
i=0
count = 0
while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
i+=1
if n%2==0: # n hasn't changed so this is always going to be true
count += 1
return count
print(num_even_digits(123456))