So I was able to run part of a program doing below (using tuples)
def reverse_string():
string_in = str(input("Enter a string:"))
length = -int(len(string_in))
y = 0
print("The reverse of your string is:")
while y != length:
print(string_in[y-1], end="")
y = y - 1
reverse_string()
The output is:
Enter a string:I Love Python
The reverse of your string is:
nohtyP evoL I
I am still thinking how for the program to reverse the position of the words instead of per letter.
The desired output will be "Phython Love I"
Is there anyway that I will input a string and then convert it to a tuple similar below:
So If I enter I love Phyton, a certain code will do as variable = ("I" ,"Love", "Python") and put additional codes from there...
Newbie Programmer,
Mac
Related
I need to figure out how to read in this data of the filename 'berlin52.tsp'
This is the format I'm using
NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0
And this is my current code
# Open input file
infile = open('berlin52.tsp', 'r')
# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()
# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
x,y = infile.readline().strip().split()[1:]
nodelist.append([int(x), int(y)])
# Close input file
infile.close()
The code should read in the file, output out a list of tours with the values "1, 2, 3..." and more while the x and y values are stored to be calculated for distances. It can collect the headers, at least. The problem arises when creating a list of nodes.
This is the error I get though
ValueError: invalid literal for int() with base 10: '565.0'
What am I doing wrong here?
This is a file in TSPLIB format. To load it in python, take a look at the python package tsplib95, available through PyPi or on Github
Documentation is available on https://tsplib95.readthedocs.io/
You can convert the TSPLIB file to a networkx graph and retrieve the necessary information from there.
You are feeding the string "565.0" into nodelist.append([int(x), int(y)]).
It is telling you it doesn't like that because that string is not an integer. The .0 at the end makes it a float.
So if you change that to nodelist.append([float(x), float(y)]), as just one possible solution, then you'll see that your problem goes away.
Alternatively, you can try removing or separating the '.0' from your string input.
There are two problem with the code above.I have run the code and found the following problem in lines below:
Dimension = infile.readline().strip().split()[1]
This line should be like this
`Dimension = infile.readline().strip().split()[2]`
instead of 1 it will be 2 because for 1 Dimension = : and for 2 Dimension = 52.
Both are of string type.
Second problem is with line
N = int(intDimension)
It will be
N = int(Dimension)
And lastly in line
for i in range(0, int(intDimension)):
Just simply use
for i in range(0, N):
Now everything will be alright I think.
nodelist.append([int(x), int(y)])
int(x)
function int() cant convert x(string(565.0)) to int because of "."
add
x=x[:len(x)-2]
y=y[:len(y)-2]
to remove ".0"
Here i get the input from the user.
This is my code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
print("\nThe numbers in ascending order are:%d" %(num_array.sort())
And when i want to print the numbers ,it is showing me an error.
I want output to look like this
Enter the number:
5
4
3
2
1
The numbers in ascending order are 1 2 3 4 5
Here is your code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
#print(sorted(num_array))
arr = sorted(num_array)
output = ""
for x in arr:
output = output + str(x) + " "
print(output)
this may be what you want (replaced % print statement with .format() syntax).
num_array.sort() will sort your array but will return None (and that is what your print statement will try to print). sorted on the other hand returns a list.
num_array = []
x = int(raw_input('Enter length of the array: '))
for i in range(int(x)):
n = raw_input("number '{}': ".format(i))
num_array.append(int(n))
print("\nThe numbers in ascending order are: {}".format(sorted(num_array)))
if you do not want the output to look like a python list you could to this:
sorted_str = ' '.join(str(n) for n in sorted(num_array))
print("\nThe numbers in ascending order are: {}".format(sorted_str))
I used the split() function to convert string to a list time = time.split() and this is how my output looks like :
[u'1472120400.107']
[u'1472120399.999']
[u'1472120399.334']
[u'1472120397.633']
[u'1472120397.261']
[u'1472120394.328']
[u'1472120393.762']
[u'1472120393.737']
Then I tried accessing the contents of the list using print time[1] which gives the index out of range error (cause only a single value is stored in one list). I checked questions posted by other people and used print len(time). This is the output for that:
1
[u'1472120400.107']
1
[u'1472120399.999']
1
[u'1472120399.334']
1
[u'1472120397.633']
1
[u'1472120397.261']
1
[u'1472120394.328']
1
[u'1472120393.762']
1
[u'1472120393.737']
I do this entire thing inside a for loop because I get logs dynamically and have to extract out just the time.
This is part of my code:
line_collect = lines.collect() #spark function
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
time = time.split()
#print time[1] #index out of range error which is why I wrote another for below
for k in time :
time1 = time[k]#trying to put those individual list values into one variable but get type error
print len(time1)
I get the following error :
time1 = time[k]
TypeError: list indices must be integers, not unicode
Can someone tell me how to read each of those single list values into just one list so I can access each of them using a single index[value]. I'm new to python.
My required output:
time =['1472120400.107','1472120399.999','1472120399.334','1472120397.633','1472120397.261','1472120394.328','1472120393.762','1472120393.737']
so that i can use time[1] to give 1472120399.999 as result.
Update: I misunderstood what you wanted. You have the correct output already and it's a string. The reason you have a u before the string is because it's a unicode string that has 16 bits. u is a python flag to distinguish it from a normal string. Printing it to the screen will give you the correct string. Use it normally as you would any other string.
time = [u'1472120400.107'] # One element just to show
for k in time:
print(k)
Looping over a list using a for loop will give you one value at a time, not the index itself. Consider using enumerate:
for k, value in enumerate(time):
time1 = value # Or time1 = time[k]
print(time1)
Or just getting the value itself:
for k in time:
time1 = k
print(time1)
--
Also, Python is zero based language, so to get the first element out of a list you probably want to use time[0].
Thanks for your help. I finally got the code right:
newlst = []
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
newlst.append(float(time))
print newlst
This will put the whole list values into one list.
Output:
[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]
user = int(raw_input("Type 5 numbers"))
even = []
def purify(odd):
for n in odd:
even.append(n)
if n % 2 > 0:
print n
print purify(user)
Hello I am a beginner and I would like to understand what is wrong with this code.
The User chose 5 numers and I want to print the even numbers only.
Thanks for helping
There are a few problems:
You can't apply int to an overall string, just to one integer at a time.
So if your numbers are space-separated, then you should split them into a list of strings. You can either convert them immediately after input, or wait and do it within your purify function.
Also, your purify function appends every value to the list even without testing it first.
Also, your test is backwards -- you are printing only odd numbers, not even.
Finally, you should return the value of even if you want to print it outside the function, instead of printing them as you loop.
I think this edited version should work.
user_raw = raw_input("Type some space-separated numbers")
user = user_raw.split() # defaults to white space
def purify(odd):
even = []
for n in odd:
if int(n) % 2 == 0:
even.append(n)
return even
print purify(user)
raw_input returns a string and this cannot be converted to type int.
You can use this:
user = raw_input("Input 5 numbers separated by commas: ").split(",")
user = [int(i) for i in user]
def purify(x):
new_lst = []
for i in x:
if i % 2 == 0:
new_lst.append(i)
return new_lst
for search even
filter would be the simplest way to "filter" even numbers:
output = filter(lambda x:~x&1, input)
def purify(list_number):
s=[]
for number in list_number:
if number%2==0:
s+=[number]
return s
I am trying to create a code that takes the user input, compares it to a list of tuples (shares.py) and then prints the values in a the list. for example if user input was aia, this code would return:
Please list portfolio: aia
Code Name Price
AIA Auckair 1.50
this works fine for one input, but what I want to do is make it work for multiple inputs.
For example if user input was aia, air, amp - this input would return:
Please list portfolio: aia, air, amp
Code Name Price
AIA Auckair 1.50
AIR AirNZ 5.60
AMP Amp 3.22
This is what I have so far. Any help would be appreciated!
import shares
a=input("Please input")
s1 = a.replace(' ' , "")
print ('Please list portfolio: ' + a)
print (" ")
n=["Code", "Name", "Price"]
print ('{0: <6}'.format(n[0]) + '{0:<20}'.format(n[1]) + '{0:>8}'.format(n[2]))
z = shares.EXCHANGE_DATA[0:][0]
b=s1.upper()
c=b.split()
f=shares.EXCHANGE_DATA
def find(f, a):
return [s for s in f if a.upper() in s]
x= (find(f, str(a)))
print ('{0: <6}'.format(x[0][0]) + '{0:<20}'.format(x[0][1]) + ("{0:>8.2f}".format(x[0][2])))
shares.py contains this
EXCHANGE_DATA = [('AIA', 'Auckair', 1.5),
('AIR', 'Airnz', 5.60),
('AMP', 'Amp',3.22),
('ANZ', 'Anzbankgrp', 26.25),
('ARG', 'Argosy', 12.22),
('CEN', 'Contact', 11.22)]
I am assuming a to contain values in the following format 'aia air amp'
raw = a # just in case you want the original string at a later point
toDisplay = []
a = a.split() # a now looks like ['aia','air','amp']
for i in a:
temp = find(f, i)
if(temp):
toDisplay.append(temp)
for i in toDisplay:
print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2])))
Essentially what I'm trying to do is
Split the input into a list
Do exactly what you were doing for a single input for each item in that list
Hope this helps!