How to use a generator expression in python to create a list of odd integers? - generator-expression

How would I go about changing the program below to a generator expression that yields the same result?
print 'this program creates a list of odd numbers in the range of your choice'
start_num=int(input('Enter Starting Number'))
end_num=int(input('Enter ending number'))
my_list=[]
for i in range(start_num,end_num+1):
if i%2==1:
my_list.append(i)
print ('odd numbers in the range', my_list)

print("this program creates a list of odd numbers in the range of your choice.")
def generator():
start_num=int(input("enter the starting number:"))
end_num=int(input("Enter the ending number:"))
odds=list(i for i in range(start_num,end_num+1)if i%2==1)
print(odds)
if__name__=='__main__':
generator()``
P.S. GOOD LUCK ON THE MIDTERM THIS WEEK!

Related

I need the code to stop after break and it should not print max(b)

Rahul was learning about numbers in list. He came across one word ground of a number.
A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.
O(n) time complexity
O(n) Auxilary space
Input Description:
First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.
Output Description:
Print the index of val.Print -1 if equal or near exqual number
Sample Input :
7 3
1 2 3 4 5 6 7
Sample Output :
2
`
n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
print(max(b))
`
I've found a solution, you can pour in if you've any different views
n,k = 7,12
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
else:
print(max(b))
From what I understand, these are the conditions to your question,
If can find number, print the number and break
If cannot find number, get the last index IF it's less than value k
Firstly, it's unsafe to manually input the length of iteration for your list, do it like this:
k = 3
a= [1,7,2,2,5,1,7]
finalindex = 0
for i, val in enumerate(a):
if val==k:
finalindex = i #+1 to index because loop will end prematurely
break
elif val>=k:
continue
finalindex = i #skip this if value not more or equal to k
print(finalindex) #this will either be the index of value found OR if not found,
#it will be the latest index which value lesser than k
Basically, you don't need to print twice. because it's mutually exclusive. Either you find the value, print the index or if you don't find it you print the latest index that is lesser than K. You don't need max() because the index only increases, and the latest index would already be your max value.
Another thing that I notice, if you use your else statement like in your answer, if you have two elements in your list that are larger than value K, you will be printing max() twice. It's redundant
else:
print(max(b))

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

Palindrome problem - Trying to check 2 lists for equality python3.9

I'm writing a program to check if a given user input is a palindrome or not. if it is the program should print "Yes", if not "no". I realize that this program is entirely too complex since I actually only needed to check the whole word using the reversed() function, but I ended up making it quite complex by splitting the word into two lists and then checking the lists against each other.
Despite that, I'm not clear why the last conditional isn't returning the expected "Yes" when I pass it "racecar" as an input. When I print the lists in line 23 and 24, I get two lists that are identical, but then when I compare them in the conditional, I always get "No" meaning they are not equal to each other. can anyone explain why this is? I've tried to convert the lists to strings but no luck.
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
Despite your comments first_half and second_half are substrings of your input, not lists. When you print them out, you're converting them to lists, but in the comparison, you do not convert first_half or reversed(second_half). Thus you are comparing a string to an iterator (returned by reversed), which will always be false.
So a basic fix is to do the conversion for the if, just like you did when printing the lists out:
if list(first_half) == list(reversed(second_half)):
A better fix might be to compare as strings, by making one of the slices use a step of -1, so you don't need to use reversed. Try second_half = the_string[-1:x//2:-1] (or similar, you probably need to tweak either the even or odd case by one). Or you could use the "alien smiley" slice to reverse the string after you slice it out of the input: second_half = second_half[::-1].
There are a few other oddities in your code, like your for i in range(x) loop that overwrites all of its results except the last one. Just use x - 1 in the slicing code and you don't need that loop at all. You're also calling int a lot more often than you need to (if you used // instead of /, you could get rid of literally all of the int calls).

Locating prime numbers using for loop(s) in Python

So first of all, I realise there are much easier ways to get a list of prime numbers, but I'm just doing this to learn. I have a very poor understanding of a lot of this (as you'll see) so sorry if this is a dumb question. I'm trying to learn.
#make an empty list to store primes in
primes = list()
#make a variable to easily change the amount of numbers I test for primality
high_val = 15
#Allocate a range that I will test all numbers in for primality
for n in range(2, high_val):
#Within the previous for loop, start another for loop to test every integer against every
#value inside the primes list
for p in primes:
if n % p == 0:
print(%s is not prime" % n)
else:
#If n is prime, I add it to the list and print that it is prime
primes.append(n)
print("%s is a prime" % n)
I don't know if those comments make it harder to read, but that's my logic. There is no print output for the function. So I figured, there's just no value in primes, I need to give it something to compare to. So I added a primes.append(2) at the start immediately after the first line, and changed the range to (3, high_val)...
If I do that, it ends up printing about 5 times for every number that it is prime and 5 more messages saying it is not prime. Clearly I'm doing something massively wrong, if anyone knows where I went wrong and/or how to fix this that would be greatly appreciated. Thanks!
The thing is that you are missing some flags: you are printing if the number is prime every time you check it against another number. You should print it only after iterating over all primes.
About this, consider using all:
primes = [2]
high_val = 15
for n in range(3, high_val, 2):
if all(n % p == 0 for p in primes):
print(f"{n} is prime")
primes.append(n)
else:
print(f"{n} is not prime")
ps: I didn't test it.

Why `a` is treated like 2D array also?

I am new to Python programming. In this Python code first a is treated like what we call 1D array in C. But, in the middle it is treating it as a 2D array!
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j]) #this line
if(n!=0):
a[i].append(1)
for i in range(n):
print(" "*(n-i),end=" ",sep=" ")
for j in range(0,i+1):
print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
print()
I am not getting this idea. Can anyone explain what is happening in the line I have commented #this line(line number 7)? Thanks.
Python is dynamically typed and that's the reason why this is possible. The array (in python this is called a list) a can contain multiple list and values.
a=[1,"a",["abc",10]]
# Here you get the "abc" by calling
print(a[2][0])
In your example, here you append a list:
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
a.append([]) # <---- insert a list into the list
The last line above makes the list a a 2D list.
If you come from C, you are probably familiar with linked lists being implemented as containing a void * value in each node. This is the same as assigning the value of a node to the head of another linked list.

Resources