I can't figure out how to properly slice a string.
There is a line: "1, 2, 3, 4, 5, 6". The number of characters is unknown, numbers can be either one-digit or three-digit
I need to get the last value up to the nearest comma, that means I need to get the value (6) from the string
you can try to split and get last value
string = "1, 2, 3, 4, 5, 6"
string.split(',')[-1]
>>> ' 6'
add strip to get rid of the white spaces
string.split(',')[-1].strip(' ')
>>> '6'
Better use str.rsplit, setting maxsplit=1 to avoid unnecessarily splitting more than once:
string = "1, 2, 3, 4, 5, 6"
last = string.rsplit(', ', 1)[-1]
Output: '6'
It seems to me the easiest way would be to use the method split and divide your string based on the comma.
In your example:
string = '1, 2, 3, 4, 5, 6'
last_value = string.split(', ')[-1]
print(last_value)
Out[3]: '6'
Here's a function that should do it for you:
def get_last_number(s):
return s.split(',')[-1].strip()
Trying it on a few test strings:
s1 = "1, 2, 3, 4, 5, 6"
s2 = "123, 4, 785, 12"
s3 = "1, 2, 789654 "
...we get:
print (get_last_number(s1))
# 6
print (get_last_number(s2))
# 12
print (get_last_number(s3))
# 789654
First of all you have to split the string:
string = '1, 2, 3, 4, 5, 6'
splitted_str = string.split(',')
Then, you should get the last element:
last_elem = splitted_str[-1]
Finally, you have to delete the unnecessary white spaces:
last_number_str = last_elem.strip()
Clearly this answer is a string type, if you need the numeric value you can cast the type by using
last_elem_int = int(last_elem_str)
Hope that helps
Related
So I have a list of strings such as this:
my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
I want, for each string, to retrieve the position where the first and last letters appear. Or in other words, to find the position of the first character that isn't a "-" and the position of the last character that isn't a "-". It would be perfect if I could save the result as two lists, one of the first positions and another for the last.
I've tried using find() at least for the first position but since the character I'm trying to find is one of several letters, I don't know how to do it.
The output I wanted was something like this:
first_positions=[3,2,10,1,4]
last_positions=[17,7,25,11,23]
Thanks in advance for any answer
Here is an implementation without using regex.
my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
def find_i(word):
first = None
last = None
for i, letter in enumerate(word):
if first == None:
if letter != '-':
first = i
else:
if letter != '-':
last = i
return (first, last)
r = list(map(find_i, my_list))
print(r) #I like this output more, but it is up to you.
first_positions = [i[0] for i in r]
last_positions = [i[1] for i in r]
print(first_positions)
print(last_positions)
Output:
[(3, 17), (2, 7), (10, 25), (1, 10), (4, 23)]
[3, 2, 10, 1, 4]
[17, 7, 25, 10, 23]
There is possibly a nicer way to do this, but one way to get it is to match all non-hyphen characters and get the start index of that match, and then to match all non-hyphen characters which are followed by 0 or more hyphens and then the end of the line, and get the start index of that match, and compile them into li
>>> import re
>>> [re.search(r'[^-]+', string).start() for string in my_list]
[3, 2, 10, 1, 4]
>>> [re.search(r'[^-]-*$', string).start() for string in my_list]
[17, 7, 25, 10, 23]
Check string is alphabet or not and then add index of string in the list. if you want to find first positions then by default function takes first then it returns the first indexes of string else it returns the last indexes
my_list=["---abcdefgh----abc--","--abcd-a--","----------abcdefghij----ab-","-abcdef---a-","----abcdefghijklm----abc--"]
def get_index(string,find='first'):
index_lt=[]
for idx,char in enumerate(string):
if char.isalpha():
index_lt.append(idx)
return index_lt[0] if find=='first' else index_lt[-1]
print([get_index(string) for string in my_list])
#[3, 2, 10, 1, 4]
print([get_index(string,find='last') for string in my_list])
#[17, 7, 25, 10, 23]
I am looking to develop a program that identifies individual words in a sentence and replaces each word with the position of each word in the list.
For example, this sentence:
HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON
This contains 11 different words and I'd like my program to recreate the sentence from the positions of these 11 words in a list:
1,2,3,4,5,6,7,8,9,10,5,11,6,7
I'd then like to save this new list in a separate file. So far I have only gotten this:
#splitting my string to individual words
my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
splitted = my_string.split()
>>> my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
>>> splitted = my_string.split()
>>> order = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 11, 6, 7
>>> new_str = ' '.join(splitted[el] for el in order)
'I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP IN ME PYTHON PLEASE'
Updated according to your comment:
You are looking for index() method.
my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
splitted = my_string.split()
test = "I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP IN ME PYTHON PLEASE".split()
print ', '.join(str(splitted.index(el)) for el in test)
>>> 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 11, 6, 7
** we suppose that there are no repeating words
my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
splitted = my_string.split()
d = {}
l=[]
for i,j in enumerate(splitted):
if j in d:
l.append(d[j])
else:
d[j]=i
l.append(i)
print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 11, 5, 6]
Try:
>>> from collections import OrderedDict
>>> my_string = "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
>>> splitted = my_string.split()
>>> key_val = {elem : index + 1 for index, elem in enumerate(list(OrderedDict.fromkeys(splitted)))}
>>> [key_val[elem] for elem in splitted]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 11, 6, 7]
list(OrderedDict.fromkeys(splitted)) create a list having only unique elements from splitted.
key_val is dictionary of these unique elements as key and their index as the value.
Try this:
sentence= "HELLO I NEED SOME HELP IN PYTHON PLEASE CAN YOU HELP ME IN PYTHON"
lst = sentence.split()
lst2= []
for i in lst:
if i not in lst2:
lst2.append(i)
inp = inputSentence.split()
output=[]
for i in inp:
print lst2.index(i)+1,
output.append(lst2.index(i)+1)
The index is evaluated and stored in lst2. You just have to pass your input string to inputSentence , so that you are able to test this code.
benstring = input ('enter a sentence ')
print('the sentence is', benstring)
ben2string = str.split(benstring)
print('the sentence now looks like this',ben2string)
x=len(ben2string)
for i in range(0,x):
if x is
Sentence = input("Enter a sentence!")
s = Sentence.split() #Splits the numbers/words up so you can see them individually.
another = [0]
for count, i in enumerate(s):
if s.count(i) < 2:
another.append(max(another) + 1) #adds +1 each time a word is used, showing the position of each word.
else:
another.append(s.index(i) +1)
another.remove(0)
print(another) #prints the number that word is in.
I am scanning a column in Python, which is full of integers. There are some double digit numbers.
d = []
for Column in ReadDataSourceFile: #ReadDataSourceFile works well. Its file open and delimiter
if Column[1] == 'Something' and Column[0] == 'Somewhere':
countFL += 1
print Column[5]
some = map(int, Column[5])
d.extend(some)
print d
Here Column[5] is 1, 15, 23, 1, 4, 5. But the print displays [1, 1, 5, 2, 3, 1, 4, 5]
Probably some = map(int, Column[5]) split number on the digits
print map(int, '15')
[1, 5]
So print some to check it.
Maybe you need only some = int(Column[5])
EDIT: try
print Column[5]
some = int(Column[5])
d.append(some)
Your first output looks like a string
Maybe this will work:
Column[5].split(',')
IF I have a dictionary:
mydict = {"g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt" : 0,
"g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt" : 1,
"g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt" : 2,
"g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt" : 3,
"g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt" : 4,
"g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt" : 5,
"h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG-CMVP1_Y1000-FIX.txt" : 6,
"g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt" : 7,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG-CMVP2_Y1000-FIX.txt" : 8,
"h18_84pp_3A_MVP3_GoodiesT1-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 9,
"p18_84pp_2B_MVP1_GoodiesT2-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 10}
I want to extract the common part g18_84pp_2A_MVP_GoodiesT0 before the first -.
also I want add a _MIX to follow g18_84pp_2A_MVP_GoodiesT0 when finding the particular word MIX in first group . Assume that I am able to classify two groups depending on whether is MIX or FIX in myDict, then the final Output dictionary:
OutputNameDict= {"g18_84pp_2A_MVP_GoodiesT0_MIX" : 0,
"h18_84pp_3A_MVP_GoodiesT1_FIX" : 1,
"p18_84pp_2B_MVP_FIX": 2}
Is there any function I could use to find common part? How pick up the word before or after particular symbol like - and find particular words like MIX or FIX?
You can use split to get the common part:
s = "g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt"
n = s.split('-')[0]
In fact, split will give you a list of each token delimited by '-', so s.split('-') yields:
['g18_84pp_2A_MVP1_GoodiesT0', 'HKJ', 'DFG_MIX', 'CMVP1_Y1000', 'MIX.txt']
To see if MIX or FIX is in a string, you can use in:
if 'MIX' in s:
print "then MIX is in the string s"
If you want to get rid if the numbers after 'MVP', you can use re module:
import re
s = 'g18_84pp_2A_MVP1_GoodiesT0'
s = re.sub('MVP[0-9]*','MVP',s)
Here is a sample function to get a list of the common parts:
def foo(mydict):
return [re.sub('MVP[0-9]*', 'MVP', k.split('-')[0]) for k in mydict]
You can use the index() function to find your dashes, then with that knowledge you can take the rest of the string past that point. For instance,
mydict = {"g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt" : 0,
"g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt" : 1,
"g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt" : 2,
"g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt" : 3,
"g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt" : 4,
"g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt" : 5,
"g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt" : 6,
"h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG_MIX-CMVP1_Y1000-FIX.txt" : 7,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG_MIX-CMVP2_Y1000-FIX.txt" : 8,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG_MIX-CMVP3_Y1000-FIX.txt" : 9}
for value in sorted(mydict.iterkeys()):
index = value.index('-')
extracted = value[index+1:-4] # Goes past the first occurrence of - and removes .txt from the end
print extracted[-3:] # Find the last 3 letters in the string
Will print the following:
MIX
MIX
MIX
MIX
MIX
MIX
MIX
FIX
FIX
FIX
Then if statements can be used to do what you would like.
If you want to extract just the common part.
index = value.index('-')
extracted = value[:index] # Will get g18_84pp_2A_MVP1_GoodiesT0
Then to figure out the ending to use. If you know the ending of the mydict value will always be MIX.txt or FIX.txt then you can do this.
for value in sorted(mydict.iterkeys()):
ending = value[-7:-4]
index = value.index('-')
extracted = value[:index]
print "%s_%s" % (extracted, ending)
Which prints
g18_84pp_2A_MVP1_GoodiesT0_MIX
g18_84pp_2A_MVP2_GoodiesT0_MIX
g18_84pp_2A_MVP3_GoodiesT0_MIX
g18_84pp_2A_MVP4_GoodiesT0_MIX
g18_84pp_2A_MVP5_GoodiesT0_MIX
g18_84pp_2A_MVP6_GoodiesT0_MIX
g18_84pp_2A_MVP7_GoodiesT0_MIX
h18_84pp_3A_MVP1_GoodiesT1_FIX
h18_84pp_3A_MVP2_GoodiesT1_FIX
h18_84pp_3A_MVP2_GoodiesT1_FIX
Then you add it to the extracted dictionary.
Thanks for the answers. My complete code as following. Any suggestion to optimize it?
import re
mydict = {"g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt" : 0,
"g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt" : 1,
"g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt" : 2,
"g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt" : 3,
"g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt" : 4,
"g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt" : 5,
"h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG-CMVP1_Y1000-FIX.txt" : 6,
"g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt" : 7,
"h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG-CMVP2_Y1000-FIX.txt" : 8,
"h18_84pp_3A_MVP3_GoodiesT1-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 9,
"p18_84pp_2B_MVP1_GoodiesT2-HKJ-DFG-CMVP3_Y1000-FIX.txt" : 10}
ExtractDict = {}
start = 0
for stringList in sorted(mydict.iterkeys()):
stringList = stringList.split('.')[0]
underscore = stringList.split('_')
Area= re.split('[0-9]+',stringList.split('_')[3])[0] # MVP and etc.
CaseNameString=underscore[0]+"_"+underscore[1]+"_"+underscore[2]+"_"+Area #g18_84pp_2A_MVP_GoodiesT0 and etc.
postfix= stringList.split('-')[4]
Newstring= CaseNameString + "_" + postfix
ExtractDict[Newstring]= start
start += 1
startagain =0
OutputNameDict = {}
for OutputNameList in sorted(ExtractDict.iterkeys()):
OutputNameDict[OutputNameList] = startagain
startagain +=1
#OutputNameDict = {'h18_84pp_3A_MVP_FIX': 1, 'p18_84pp_2B_MVP_FIX': 2, 'g18_84pp_2A_MVP_MIX': 0}
This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
Closed last month.
I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.
Just create a string out of it.
myinteger = 212345
number_string = str(myinteger)
That's enough. Now you can iterate over it:
for ch in number_string:
print ch # will print each digit in order
Or you can slice it:
print number_string[:2] # first two digits
print number_string[-3:] # last three digits
print number_string[3] # forth digit
Or better, don't convert the user's input to an integer (the user types a string)
isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)
For more information read a tutorial.
while number:
digit = number % 10
# do whatever with digit
# remove last digit from number (as integer)
number //= 10
On each iteration of the loop, it removes the last digit from number, assigning it to digit.
It's in reverse, starts from the last digit, finishes with the first
list_of_ints = [int(i) for i in str(ISBN)]
Will give you a ordered list of ints. Of course, given duck typing, you might as well work with str(ISBN).
Edit: As mentioned in the comments, this list isn't sorted in the sense of being ascending or descending, but it does have a defined order (sets, dictionaries, etc in python in theory don't, although in practice the order tends to be fairly reliable). If you want to sort it:
list_of_ints.sort()
is your friend. Note that sort() sorts in place (as in, actually changes the order of the existing list) and doesn't return a new list.
On Older versions of Python...
map(int,str(123))
On New Version 3k
list(map(int,str(123)))
(number/10**x)%10
You can use this in a loop, where number is the full number, x is each iteration of the loop (0,1,2,3,...,n) with n being the stop point. x = 0 gives the ones place, x = 1 gives the tens, x = 2 gives the hundreds, and so on. Keep in mind that this will give the value of the digits from right to left, so this might not be the for an ISBN but it will still isolate each digit.
Convert it to string and map over it with the int() function.
map(int, str(1231231231))
Recursion version:
def int_digits(n):
return [n] if n<10 else int_digits(n/10)+[n%10]
Converting to str is definitely slower then dividing by 10.
map is sligthly slower than list comprehension:
convert to string with map 2.13599181175
convert to string with list comprehension 1.92812991142
modulo, division, recursive 0.948769807816
modulo, division 0.699964046478
These times were returned by the following code on my laptop:
foo = """\
def foo(limit):
return sorted(set(map(sum, map(lambda x: map(int, list(str(x))), map(lambda x: x * 9, range(limit))))))
foo(%i)
"""
bar = """\
def bar(limit):
return sorted(set([sum([int(i) for i in str(n)]) for n in [k *9 for k in range(limit)]]))
bar(%i)
"""
rac = """\
def digits(n):
return [n] if n<10 else digits(n / 10)+[n %% 10]
def rabbit(limit):
return sorted(set([sum(digits(n)) for n in [k *9 for k in range(limit)]]))
rabbit(%i)
"""
rab = """\
def sum_digits(number):
result = 0
while number:
digit = number %% 10
result += digit
number /= 10
return result
def rabbit(limit):
return sorted(set([sum_digits(n) for n in [k *9 for k in range(limit)]]))
rabbit(%i)
"""
import timeit
print "convert to string with map", timeit.timeit(foo % 100, number=10000)
print "convert to string with list comprehension", timeit.timeit(bar % 100, number=10000)
print "modulo, division, recursive", timeit.timeit(rac % 100, number=10000)
print "modulo, division", timeit.timeit(rab % 100, number=10000)
After own diligent searches I found several solutions, where each has advantages and disadvantages. Use the most suitable for your task.
All examples tested with the CPython 3.5 on the operation system GNU/Linux Debian 8.
Using a recursion
Code
def get_digits_from_left_to_right(number, lst=None):
"""Return digits of an integer excluding the sign."""
if lst is None:
lst = list()
number = abs(number)
if number < 10:
lst.append(number)
return tuple(lst)
get_digits_from_left_to_right(number // 10, lst)
lst.append(number % 10)
return tuple(lst)
Demo
In [121]: get_digits_from_left_to_right(-64517643246567536423)
Out[121]: (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
In [122]: get_digits_from_left_to_right(0)
Out[122]: (0,)
In [123]: get_digits_from_left_to_right(123012312312321312312312)
Out[123]: (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
Using the function divmod
Code
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst)
Demo
In [125]: get_digits_from_right_to_left(-3245214012321021213)
Out[125]: (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
In [126]: get_digits_from_right_to_left(0)
Out[126]: (0,)
In [127]: get_digits_from_right_to_left(9999999999999999)
Out[127]: (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
Using a construction tuple(map(int, str(abs(number)))
In [109]: tuple(map(int, str(abs(-123123123))))
Out[109]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [110]: tuple(map(int, str(abs(1412421321312))))
Out[110]: (1, 4, 1, 2, 4, 2, 1, 3, 2, 1, 3, 1, 2)
In [111]: tuple(map(int, str(abs(0))))
Out[111]: (0,)
Using the function re.findall
In [112]: tuple(map(int, re.findall(r'\d', str(1321321312))))
Out[112]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [113]: tuple(map(int, re.findall(r'\d', str(-1321321312))))
Out[113]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [114]: tuple(map(int, re.findall(r'\d', str(0))))
Out[114]: (0,)
Using the module decimal
In [117]: decimal.Decimal(0).as_tuple().digits
Out[117]: (0,)
In [118]: decimal.Decimal(3441120391321).as_tuple().digits
Out[118]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
In [119]: decimal.Decimal(-3441120391321).as_tuple().digits
Out[119]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
Use the body of this loop to do whatever you want to with the digits
for digit in map(int, str(my_number)):
I have made this program and here is the bit of code that actually calculates the check digit in my program
#Get the 10 digit number
number=input("Please enter ISBN number: ")
#Explained below
no11 = (((int(number[0])*11) + (int(number[1])*10) + (int(number[2])*9) + (int(number[3])*8)
+ (int(number[4])*7) + (int(number[5])*6) + (int(number[6])*5) + (int(number[7])*4) +
(int(number[8])*3) + (int(number[9])*2))/11)
#Round to 1 dp
no11 = round(no11, 1)
#explained below
no11 = str(no11).split(".")
#get the remainder and check digit
remainder = no11[1]
no11 = (11 - int(remainder))
#Calculate 11 digit ISBN
print("Correct ISBN number is " + number + str(no11))
Its a long line of code, but it splits the number up, multiplies the digits by the appropriate amount, adds them together and divides them by 11, in one line of code. The .split() function just creates a list (being split at the decimal) so you can take the 2nd item in the list and take that from 11 to find the check digit. This could also be made even more efficient by changing these two lines:
remainder = no11[1]
no11 = (11 - int(remainder))
To this:
no11 = (11 - int(no11[1]))
Hope this helps :)
Similar to this answer but more a more "pythonic" way to iterate over the digis would be:
while number:
# "pop" the rightmost digit
number, digit = divmod(number, 10)
How about a one-liner list of digits...
ldigits = lambda n, l=[]: not n and l or l.insert(0,n%10) or ldigits(n/10,l)
Answer: 165
Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.
from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
if n % 11 and is_ps(sum(map(int, str(n)))):
count += 1
print "#%i: %s" % (count, n)
Just assuming you want to get the i-th least significant digit from an integer number x, you can try:
(abs(x)%(10**i))/(10**(i-1))
I hope it helps.