I am currently having x number in a list, and I am trying to convert inconsistent data that may be in 1 digit, 5 digit or 2 digit.
How can I convert all into 2 digit number?
Example:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]<100 or z[i]>10):
if(z[i]<100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
list_a = [5.2,1600,520,3600,13,55,4000]
result_list= List_Convert_2_Digit(list_a)
Result should yields: [52,16,52,36,13,55,40]
But the above code does not work and it's running forever.
I've tried mod, but it is not what I am looking for.
It looks like you just want to take the first two characters from each, and if there is a separator (dot in your case) ignore it.
In that case you can do this:
two_digit_list = [int(str(x).replace('.', '')[:2]) for x in List]
If other non numeric characters than a dot are going to appear your would have to deal with those as well of course :)
What this does is just converts the numbers to a string, removes dots and then grabs the first two characters and converts it back to an int.
EDIT: Since I saw you replied to someone above that single digit numbers should have 0 added to the end you can do this instead to cover that case:
two_digit_list = [int(str(x).replace('.', '')[:2]) if len(str(x).replace('.', '')) > 1 else int(f"{x}0") for x in List]
At that point it's a bit too long to be a pretty list comprehension so you could always just break it up into a for loop if it's unclear, might be a good exercise if nothing else :)
This is a simple solve to this.
yield_list = []
number_list = [5.2,1600,520,3600,13,55,4000]
for number in number_list:
string = str(number)
string =string.replace('.', '')
yield_list.append(string[:2])
yield_list
There is an error in your logic; your < and > are flipped. This code works:
def List_Convert_2_Digit(z):
for i in range(len(z)):
while(z[i]>100 or z[i]<10):
if(z[i]>100):
z[i]=z[i]/10
else:
z[i]=z[i]*10
return z
Solution that increases/decreases the numbers magnitude until we can get the left two digits:
def two_digit_list(lst):
rv = []
for item in lst:
if item < 10:
item *= 10
while item > 99:
item //= 10
rv.append(int(item))
return rv
Related
I'm having trouble with this code below.
My task is to create a function, that among the given numbers finds one that is different in evenness, and returns a position of that number. The numbers are given as a string. So far I have managed to convert the string into an integer list, then using for loop to iterate through each number.
The problem I'm encountering is that I've managed to return only the position of an odd number among the even numbers, and I can't continue on with the code for vice versa action, because it only returns the position of the odd number.
Here is the code:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into int
num_map = map(int, num_split)
# converting the object into list
list_num = list(num_map)
for n in list_num:
if not n%2 == 0:
return list_num.index(n) + 1
Your problem is, that you are assuming, that you are searching for the first even number. What you have to do, is to first decide, what you are searching for. You could for example simply first count the number of even numbers. If it is one, then you are looking for an even number, otherwise, you are looking for an odd. As you don't care for the actual numbers, I would map all of them to their value mod 2 as so:
num_map = list(map(lambda x: int(x) % 2, num_split))
Then, the rest is simple. For example like this:
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into even (0) or odd (1)
num_map = list(map(lambda x: int(x) % 2, num_split))
# return the correct position based on if even or odd is in search
evens = num_map.count(0)
if evens == 1:
return num_map.index(0) + 1
else:
return num_map.index(1) + 1
I came up with a similar and a little bit shorter solution
def iq_test(numbers):
# first check what im looking for "even" or "odd", map a lambda function that basically does it for me, using the numbers argument as a list type and afterwards cast it into a list so i can iterate later on
num_map = list(map(lambda x: 'e' if int(x) % 2 == 0 else 'o', numbers.split()))
# search for even numbers numbers
if num_map.count('e') == 1:
return num_map.index('e') + 1
# search for odd numbers numbers
return num_map.index('o') + 1
def iq_test(numbers):
# Splitting the "numbers" string
num_split = numbers.split()
# converting the splitted strings into int
num_map = map(int, num_split)
# converting the object into list
list_num = list(num_map)
for n in list_num:
if not n%2 == 0:
return list_num.index(n) + 1
Given a list, I need to print the numbers in sorted order and remove any duplicates. I am using python 3.7.2
My code:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = input().split()
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
However, whenever my input consists of a 2 digit number, the logic fails.
Eg. for input of 2 1 43 2 5, I get an output of 1 2 43 5.
This work perfectly for single digit numbers. Can someone help me out with this?
You only need a slight modification. You are comparing strings instead of numbers, so try this instead:
def sorted_elements(numbers):
return sorted(set(numbers))
testcase = int(input())
while testcase > 0:
numbers = map(int, input().split())
l = sorted_elements(numbers)
for x in l:
print (x, end = ' ')
print ()
testcase -= 1
If you want, you can also do:
numbers = (int(x) for x in input().split())
You can simplify this in various aspects. Sort by numeric value using an appropriate key function, use a for loop if you know the number of iterations beforehand, utilize appropriate string utils like str.join, etc.
testcases = int(input())
for _ in range(testcases):
print(' '.join(sorted(set(input().split()), key=int)))
You are going correct way with set(numbers) to remove duplicates. The problem comes from sorted with your numbers being list of strs not ints.
Try this:
x_numbers = input().split()
numbers = [int(x) for x in x_numbers]
Try it now:
testcase = int(input())
n=list(str(testcase))
results = map(int, n)
numbers= sorted(set(results))
print(numbers)
code here:https://repl.it/repls/SeriousRosybrownApplicationprogrammer
We can keep it simple like this. This is a reference
input=raw_input() #took input as string
inputlist=input.split() #split the string to list
lsintegers = map(int, list(set(inputlist))) #remove duplicates converted each element to integer
lsintegers.sort() #sorted
print(lsintegers)`
Example: unique_dig(123456) All unique
6
I'm trying to write code to have a function return how many unique numbers there are in a positive integer.
count = 0
for i in unique_digits:
if count.has_key(i):
count[i] += 1
else:
count[i] = count + 1
Convert the integer to a string, convert that string to a set of characters, then get the size of the set.
>>> N = 12334456
>>> len(set(str(N)))
6
I am indebted to Stefan Pochmann for teaching me something. (See the comments.)
Here is a solution in pseudocode. You should be able to convert this into Python without too much trouble. Depending on the limitations (I assume this is homework of some kind), you may need to nest a second loop to check each char against the arrayOfUniqueCharacters.
someInputString = "abracadabra"
emptyArrayOfUniqueCharacters = []
FOR char IN someInputString
IF char NOT IN arrayOfUniqueChars
APPEND char TO arrayOfUniqueChars
RETURN length OF arrayOfUniqueChars
So I was messing around in python, and developed a problem.
I start out with a string like the following:
a = "1523467aa252aaa98a892a8198aa818a18238aa82938a"
For every number, you have to add it to a sum variable.Also, with every encounter of a letter, the index iterator must move back 2. My program keeps crashing at isinstance(). This is the code I have so far:
def sum():
a = '93752aaa746a27a1754aa90a93aaaaa238a44a75aa08750912738a8461a8759383aa328a4a4935903a6a55503605350'
z = 0
for i in a:
if isinstance(a[i], int):
z = z + a[i]
elif isinstance(a[i], str):
a = a[:i] + a[(i+1):]
i = i - 2
continue
print z
return z
sum()
This part is not doing what you think:
for i in a:
if isinstance(a[i], int):
Since i is an iterator, there is no need to use a[i], it will confuse Python.
Also, since a is a string, no element of it will be an int, they will all be string. You want something like this:
for i in a:
if i.isdigit():
z += int(i)
EDIT: removing elements of an iterable while iterating over it is a common problem on SO, I would recommend creating a new string with only the elements you wan to keep:
z = 0
b = ''
for i in a:
if i.isdigit():
z += int(i)
b += str(i)
a = b # set a back to b so the "original string" is set to a string with all non-numeric characters removed.
You have a few problems with your code. You don't seem to understand how for... in loops work, but #Will already addressed that problem in his answer. Furthermore, you have a misunderstanding of how isinstance() works. As the numbers are characters of a string, when you iterate over that string each character will also be a (one-length) string. isinstance(a[i], int) will fail for every character regardless of whether or not it can be converted to an int. What you actually want to do is just try converting each character to an int and adding it to the total. If it works, great, and if not just catch the exception and keep on going. You don't need to worry about non-numeric characters because when each one raises a ValueError it will simply be ignored and the next character in the string will be processed.
string = '93752aaa746a27a1754aa90a93aaaaa238a44a75aa08750912738a8461a8759383aa328a4a4935903a6a55503605350'
def sum_(string):
total = 0
for c in string:
try:
total += int(c)
except ValueError:
pass
return total
sum_(string)
Furthermore, this function is equivalent to the following one-liners:
sum(int(c) for c in string if c.isdigit())
Or the functional style...
sum(map(int, filter(str.isdigit, string)))
I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, and as a result i cant tell them apart from numbers with anything else. I can't use the int() function as it would apply to all of them and make them all integers, and then i'd lose the ones that originally were.
Here is my code:
z = 300
mylist = []
while(z > 1):
z = z - 1
x = 600851475143 / z
mylist.append(x)
print(mylist)
[y for y in mylist if y #insert rule to tell if it contains .0 here]
the first bit just divides 600851475143 by every number between 300 and 1 in turn. I then need to filter this list to get only the ones that are whole numbers. I have a filter in place, but where the comment is i need a rule that will tell if the particular value in the list has .0
Any way this can be achieved?
You're performing an integer division, so your results will all be integers anyway.
Even if you'd divide by float(z) instead, you'd run the risk of getting rounding errors, so checking for .0 wouldn't be a good idea anyway.
Maybe what you want is
if 600851475143 % z == 0:
mylist.append(600851475143/z)
It's called the "modulo operator", cf. http://docs.python.org/reference/expressions.html#binary-arithmetic-operations
EDIT: Ralph is right, I didn't put the division result into the list. Now it looks ugly, due to the repetition of the division ... :) gnibbler's answer is probably preferable, or Ralph's.
You can use divmod() and only put the result of an "even divide" in to
your list:
z = 300
mylist = []
while(z > 1):
z = z - 1
x,y = divmod(600851475143, z)
if y==0:
mylist.append(x)
print(mylist)
You can use int() - just not the way you were thinking of perhaps
z = 300
mylist = []
while(z > 1):
z = z - 1
x = 600851475143 / z
mylist.append(x)
print(mylist)
[y for y in mylist if y==int(y)]
Use regular expressions to match what you need. In your case, it should be check for ".0" at the end of the string, thus re.search("\.0$", y). Please be aware that you should use re.search, because re.match checks only for match at the beginning of the string.
Edit: sorry, I was disappointed with
however python creates lists where
even whole numbers get .0
and thought that you are making it list of strings. jellybean gave you the answer.
jellybean's answer is quite good, so I'd summarise:
magic_num = 600851475143
filtered_list = [magic_num/i for i in range(300,0,-1) if magic_num%i == 0]
(the division operator should be integer //, but the code coloriser interprets it as a comment, so I've left the single slash)