Am new to python and I have been trying to solve this problem but it does not seem to work as intended. your help is highly appreciated:
Given two numbers X and Y, write a function that:
returns even numbers between X and Y, if X is greater than Y
else returns odd numbers between x and y
.
def number(x,y):
if x > y:
for i in range(x,y):
if i%2 == 0:
list = []
return list.append[i]
else:
for i in range(x,y):
if i%2 == 1:
list = []
return list.append[i]
print(number(10,2))
Try this code it's working as per your need.
def number(x,y):
num= []
if x > y:
for i in range(y,x):
if i%2 == 0:
num.append(i)
else:
for i in range(x,y):
if i%2 == 1:
num.append(i)
return num
print(number(2,10))
print(number(10,2))
The outputs are:
[3, 5, 7, 9]
[2, 4, 6, 8]
Let me know if this doesn't serve your purpose.
And it is done. Basically if x > y, you need to switch the first range. You append the items normally(using () instead of []), and then return the full list, got it?
def number(x,y):
list = []
if x > y:
for i in range(y,x):
if i%2 == 0:
list.append(i)
else:
for i in range(x,y):
if i%2 == 1:
list.append(i)
return list
print(number(10,2))
Working sample: https://py3.codeskulptor.org/#user302_nwBq00w56n_1.py
Instead of testing for oddness/evenness all the time, use range(start,stop[,step]) with a step of 2 starting with a (corrected, known) odd/even number:
def number(x,y):
if x > y:
if y%2 == 1: # y is smaller && odd
y += 1 # make even
return list(range(y,x,2)) # x is > y - start from y to x
else: # this is strictly not needed - but more verbose intention-wise
if x%2 == 0: # is even
x += 1 # make odd
return list(range(x,y,2))
print(number(10,32))
print(number(10,2))
You need to also switch x and y if x > y
you do not need to iterate a range and add its element to a list iteratively - simply stuff the range-sequence into the list(sequence) constructor and return it
Output:
[11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31]
[2, 4, 6, 8]
It's so easy to do, and there are several ways to do what do you want, so i show you two ways to do that, first an understandable way and second an easy way ok let's start:-
First example
def number(x,y):
list = [] #firstly create a list
if x > y: #if x was greater than y
for num in range(y, x): # a loop for searching between them
if(num % 2 == 0): # if the number was even add it to list
list.append(num)
elif y > x: #if y was greater than x
for num in range(x, y): # a loop for searching between them
if(num % 2 != 0): # if the number was not even add it to list
list.append(num)
return list
print(number(10, 20))
print(number(20, 10))
#[11, 13, 15, 17, 19]
#[10, 12, 14, 16, 18]
Second example
number = lambda x, y : [n for n in range(y, x) if n%2 == 0] if x > y else [n for n in range(x, y) if n%2 != 0]
print(number(10, 20))
print(number(20, 10))
#[11, 13, 15, 17, 19]
#[10, 12, 14, 16, 18]
Note : But be sure that in both of my answers the x number is inclusive(exists in searching function) and the y number is exclusive, so if you wanted to make both of them inclusive so make loops ...(x, y+1)... and if you wanted to make both of them exclusive just change loops to ...(x+1, y)....
Knowing that 2 % 2 == 0 we then can just use if not 2 % 2 for evens since not 0 will evaluate to true, here it is with comprehension and in extended form
def something(x, y):
if x > y:
l = [i for i in range(y, x) if not i % 2]
else:
l = [i for i in range(x, y) if i % 2]
return l
print(something(10, 2))
print(something(2, 10))
~/python/stack$ python3.7 sum.py
[2, 4, 6, 8]
[3, 5, 7, 9]
Full loop:
def something(x, y):
l = []
if x > y:
for i in range(y, x):
if not i % 2:
l.append(i)
else:
for i in range(x, y):
if i %2:
l.append(i)
return l
Here in this i use the list comprehensions.list comprehension is a easy and readable technique in python.In this i include both x and y
def fun(x,y):
if x>y:
l=[i for i in range(y,x-1) if i%2==0]
return l.reverse()
else:
l=[i for i in range(x,y+1) if i%2!=0]
return l
Related
hello I am struggling with this problem for school and can't get my code to do what it needs to solve this. The question is: Define an element of a list of items to be a dominator if every element to its right (not just the one
element that is immediately to its right) is strictly smaller than that element. It wants me to count how many denominators are in the list.
def extract_increasing(digits):
countDem = 0
#check and see if there is anything in the list
if not digits:
return 0
#compare the first element to the one on the right of it
for x in range(len(digits)):
for y in range(x + 1, len(digits)):
if digits[x] > digits[y]:
countDem += 1
return countDem
The code below should check if a number in the list is a dominator.
def is_dominator(lst, idx):
for i in range(idx + 1, len(lst)):
if lst[i] >= lst[idx]:
return False
return True
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in digits:
print(is_dominator(digits, i))
The error in your code is that you're adding one for the counter every time the next value meets the condition.
for x in range(len(digits)):
for y in range(x + 1, len(digits)):
if digits[x] > digits[y]:
countDem += 1
Every time digits[x] > digits[y] is met you add one to your counter. You should only add one once you checked that all values to the right meet the condition.
isDem = False
for x in range(len(digits)):
for y in range(x + 1, len(digits)):
if digits[x] > digits[y]:
isDem = True
else:
isDem = False
#Once you went through all the values to the right you can add one to the counter
if isDem ==True:
countDem += 1
Hope that helps!
You start in the last element, and save always the max_element in every iteration, then you know always if exist some number grater than the current number. This is a little more efficient because it runs through the array only once.
def dominator(li: list):
sol = 0
max_number = -math.inf
for i in range(len(li)-1, -1,-1):
if li[i] > max_number:
sol+=1
max_number = li[i]
return sol
Try list comprehension
lst = [0, 10, 2, 6, 7]
new_lst = [v for k,v in enumerate(lst) if all(v > x for x in lst[k+1:])]
# [10, 7]
Update
def extract_increasing(digits: list) -> int:
countDem = 0
for x, y in enumerate(digits):
if all(y > a for a in digits[x+1:]):
countDem += 1
return countDem
lst = [0, 10, 2, 6, 7]
extract_increasing(lst) # -> 2
can someone help me write code in Python for this problem?
x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]
Write up some code to multiply only the negative values. Print the result of these multiplications. Include a loop of some kind as well as an if-statement to grab just the negative numbers.
This is what I have so far:
x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]
for num in x:
if num < 0:
print (num, end = "")
IIUC, here's one way via reduce
from functools import reduce
x = [10, -5, 6, -7, 2, 4, -9, 12, -55, 33, 44, 77, -1]
result = reduce(lambda x, y: x*y, (i for i in x if i < 0))
OUTPUT:
17325
You almost got it. I think they want you to do a simple script:
x = [10,-5,6,-7,2,4,-9,12,-55,33,44,77]
result = 1
for num in x:
if num < 0:
result = result * num
# or result *= num
print(result)
With basic arithmetic and closest to your original version:
total = 0 if len(x)==0 else 1
for i in x:
if i < 0:
total *= i
print(total, end = "")
17325
borrowing from https://stackoverflow.com/a/13843424/1248974
I want to make a program as an exercise which prints all prime numbers in range of given limit(parameter). Thanks.
#prime numbers
prime = list()
for x in range(1, 100):
for a in range(2, x):
if x % a == 0:
break
else:
prime.append(x)
print(prime)
You can use this list comprehension to find prime numbers in given range;
def prime_generator(number):
return [x for x in range(2, number) if not any(x % y == 0 for y in range(2, int(x/2)+1))]
In: prime_generator(30)
Out: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
i have a task:
got a range on input
[x;y]
then i should check every number from that range and check every numeral in number. if its odd, i should print it
for example: 3, 20
i should print 4,6,8,20
def check(num):
if int(num) % 2 == 0:
return True
x, y = int(input()), int(input())
numbers = []
if x <= y:
while x != y:
for i in str(x):
if check(i):
numbers.append(x)
x += 1
else:
while y != x:
for i in str(y):
i = int(i)
if check(i):
numbers.append(y)
y += 1
if y == x:
for i in str(x):
if check(i):
numbers.append(x)
print(numbers)
it prints
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29]
instead of 2,4,6,8,20,22,24,26,28
You are checking and approving based on a single digit for each number. You should check all of them before appending the entire number. That's why you get 22 twice: once for the first 2 and once for the second. You get 10, because even though 1 is odd, 0 is even and so you append it to your list.
Move the check for the entire number into the function check and have it return True only if all digits are even. This shortens your code. Also note that you can trivially swap x and y if the user entered them in the wrong order.
The function check immediately returns False as soon as it finds a digit i is odd, and you can see it can only return True if the loop ended and all digits were even.
def check(num):
for i in str(num):
if int(i) % 2 != 0:
return False
return True
x, y = int(input()), int(input())
if x > y:
x,y = y,x
numbers = []
while x <= y:
if check(x):
numbers.append(x)
x += 1
print (numbers)
Result, with 3 and 20 entered (but 20 and 3 would also work):
[4, 6, 8, 20]
I am trying to learn the selection sort using python, but can't get my code to work. Some assistance would be appreciated.
def selection(seq):
for x in range(len(seq)):
temp = 0
for y in range(1, len(seq)):
if seq[y] < seq[temp]:
temp = y
if temp != 0:
seq[x], seq[temp] = seq[temp], seq[x]
return seq
selection([12, 38, 2, 18, 15, 1, 19])
You mixed indexes for both loops and initialisation of temp. You can fix it with this code:
def selection(seq):
for x in range(len(seq)):
temp = x
for y in range(x+1, len(seq)):
if seq[y] < seq[temp]:
temp = y
seq[x], seq[temp] = seq[temp], seq[x]
return seq
seq = [5, 3, 1, 2, 4]
print(selection(seq))