Python newbie here.
Let's say we have an array which contains 10 random integers.
I want to check if each value of the integers is 0<= x <= 9.
So for example somehow like this:
if 0 <= n[:11] <=9:
print('correct')
'n[:10]' is treated like a list so I can't compare it with 0 and 9.
Is there an elegant way to check the range of items in that array?
I don't want to code something like:
if 0 <= n[0] and n[1] and ... n[9] <=9:
thanks for your help
Check this out:
This returns True if and only if ALL of the numbers in the list n are at least 0 and at most 9, (in range(0, 10))
all(i in range(0, 10) for i in n)
if 0 <= min(n) <= max(n) <= 9:
Could use and instead of <= in the middle, not sure which I like better.
What you want is the check the equality for every elements:
all(0 <= item <= 9 for item in n)
If you first sort the list you only have to check the first and last value, like this:
sorted_n = sorted(n)
if sorted_n[0] > 0 and sorted_n[-1] < 10: # returns True or False for whole list
Related
I want to count the number of numbers larger then 0 in a list for example. Can i use larger then, smaller then etc operators inside .count()?
test_list = ['0','2','3']
for i in test_list:
i = int(i)
larger_zero = test_list.count(i > 0)
print(larger_zero)
Its printing 0 and i wonder why? What is the explanation why its printing a zero?
You could use an iterator with sum for that.
test_list = ['0', '2', '3']
larger_zero = sum(int(i) > 0 for i in test_list)
print(larger_zero)
Which prints:
2
Note that int(i) > 0 is either True (which sum treats as 1) or False (which sum treats as 0). sum just adds up all of them, effectively counting how many times int(i) > 0 is True.
list.count takes a value, not an expression. i > 0 evaluates to False or True, then test_list.count checks how many times it occurs in the list, which is 0.
You can do it like this:
larger_zero = sum(1 for i in test_list if int(i) > 0)
Or you can be a bit hacky and use the fact that False == 0 and True == 1:
larger_zero = sum(int(i) > 0 for i in test_list)
when u use the operator i>0, it will return true or false. So it will count how many true and false in the list. so better use if statement if u want to return list of the number > 0. For example:
test_list = ['0','2','3']
larger_zero = []
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
if test_list[i] > 0:
larger_zero.append(test_list[i])
print(larger_zero)
now u will get list of number which is higher than 0. if u want the total count of > 0 u can use length of the new list for example:
print(len(larger_zero))
if you don't wan to change the data type of the origin list, u can make it like this:
test_list = ['0','2','3']
larger_zero = []
for i in range(0, len(test_list)):
if int(test_list[i]) > 0:
larger_zero.append(test_list[i])
print(larger_zero)
print(len(larger_zero))
I have this function to find the number of times a number is followed by a larger number in a list. Is there another more "pythonic" way this could be done? I am using Python 3.7.0.
Thanks in advance.
def find_greater_numbers(arr):
count = 0
i = 0
j = 1
while i < len(arr):
while j < len(arr):
if arr[j] > arr[i]:
count += 1
j+=1
j = i+1
i+=1
return count
find_greater_numbers([6,1,2,7]]) # returns 4
It's a bit unclear if you mean immediately followed, or followed at any later index
In the first case, this one liner:
sum(x < y for x,y in zip(arr[:-1],arr[1:])) # answer is 2
In the second, this one:
sum(any(x < y for y in arr[i:]) for i,x in enumerate(arr)) # answer is 3
And if you want to count the number of exact such pairs (like what your actual code seems to be doing):
sum(x < y for i,x in enumerate(arr) for y in arr[i:]) # answer is 4
Use map to get the list of True/False for each pair of number in the list depending on the condition if x < y. This list is being generated using the for loop. After getting the list, filter the number of 'True' in the list. Then create a single list using itertools.chain.from_iterable() function and find its length.
import itertools
arr = [6, 1, 2, 7]
num = len(list(itertools.chain.from_iterable(list(filter(lambda x: x , map(lambda x, y: x<y, arr[:-i], arr[i:]))) for i, x in enumerate(arr))))
print(num)
I have been generating random sets and lists and was curious about how one would calculate the number of multiples in that given set or list. The code I have written gives me the wrong number, so I am assuming I have allocated something incorrectly. The code is
b= random.sample(range(1, 56), 6)
print(b)
numbers = (b)
count_multiples = 0
for y in (b):
for x in (b):
if y % x ==0:
count_multiples+=1
print("MPS:", count_multiples)
I am brand new to coding and this exchange, so any help would be appreciated.
This depends on what exactly you mean by number of multiples in the list.
1). Do you want to count every number at least once, since every number is a multiple of itself?
2). Do you want to count an element more than once if it is a multiple of more than one element in the list?
If you answer yes to both of these questions your code looks fine (although not the most efficient). If no try something like the following:
min, max = 1, 56
n = 6
count = 0
random_list_with_no_duplicates = random.sample(range(min, max), n)
# If no to 1) but yes to 2)
random_list_with_no_duplicates.sort()
for i in range(n):
for j in range(i + 1, n):
if random_list_with_no_duplicates[j] % random_list_with_no_duplicates[i] == 0:
count += 1
# If no both
random_list_with_no_duplicates.sort(reverse=True)
for i in range(n):
for j in range(i + 1, n): # change to just 'i' if yes to 1), no to 2)
if random_list_with_no_duplicates[i] % random_list_with_no_duplicates[j] == 0:
count += 1
break
In Python, True and False are equal to 1 and 0, respectively. You can take advantage of this and use sum to add the booleans together. The result will be the number of elements, e, where bool(e) evaluates as True.
count_multiples = sum(y % x == 0 for y in b for x in b)
I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))
Consider the following definitions of positive numbers:
A number is nondecreasing if its digits never get smaller as you go from left to right. For example, 12345
and 3388 are nondecreasing.
A number is nonincreasing if its digits never larger as you go from left to right. For example, 987542 and
881 are nonincreasing.
A number is bouncy if it is neither nondecreasing nor nonincreasing. For example, 12134 and 98462 are
bouncy.
Write a Python function bouncy that consumes a positive natural number (called n) and produces the
percentage of numbers between 1 and n, inclusive, which are bouncy. The result should be produced as a
natural number between 0 and 100, inclusive. Use round to convert the floating point percentage to an
integer.
def bouncy(input):
list1 = [0 for i in range(input)]
list1[0] = 0
for x in range(1, input-1):
if x < 100:
list1[x] = list1[x - 1]
else:
n=x
a = [0 for i in range(x)]
i = 0
while n > 0:
a[i]=n % 10
n/= 10
i+=1
flag = 1
for k in range(1, len(a) - 2):
if not ((a[k - 1] < a[k] < a[k + 1]) or (a[k - 1] > a[k] > a[k + 1])):
flag = 0
break
if flag == 0:
list1[x]==list[x-1]+ 1
return list1[input-1]
when i ran my code, it displays builtins.IndexError: list assignment index out of range.
Anyone got an idea?
You don't have to do any of that. Just turn the number into a string. If it's sorted it's nondecreasing, if it's reverse sorted it's nonincreasing, otherwise it's bouncy.
def bouncy(n):
return round(sum(list(i) not in (sorted(i), sorted(i, reverse=True)) for i in map(str, range(1, n+1)))/n*100)
This map()s each number in the range to a string, then checks whether a list() of that string is not found in a sorted() version of that string (either increasing or decreasing). Then it adds together how many numbers match that, divides by n, multiplies by 100, round()s that, and returns it.