eg : `a = "452398" i want to take all the indices(one after - one after digits) like (4 , 2 , 9) double them == (8 , 4 , 18)
next step to check if the doubled digits is greater than 9 if so need to subtract from 9 (8 , 4 , 9) and finally i want add the digits in a ("854398") it must a string any idea how to do it ?
i tired for loop using range , len skip i sorted out everything till the last step but i couldn't apply the digits in "a" . so deleted the whole loop :(
This does what you described, but why would you want to do that:
a = "452398"
a_list = [int(x) for x in a]
numbers = [x*2 for x in a_list[::2]]
numbers = [x-9 if x>9 else x for x in numbers]
result = [j for i in zip(numbers,a_list[1::2]) for j in i]
result = map(str, result)
result = ''.join(result)
string is immutable so first you should create a list of characters using your string
a = '452398'
new = list(a)
then create a loop to do your conditions and change the value of characters in the list
for i in range(0,len(new),2):
num = int(new[i]) * 2
if num > 9:
new[i] = num - 9
else:
new[i] = num
now overwrite the value of your variable a using your new list of characters.
a = ''.join(map(str,new))
Here is the whole code.
a = '452398'
new = list(a)
for i in range(0,len(new),2):
num = int(new[i]) * 2
if num > 9:
new[i] = num - 9
else:
new[i] = num
a = ''.join(map(str,new))
print(a)
Here's how you do it using list comprehensions
A = "452398"
res = "".join([(str(min(int(a) * 2, 9)) if idx % 2 == 0 else a) for idx, a in enumerate(A)])
One of the simple answers could be.
a = '452398'
b = []
for i, x in enumerate(a):
if (i%2 == 0):
res = int(x) * 2
if len(str(res)) > 1:
res = res - 9
b.append(res)
else:
b.append(x)
b = map(str, b)
b = ''.join(b)
print(b)
Related
I just started to code and try to build my first function in Python/NumPy. My first goal was to get a list for all multiplies of 31 which are not divisible by numbers 1>31 and I figured it out
Here is the code:
c = float(input("Range?"))
a = np.arange(1,c)
A = np.array([31*a])
B=(A[(A%2!=0) & (A%3!=0) & (A%5!=0) & (A%7!=0) & (A%11!=0) & (A%13!=0) & (A%17!=0) & (A%19!=0) & (A%23!=0) & (A%29!=0)] )
print(B)
The next step is to make the function more flexible, but easy ideas like this just don't work, obviously:
c = float(input("Range?"))
a = np.arange(1,c)
d = float(input("multiplier of?"))
A = np.array([d*a])
C=(A[(A%d!=0)])
The answer will be something like
def can_multiply(border_num, num) -> bool:
# 2 instead of 1 here because every num is divisible to 1
arr = [x for x in range(2, border_num)]
for number in arr:
if num % number == 0:
return False
return True
c = float(input("Range?"))
a = np.arange(1, c)
d = float(input("multiplier of?"))
A = np.array([d * a])
print(A[0])
C = [x for x in A[0] if can_multiply(int(d), x)]
print(C)
where [x for x in A[0] if ....] is a list comprehension meaning we take every element in array A[0] and add it to the new array C if can_multiply func returns True
I tried it a lot and I want to get occurrence of 4 without using count function
n = int(input()) #number of input
for i in range(n): #range
l = [] #list
x = int(input()) #input
while (x > 0): #innserting input into list
y = x % 10
x = x / 10
l.append(y)
z = 0
for i in l:
if (i == 4): # calculating no of occurrence
z = z + 1
print(z)
Here's a much simpler way of solving it.
number = int(input("Enter Number: "))
fours = [] #create list to store all the fours
for x in str(number): #loop through the number as a string
if x == '4': #check if the character if 4
fours.append(x) #add it to the list of fours
print("Number of fours: " + str(len(fours))) #prints the length of the array
In the following code, I am trying to extract numbers from a list in which all digits are divisible by 2. The following code works.
l = range(100,401)
n=[]
for i in l:
s =str(i)
if all([int(s[0])%2==0,int(s[1])%2==0,int(s[2])%2==0]):
n.append(s)
print(",".join(n))
I was trying to insert a for loop to avoid writing all three conditions explicitly.
l = range(100,401)
n=[]
ss=[]
for i in l:
s =str(i)
ss.append(s)
for element in ss:
for j in range(3):
if int(element[j])%2==0:
n.append(element)
print(n)
I can't get the desired output. Not only that, the elements of output list 'n' at even index are printed twice. I am unable to figure out WHY?
Thanks.
Generator expression checking if all() elements evaluate to True comes to your rescue:
l = range(100,401)
n=[]
for i in l:
s = str(i)
if all(int(ch) % 2 == 0 for ch in s):
n.append(s)
print(",".join(n))
Now it also works even if you work with more digits.
Thanks for #jpp's advice on generator expression!
And here a faster alternative where you evaluate if any() is not divisable with 2.
l = range(100,401)
n=[]
for i in l:
s = str(i)
if any(int(ch) % 2 != 0 for ch in s):
continue
else:
n.append(s)
print(",".join(n))
You can do this:
l = range(100, 401)
n = []
for i in l:
v = 0
for j in str(i):
if int(j) % 2 == 0:
v += 1
if v == len(str(i)):
n.append(str(i))
print(",".join(n))
Or with some list comprehension:
l = range(100, 401)
n = []
for i in l:
if all(int(j) % 2 == 0 for j in str(i)):
n.append(str(i))
print(",".join(n))
Or with even more list comprehension:
l = range(100, 401)
n = [str(i) for i in l if all(int(j) % 2 == 0 for j in str(i))]
print(",".join(n))
Or with a ridiculous minimizing:
print(",".join([str(i) for i in range(100, 401) if all(int(j) % 2 == 0 for j in str(i))]))
Explaining
OP asked me to explain why his code doesn't work. I'll make it in some steps, also optimizing it:
l = range(100,401)
n = []
ss = []
for i in l: # You don't need this loop, you are just making a new list with string values instead of integers. You could make that on the fly.
s = str(i)
ss.append(s)
for element in ss:
for j in range(3):
if int(element[j]) % 2 == 0: # This only check if the current digit is pair and it append the whole number to the list. You have to check if the 3 numbers are pair AND then append it.
n.append(element)
print(n)
Your code check each digit and if that is true, the number is appended to the result list (n). But you don't want that, you want to check if the 3 digits that make the number are pair, so you have to check the whole group.
For example you could do this:
for element in l:
pairs = 0
for j in range(3):
if int(str(element)[j]) % 2 == 0:
pairs += 1 # Each time a digit of the number is pair, `pairs` variable increase in one
if pairs == 3: # If the 3 digits are true it append your number
n.append(str(element))
That is my first idea of how to improve your code, but instead of element and pairs I use j and v, (also I don't use range(3), I just iterate over the stringed number).
If you are looking for something "better" you could try to use a list comprehension like all(int(j) % 2 == 0 for j in str(i)). That iterate over all the digits to check if the are pair, if all the checks are true (like 222, or 284) it returns true.
Let me know if I should explain something more.
Try this method. You don't need to check all the numbers.
You just need to change the range statement from range(100, 401) to range (100, 401, 2) and add some checks as the Numbers which have first digit as Odd you can skip all the 100 numbers and then in next 10 series you can skip 10 if the tenth digit is odd. It reduces the complexity and decreases your processing time.
l = range(100, 401, 2)
n = []
for i in l:
s = str(i)
if int(s[0]) % 2 == 1:
remainder = i % 100
i = i - remainder + 100 - 1
continue
elif int(s[1])%2 == 1:
remainder = i % 10
i = i - remainder + 10 - 1
continue
n.append(s)
print(",".join(n))
How can I remove even numbers from a list?
a = []
i = 0
while i < 10:
c = int(raw_input('Enter an integer: '))
a.append(c)
i += 1 # this is the same as i = i + 1
for i in a:
if i % 2 == 0:
a.remove(i)
print(a)
This keeps asking for numbers even after 10 have been entered
Why not preventing the append if the number is even, instead of adding and then checking for removal?
a = []
counter = 0
while counter < 10:
c = int(raw_input('Enter an integer: '))
if c % 2 != 0:
a.append(c)
counter += 1
print(a)
i is reassigned by the for statement. Use a different variable.
If you want to see how to 'filter' a list according to a predicate, here is an example:
a_without_even = filter(lambda x: x%2==1, a)
def removalDiffMethod(self, array):
l=0
r=len(array)
while l<r:
if array[l]%2==0:
array[l:r] = array[l+1:r+1]
r-=1
else:
l+=1
return array[:r]
Something like this?
your_dirty_list = [2,3,3,3,4,4,2,2,7,7,8]
your_clean_list = [clean_dude for clean_dude in your_dirty_list if clean_dude % 2]
Out[]: [3, 3, 3, 7, 7]
Here is my original code:
x = input("Please input an integer: ")
x = int(x)
i = 1
sum = 0
while x >= i:
sum = sum + i
i += 1
print(sum)
Here is what the second part is:
b) Modify your program by enclosing your loop in another loop so that you can find consecutive sums. For example , if 5 is entered, you will find five sum of consecutive numbers so that:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
I have been stuck on this for 3 days now, and I just can't understand how to do it. I have tried this but to no avail.
while x >= i:
sum_numbers = sum_numbers + i
past_values = range(i)
for ints in past_values:
L = []
L.append(ints)
print(L, "+", i, "=", sum_numbers)
i += 1
Can anyone just help steer my in the correct direction? BTW. it is python 3.3
You could do this in one loop, by using range to define your numbers, and sum to loop through the numbers for you.
>>> x = input("Please input an integer: ")
Please input an integer: 5
>>> x = int(x)
>>>
>>> for i in range(1, x+1):
... nums = range(1, i+1)
... print(' + '.join(map(str, nums)), '=', sum(nums))
...
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
range(1, x+1) would give me [1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.
nums = range(1, i+1) notice we are using i instead here, (taken from the range above), which I am using to define which number I am up to in the sequence.
' + '.join(map(str, nums)):
map(str, nums) is used to convert all elements of nums into strings using str, since the join method expects an iterable filled with strings.
' + '.join is used to "join" elements together with a common string, in this case, ' + '. In cases where there is only 1 element, join will just return that element.
sum(nums) is giving you the sum of all numbers defined in range(1, i+1):
When nums = range(1, 2), sum(nums) = 1
When nums = range(1, 3), sum(nums) = 3
Etc...
reduce(lambda x,y:x+y,range(x+1))
You don't have to use a while loop, 2 for will do the trick nicely and with a more natural feeling.
x = input("Please input an integer : ")
x = int(x)
item = range(1, x + 1)
for i in item:
sum = 0
for j in range(1, i + 1):
sum = sum + j
print(str(sum))
Using list comprehension in python:
x = input("Please input an integer: ")
x = int(x)
i = 1
sums = [(((1+y)*y)//2) for y in range(i, x+1)] # creates list of integers
print(sums) # prints list of sums on one line
OR
[print(((1+y)*y)//2) for y in range(i, x+1)] # prints sums on separate line