I've tried to get numbers' list between 0 and100,000. and then i want to multiply every second digits of the list. I have no idea how to get the ervery second digit of the numbers.
def breakandSum():
if 0<=x<100000:
digits=(map(int,str(x)))
return digits
To get the second digit from the right in base 10, you would first mod the number by 100 to truncate the leading digits, then take the integer result and divide by the integer 10 to truncate the trailing digits.
Here's a quick example where x = 4567 which extracts the second base 10 digit from the right, or the "tens" digit, which is "6" in this example:
>>> x = 4567
>>> x = x % 100
>>> x = x / 10
>>> print x
6
If you wanted to put all the digits in a list, you could just extract the right-most digit, append it to the list, then truncate and continue the loop as shown here:
>>> x = 4567
>>> xdigit = []
>>> while x > 0:
... xdigit.append(x % 10)
... x = x / 10
...
>>> print xdigit
[7, 6, 5, 4]
>>>
From here you can then get every second digit using a list comprehension and filter:
>>> every_other_digit = [xdigit[i] for i in filter(lambda j: j % 2 == 0, range(len(xdigit)))]
>>> print every_other_digit
[7, 5]
Which if you need to multiply these digits you can now just iterate over this list to get the final product:
>>> answer = 1
>>> for k in every_other_digit: answer *= k
...
>>> print answer
35
There is a more concise way of doing it:
digitSum = sum(x * 2 for x in list(map(int, str(num)))[::2])
Where:
str(num) turns num into a string
list(map(int, str(num))) for every element in string turn it back to an int and put it in a list
list(...)[::2] for every other element in the list starting from the leftmost element
x * 2 for x in list(...)[::2] for each element in the list multiply it by 2
sum(...) add every element from the iteration
Edit: sorry I thought you wanted to multiply each by a specific number if you want to multiply every other you just go:
import math
digitSum = math.prod(x for x in list(map(int, str(num)))[::2])
Related
I have a problem with the task, I need to input numbers and print it like a histogram with symbol ($). One unit is one ($) symbol.
For example:
input
1 5 3 2
print
$
$$$$$
$$$
$$
The code at the moment:
number = int(input())
while (number > 0):
print('$' * number)
number = 0
This works only with one number.
What need to do to code work properly?
You can do that like the follwoing,
>>> x = input("Enter the numbers: ") # use `raw_input` if `python2`
Enter the numbers: 1 2 3 4 5
>>> x
'1 2 3 4 5'
>>> y = [int(z) for z in x.split()]
>>> y
[1, 2, 3, 4, 5]
>>> for i in y:
... print('$' * i)
...
$
$$
$$$
$$$$
$$$$$
>>>
You're close and your thinking is right.
When you input() a string a numbers separated by a space, you need to convert each number into an integer, because by default all arguments are string for input.
You can use the map function to convert each input to integer.
inp = map(int, input().split())
Here input().split() converts 1 5 3 2 to ['1', '5', '3', '2']
Then applying map(int, [1, 5, 3, 2]) is equivalent to doing int(1), int(5) to each element.
Syntax of map: map(function, Iterable) function is int() in out case.
Then as you have the integers, all you need to do is take each value and print the number of '$'
for val in inp:
print('$'*val)
Here's the complete code:
inp = map(int, input().split())
for val in inp:
print('$'*val)
$
$$$$$
$$$
$$
You could try this
#get numbers as string
numbers = input('Enter numbers separated by <space> :')
# split numbers (create list)
nums = numbers.split(' ')
#loop each number
for num in nums:
print_num = ''
#create what to print
for i in range(int(num)):
print_num = print_num + '$'
#print
print(print_num)
numbers = raw_input("input :")
for number in [li for li in numbers.split(" ") if li.isdigit()]:
print('$' * int(number))
I need to create a list of values of a specified length which are unique. The way i am doing this currently is using
[str(i+1).ljust(subscriber_length, "0") for i in range(count)]
However this does not give unique numbers as if subscriber length is > 9 then n, n0 and n00 all give the same value eg, 1, 10 and 100 all give 100 as a value.
I know there must be a better way of doing this.
The expected output needs to be a string of digits (at the moment numbers is fine) of Length (subscriber_length) this is inserted into a CSV file and processed so preceding 0's don't work.
as an example if subscriber_length was 7 an acceptable range would be
|ID |
|1000000|
|1000001|
|1000002|
as this is test data what the values are isn't important, what is important is they are unique and there is no possibility of preceding 0's being stripped.
The range function supports setting a starting value, so you can set that to a suitable value and then just cast each value to str.
If you want identifiers to be seven characters long, set the start value to 1000000 (10 ** 6):
>>> count = 100
>>> subscriber_length = 7
>>> start = 10 ** (subscriber_length -1)
>>> end = start + count
>>> L = [str(i) for i in range(start, end)]
# There's no duplication
>>> len(L) == len(set(L)) == count
True
# All the values are the correct length
>>> all(len(x) == subscriber_length for x in L)
True
The code still works for lengths greater than nine.
>>> count = 100
>>> subscriber_length = 12
>>> start = 10 ** (subscriber_length -1)
>>> end = start + count
>>> L = [str(i) for i in range(start, end)]
>>> len(L) == len(set(L)) == count
True
>>> all(len(x) == subscriber_length for x in L)
True
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0]):
print('number is {}'.format(i))
Hey, I was making program where I needed to to access lists elements particular digits like if one list is [12,23,34] and another is [13,34],I want to access the first elements i.e 12's digits i.e 1 & 2 and compare it with another list and if any equal digit occurs i want to print the first element of the first list.
Like in our example 12 & 13 have 1 as equal digit I want to print 12.I am trying it from several days but getting stuck.And also I tried converting it in string then also some problem arised.
In the above example I am getting the particular digits printed like this:
number is 1
number is 3
number is 3
number is ,
number is ,
number is 1
number is 4
I dont want the 'comma' ,and if a match occurs the number should be printed as mentioned in the example.Any help would be highly appreciated.
Thanks.
Wouldn't keeping them as lists be easier to work with?
If you only want to compare the same indexes, then:
In []:
l1 = [12,23,34]
l2 = [13,34]
for a, b in zip(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
Or you want to check any index:
In []:
import itertools as it
l1 = [12,23,34]
l2 = [13,34]
for a, b in it.product(l1, l2):
if a//10 == b//10:
print(a)
Out[]:
12
34
try this
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2)
for j in str2:
for i in str1:
if (j[0]==i[0] and (i and j != ',')):
print('number is {}'.format(i))
output
12,23,34
13,34
number is 1
number is 3
number is 3
number is 3
number is 3
number is 4
This should work for your use-case
list1 = [123, 12, 32232, 1231]
list2 = [1232, 23243, 54545]
def find_intersection(list1, list2):
list2_digits = set.union(*[get_digits(x) for x in list2])
for num1 in list1:
digits1 = get_digits(num1)
for num2 in list2:
digits2 = get_digits(num2)
if digits1.intersection(digits2):
print 'Found Match', num1, num2 # We found a match
# Break here unless you want to find all possible matches
def get_digits(num):
d = set()
while num > 0:
d.add(num % 10)
num = num / 10
return d
find_intersection(list1, list2)
I'm not sure I totally understand the question, however:
list1 = [13,23,34]
list2 = [24,18,91]
list1 = list(map(str,list1)) #Map the arrays of ints to arrays of strings
list2 = list(map(str,list2))
for j in list1:
for i in list2:
for character in j:
if character in i:
print(j+' matches with '+i)
break
Prints out:
13 matches with 18
13 matches with 91
23 matches with 24
34 matches with 24
So, maybe this question will sound very beginnerish, but I just don't know how I should begin with this example:
So the example is:
I have a list for example 13 items long (1,2,3,4...13)
There's a given number, let's say 6
The program needs to show me in a list, in what order are the numbers going to fall out. If the second number is 6, it means every time the sixth item is the next whcih is going to fall out. But my problem is that how could I tell python that if the index number goes up too high, it should start counting again from the beggining?
This is what I made myself so far
x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
#n = 1
#id = 0
numbers = [n for n in range(x+1)]
fallsout = []
numbers.remove(30)
for i in numbers:
if i % y == 0:
fallsout.append(i)
print (numbers)
print (fallsout)
Here's an example what should be in the input and output:
Input:
x = 13
y = 6
Output: 6 12 5 13 8 3 1 11 2 7 4 10 9
Okay, looks like you want to copy every 6th element from numbers into fallout and then remove the element from numbers, and continue on in a cyclic fashion until numbers is empty.
import copy
x = int(input("Number of items (numbers): "))
y = int(input("Fall-out number: "))
# list should start from 1 as by the example
numbers = [n for n in range(1,x+1)]
# deep copy to preserve original list
numbers_copy = copy.deepcopy(numbers)
fallsout = []
count = y
while len(numbers_copy)!=0:
fallsout.append(numbers_copy[count-1])
# remove element
del numbers_copy[count-1]
# handle starting edge
if count == 0:
count = 1
# handle last edge
if numbers_copy != []:
count = (count+y-1)%len(numbers_copy)
print numbers
print fallsout
Output is
Number of items (numbers): 13
Fall-out number: 6
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[6, 12, 5, 13, 8, 3, 1, 11, 2, 7, 4, 10, 9]
Explanation:
Suppose I have a array numbers = [1,2,3,4,5,6] of length=6, and I am using an counter "count" to iterate through the list. So that,
numbers[count] = 2 (when count=1)
Then to look at the next element, I would use numbers[count+1].
To jump back to the starting of the list, we use modulus operation,
count = (count+number_of_steps)%len(numbers)
eg, at index=4 and to jump 3 steps, next index would be (4+3)%6 = 1
Now we have to copy every yth element from the list,so we use,
fallsout.append(numbers_copy[count-1]) # count-1 as we are counting from 0
Then we remove that number from the list,
del numbers_copy[count-1]
Then we jump forward count by y steps by modulus as discussed above,
count = (count+y-1)%len(numbers_copy) # again -1 as we count from 0
The length of numbers needs to be calculated again as the list could change due to deleting of elements.
This might be a very simple question, but it's giving me a lot of trouble.
Code:
def search_likes(passed_list): #passed_list contains links to find below
print("Found",len(passed_list),"videos, now finding likes.")
x = 0
print("Currently fidning likes for video",x,".")
while x< len(passed_list):
likeFINDER = []
r = requests.get(passed_list[0])
soup= BeautifulSoup(r.content, 'lxml')
d_data = soup.find_all("span", {"class": "yt-uix-button-content"}) #Location of the number i'm looking for
likeFINDER.append(d_data)
str1= ''.join(str(e) for e in likeFINDER) #Converts the list into a string
likeNUMBER= (int(''.join(list(filter(lambda x: x.isdigit(), str1))))) #Removes string and leaves integers
x+=1 #count
Output:
845528455314391440
I would like to split the code where it begins to repeat itself. Ie ['84552','8455314391440']
If you have any insight on how to do this I would really appreciate it!
Thanks,
Ben
Given a string s containing your numbers, and a number n that is the size of the repetition you want to find, then you can do:
s.find(s[:n], n)
This finds the index of the first occurrence, after the start of the string, that is equal to the first n characters of the string. For example:
s = str(845528455314391440)
n = 3
r = s.find(s[:n], n)
print(r)
Output:
5
You can then use that to split the string and turn the parts into numbers:
a, b = int(s[:r]), int(s[r:])
print(a, b)
Output:
84552 8455314391440
All combined into a function, accounting for numbers without repitition:
def split_repeat(i, n):
s = str(i)
r = s.find(s[:n], n)
if r == -1:
return None
else:
return int(s[:r]), int(s[r:])
Usage:
print(split_repeat(845528455314391440, 3))
print(split_repeat(876543210, 3))
print(split_repeat(1122, 3))
Output:
(84552, 8455314391440)
None
None
Here is a simple example that will show yo how you can match the numbers of how ever many of the first few digits you need to. This example will use the first 2 digits.
we can turn the numbers into strings then use string_name[:2] where 2 is the number of digits from the front you want to match. I am using the number 11 to match my list of numbers but this is only for an example.
Let me know if you have any question:
set_list = []
var1 = 11012314
for i in range(1000):
set_list.append(i)
for item in set_list:
x = str(item)
y = str(var1)
if x[:2] == y[:2]:
print(item)
When you run this code you will see numbers printed to the console that match the first two digits to our variable with the value 11.
you can do :
def myfunc(num):
a=str(num)
for i in range(len(a)):
l1=a[:i]
l2=a[i:]
if l1 in l2:
b=l1
return [int(b), int(a[len(b):])]
that will give you :
>>> myfunc(845538455314391440)
[84553, 8455314391440]