I was trying to define a simple function to convert numbers expressed as string to real numbers. e.g 1234K to 1234000, 1234M to 1234000000. This can be easily done using if statement. Out of curiosity, I used dictionary instead and found out the following problem. Please see my code below.
# -*- coding: utf-8 -*-
dict_EN_num={"K":1000,'M':1000000}
def ENtoNum(value):
x=value
if type(x)==str:
for k,v in dict_EN_num.items():
if k in x:
x=int(x[:x.find(k)])*v
break
return x
y="1234K"
z="1234M"
print ENtoNum(y)
print ENtoNum(z)
The result in my iPython console was:
1234000
1234M
The conversion of variable y with "K" in it worked but the conversion of variable z with "M" failed.
Any idea why this is the case?
The problem is your break needs to be indented one more level.
Related
I'm trying to execute the following code in Spyder 3.3.1 using Python 2.7.15. I'm a beginner.
text = str(input("You are lost in forest..."))
while text == "Right":
text = str(input("You are lost in forest..."))
print "You got out of the forest!!!"
When I run the code with integer value it works. For example the following piece of code:
text = input("You are lost in forest...")
while text == 1:
text = input("You are lost in forest...")
print "You got out of the forest!!!"
How can I make the input() work with a string value? Thank you for your help.
Use raw_input() instead of input():
value = raw_input("You are lost in forest...") # String input
value = int(raw_input("You are lost in forest...")) # Integer input
...
In python 2, raw_input() takes exactly what the user typed and passes it back as a string. input() tries to understand the data entered by the user.Hence expects a syntactically correct python statement.That's why you got an error when you enter Right. So you can enter "Right" as input to fix this error.
But it is better to use raw_input() instead of input().
So I am having this weird problem when using 'æ', 'ø' and 'å' in python.
I have included: # -- coding: utf-8 --
at the top of every file, and æøå prints fine so no worries there. However if i do len('æ') i get 2. I am making a program where i loop over and analyze danish text, so this is a big problem.
Below is some examples from the python terminal to illustrate the problem:
In [1]: 'a'.islower()
Out[1]: True
In [2]: 'æ'.islower()
Out[2]: False
In [3]: len('a')
Out[3]: 1
In [4]: len('æ')
Out[4]: 2
In [5]: for c in 'æ': print c in "æøå"
True
True
In [6]: print "æøå are troublesome characters"
æøå are troublesome characters
I can get around the problem of islower() and isupper() not working for 'æ', 'ø' and 'å' by simply doing c.islower() or c in "æøå" to check if c is a lower case letter, but as shown above both parts of 'æ' will then count as a lower case and be counted double.
Is there a way that I can make those letters act like any other letter?
I run python 2.7 on windows 10 using canopy as its an easy way to get sklearn and numpy which i need.
You have stumbled across the problem that strings are bytes by default in python 2. With your header # -- coding: utf-8 -- you have only told the interpreter that your source code is utf-8 but this has no effect on the handling of strings.
The solution to your problem is to convert all your strings to unicode objects with the decode method, e.g
danish_text_raw = 'æ' # here you would load your text
print(type(danish_text_raw)) # returns string
danish_text = danish_text_raw.decode('utf-8')
print(type(danish_text)) # returns <type 'unicode'>
The issues with islower and len should be fixed then. Make sure that all the strings you use in your program are unicode and not bytes objects. Otherwise comparisons can lead to strange results. For example
danish_text_raw == danish_text # this yields false
To make sure that you use unicode strings you can for example use this function to ensure it
def to_unicode(in_string):
if isinstance(in_string,str):
out_string = in_string.decode('utf-8')
elif isinstance(in_string,unicode):
out_string = in_string
else:
raise TypeError('not stringy')
return out_string
new student here so please excuse my ignorance, I have searched a lot and not found a solution to my problem. I am needing to import a CSV file with mixed data types [ int, float, and string], determine the data type, then do maths on the ints and floats.
The problem is that csv reader converts everything to strings ( or they are already strings?). I can try and convert to float, and if it throws an error message I know it is a string, but how would I tell if it is a float, as my program needs to determine between the two?
I am only allowed to import CSV and no others. This is my second first-year python subject, and really not sure how to do this.
Edit, found one answer that seems similar to my problem, but it still returns the wrong answers, ints are usually, but not always, still returned as string type:
import csv
tests = [
# (Type, Test)
(int, int),
(float, float),
]
def getType(value):
for typ, test in tests:
try:
test(value)
return typ
except ValueError:
print 'value error'
continue
# No match
return str
file = open('adult.csv')
reader = csv.reader(file)
filename = 'output.xml'
text = open(filename, 'w')
text.write('<?xml version="1.0"?>')
text.write('<!DOCTYPE summary [')
headers = reader.next()
for i in headers:
print '<name>'
print i
print '</name>'
print '<dataType>'
for a in i[1]:
print getType[a]
#for row in fields:
# text = row[2]
# print type(text)
print '</dataType>'
#for value in i:
# print type(value)
print '<!ELEMENT summary\n\n>'
#text.write('<element>')
Ok sorry everybody, think i found some code i think will work:
determine the type of a value which is represented as string in python
SHOULD have searched harder, although still not reliably giving the correct type
BELOW is the code for the problem MAXCOUNT from codechef.com. The code on submission shows NZEC error.
The code takes first input t as no. of test cases, then for each test case takes input n a integer and the next line consists of space separated n integers Basically I need to return the maximum occuring integer and its count as output.
import numpy as np
import sys
t = int(raw_input())
for i in xrange(t):
n = raw_input()
n = int(n)
a = []
a = map(int, raw_input().split())
print a
count = np.bincount(a)
print np.argmax(count),np.max(count)
sys.exit(0)
Someone please help me out with this error.
The answer to your question is the use of the numpy module, which is not part of the standard library used on CodeChef. If you need to check numpy or another module in an online programming judge, a good way is to use a code sample that you know works and then add the import statement to the top before resubmitting.
For CodeChef in particular, try the basic test with the following code, with and without the import statement:
#Test for modules
import numpy
number_in = int(raw_input())
while number_in != 42:
print number_in
number_in = int(raw_input())
As a suggestion, the Counter() function from the collections module will work on CodeChef, you may want to try that instead of numpy. I find however that for many of the problems on that site without numpy or using PyPy it can be quite difficult to meet the timing requirements for solutions.
The first part of the code works which I believe is changing the list loading into loafing. But the second part of the code which I was given to turn the tuple, loading into loafing does not.
y=['l','o','a','d','i','n','g']
print type(y)
y[3] = 'F'
print y
x=('l','o','a','d','i','n','g')
print type(x)
x[3]='F'
print x
Tuples, like strings, are immutable sequence types--they cannot be changed once created. See the Python documentation on this topic.