Adding slicing numbers using a loop - python

I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....

you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic

>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16

>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'

It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).

Related

Python descending number

I need to create a program that will take a integer, (e.g. 4586), and return the number with the digits in descending order (e.g. 8654).
num = 4586
num1 = num #num1 is a string
descendingNumber = []
for i in num1:
for j in i:
if i < j:
descendingNumber.append(i)
else:
descendingNumber.insert(1,i)
What am I doing wrong?
That insertion process doesn't look quite right. You can accomplish this in one line using built-ins.
First, we get the individual digits by using str(), and then sort them using sorted(). This gives us a list of digits, so we then use ''.join() to turn it back into a string. Finally, we cast the result back into an integer to get our desired output.:
int(''.join(sorted(str(num), reverse=True)))
This outputs:
8654

Python Code Error

What's wrong with this program in Python?
I need to take an integer input(N) - accordingly, I need to create an array of (N)integers, taking integers also as input. Finally, I need to print the sum of all the integers in the array.
The input is in this format:
5
4 6 8 18 96
This is the code I wrote :
N = int(input().split())
i=0
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = int(input().split())
V.append(x)
i+=1
s+=x
print (s)
Its showing the following error.
Traceback (most recent call last):
File "main.py", line 1, in <module>
N = int(input().split())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
split() returns a list which you are trying to convert to an integer.
You probably wanted to convert everything in the list to an integer:
N = [int(i) for i in input().split()]
You can also use map:
N = list(map(int, input().split()))
You could use sys module to take the input when calling the program and a lambda function to convert the string items in list to integers. You could also make use of the built-in sum function. Something like that:
#!/usr/bin/env python
import sys
s = sum(i for i in map(lambda x: int(x), sys.argv[1].split(',')))
print s
Example:
python test.py 1,2,3,4
The output should be 10.
Modifying your code:
Now, if you want to modify your code to do what it intends to do, you could modify your code like that:
#!/usr/bin/env python
N = input()
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = input()
V.append(x)
s+=x
print (s)
Note 1: In python when you use range you don't have to manually increase the counter in the loop, it happens by default.
Note 2: the 'input()' function will maintain the type of the variable you will enter, so if you enter an integer you don't have to convert it to integer. (Have in mind that input() is not recommended to use as it can be dangerous in more complicated projects).
Note 3: You don't need to use '.split()' for your input.
You code fails because str.split() returns a list.
From the Python documentation
Return a list of the words in the string, using sep as the delimiter
string
If your input is a series of numbers as strings:
1 2 3 4
You'll want to iterate over the list returned by input.split() to do something with each integer.
in = input()
for num in in.split():
x.append(int(num))
The result of this will be:
x = [1,2,3,4]

inputted list keeps being interpreted as string

So I made this little code at school, and i know that input() can understand lists as is. I tried it again at home but it doesnt work. My school computer has python 2. something while my laptop has 3.4.
The code looks like this
a = input()
list = []
count = 0
for y in range(1, len(a)):
min = a[count]
for x in range(count +1, len(a)):
if min > a[x]:
min = a[x]
print(min)
a[count] = min #str object does not support item assignment
count=count+1
print (a)
I want to input a list such as [1,2,3,4,5] but what happens is, it reads the whole thing as a string, along with the commas, when i want to see it as a list of integers.
Python 3's input returns a string (same as Python 2's raw_input), whilst Python 2's input evaluates the text. To get similar behaviour, if you've got a valid Python list that can be evaluated, then you can use ast.literal_eval, eg:
import ast
a = ast.literal_eval(input())
# do other stuff with `a` here...
So you'd enter something like [1, 2, 3, 4, 5] as your input, and you'll end up with a being a Python list.
I assume your input would be something like: "1 2 3 4 5" -- judging by the code which comes later. This oufcourse is a string. If you want to work with the numbrs in the string as integers you need to:
a = input()
a = map(int, a.split())

Create variables dynamically inside 'for' loop

I'm new to python and trying to take some coding challenges to improve my skills. I've to take input in following ways:
2
3 1
4 3
First, I get number of test cases.(2 here) Then based on that, I've to get given number of test cases that are each 2 integers. 1st is the range and second is the number to be searched in the range.
What's the correct, pythonic way of getting the input. I was thinking like this but it's obviously incorrect
num_testcases = int(raw_input())
for i in num_testcases:
range_limit = int(raw_input())
num_to_find = int(raw_input())
raw_input() is going to be read one line at a time from STDIN, so inside the loop you need to use str.split() to get the value of range_limit and num_to_find. Secondly you cannot iterate over an integer(num_testcases), so you need to use xrange()(Python 2) or range()(Python 3) there:
num_testcases = int(raw_input())
for i in xrange(num_testcases): #considering we are using Python 2
range_limit, num_to_find = map(int, raw_input().split())
#do something with the first input here
Demo:
>>> line = '3 1'
>>> line.split()
['3', '1']
>>> map(int, line.split())
[3, 1]
Note that in Python 3 you'll have to use input() instead of raw_input() and range() instead of xrange(). range() will work in both Python 2 and 3, but it returns a list in Python 2, so it is recommended to use xrange().
Use for i in range(num_testcases): instead of for i in num_testcases. Have a look at range (or xrange in Python 2). range(a) produces an iterable from 0 to a - 1, so your code gets called the desired number of times.
Also, input and raw_input take input on encountering a newline, meaning that in range_limit = int(raw_input()), raw_input returns "3 1", which you can't just convert to int. Instead, you want to split the string using string.split and then convert the individual items:
num_testcases = int(raw_input())
for i in range(num_testcases):
range_limit, num_to_find = [int(x) for x in raw_input().split()]

Python truncating numbers in integer array

I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.

Categories

Resources