Python create a street address table - python

Very new to programming, very new to Python, I take different tasks online. The goal is to accomplish a lot without relying on external libraries.
One task I couldn't do today is this one:
Given a street name and a user provided number, create a table of user_provided_number columns and output the name of the street. Then, in the same table create the same output but reverse the street address. The space between the street addresses should be replaced with a "|". If the street name is too short to complete the row, render "?" for each remaining space.
Scenario Example:
Street address: Mystreet road, user provided number: 6
Expected output:
M y s t r e
e t | r o a
d | d a o r
| t e e r t
s y M ? ? ?
So far I managed to do the following:
strAddress = input("What's your street address?")
givenNumber = input("What's your favourite number from 1 to 10?")
reverseAddress = strAddress[::-1]
splitAddress = list(strAddress)
for row in range(0,int(len(strAddress)/givenNumber)):
for element in range(0,givenNumber):
print (splitAddress[element], end=' ')
print()
Why is this "array"(?) printing the same elements on each row? Assuming that the user provided "4" as their number, from the code I wrote I expected an output like that:
M y s t
r e e t
r o a
d
however the output is:
M y s t
M y s t
M y s t

First of all you should convert your givenNumber into int() since input() always returns string. Also you could convert your whole strAddress into itself and reversed version of itself to make accessing it easier. splitAddress wont be needed here since you can access string length and elements the same way as list in this example. In your first loop you're iterating over len(strAddress)/givenNumber which isn't enough since we need to print our Address two times (with reversed version) and we need to fill extending characters with ? so we need to round it up, without using math library we could do this like I've shown. Lastly splitAddress[element] here you access element'th index of your Address which will be number 0 - 6 on every iteration so we need take into account row to print more elements.
strAddress = input("What's your street address?")
givenNumber = int(input("What's your favourite number from 1 to 10?"))
strAddress += '|' + strAddress[::-1]
strAddress = strAddress.replace(' ', '|')
lines_to_print = len(strAddress)//givenNumber + (len(strAddress)%givenNumber>0)
for row in range(lines_to_print):
for element in range(givenNumber):
if row*givenNumber + element < len(strAddress):
print(strAddress[row*givenNumber + element], end=' ')
else:
print('? ', end='')
print()
Output for Mystreet road and 6
M y s t r e
e t | r o a
d | d a o r
| t e e r t
s y M ? ? ?

Your issue is that the nested loop starts back at 0 every time and ends at the same place every time. With your current code, the first loop is just declaring how many times to do the second loop, it doesn't have any input on the second loop. To fix this you could do for element in range(givenNumber*(row-1),givenNumber*(row)).

You never progress through the street address. row takes on values 0, 1, 2; but you never use those values to move along the address string. Look at what you print:
for element in range(0,givenNumber):
print (splitAddress[element], end=' ')
This prints the same four characters, regardless of the row value. Instead, you need to truly split the address into rows and print those. Alternately, you can compute the correct indices for each row: givenNumber*row + element.

Another solution would be to just build your string (replace characters, reverse it, ...) and then print this string character by character for each defined row. In order to calculate the number of filling characters for the last row, you could make use of the modulo operator with negative numbers.
Say your final string (chars) is 27 characters long and the given cell number (givenNumber) is 7. This would result in -27 % 7 = 1. So in this case one filling character would need to be added. chars += charFill * numCharFill will then just add the filling character x times at the end.
With an index you can then go through your string step by step and configure the output as required.
# strAddress = input("What's your street address?")
# givenNumber = int(input("What's your favourite number from 1 to 10?"))
strAddress = "Mystreet road"
givenNumber = 6
charFill = "?" # char to fill last row
chars = strAddress.replace(" ","|") # replace spaces in strAddress
chars += "|" + chars[::-1] # add reverse chars
numCharFill = -len(chars)%givenNumber # modulo of negative number
chars += charFill * numCharFill # add fill character x times
index = 0
for char in chars:
if index > 0 and not index%givenNumber:
print()
print(chars[index], end=' ')
index = index + 1

Try:
strAddress = input("What's your street address?\n")
givenNumber = int(input("What's your favourite number from 1 to 10?\n"))
charGroupSize = len(strAddress)/givenNumber
charGroups = [strAddress[i:i+givenNumber] for i in range(0, len(strAddress), givenNumber)]
for group in charGroups:
for char in group:
print (char, end=' ')
print()
Output:
What's your street address?
Mystreet road
What's your favourite number from 1 to 10?
4
M y s t
r e e t
r o a
d

Related

is there a way to eliminate similar strings without imports?

What I've been tasked to do is to take in an input in the form "n m" where n= number of courses and m= number of students. next, i must take in m more inputs, each input being in the form "a b" where a is the number of the course that the student is taking and b is the students name. Then, I must filter out the similar names that are taking the same courses and output the names of students taking each course. For example consider this sample input:
2 4
2 David
1 john
2 davin
1 johnn
I must output:
john johnn
David
in that order as john and johnn took course 1 so they will be outputted in the first line of output (i must output n amount of lines) then David is in the next line of output as he is in course 2. Notice how davin wasn't outputted, this is because he is taking same course as David and name is too similar (similar names meaning both names are same length and only have 1 letter difference so davis and Davit are too similar but davis and daviss aren't)
x = input()
n, m = x.split(' ')
n = int(n)
m = int(m)
data = {}
dict()
for a in range(m):
line = input()
course, name = line.split(' ')
if course not in data:
data[course] = [] # list()
if name not in data[course]:
data[course].append(name)
for key, value in data.items():
print( " ".join(value) )
This is what I've come up with for now, the only issue is, if "
2 davin
1 john
are the inputs, then the outs puts are
davin
john
but i need it to be
john
davin
along with that, I need to find a way to eliminate similar names and only allow the first of the two similar names to be outputted.
Any help would be appreciated thanks.
To get the output in the correct order, loop from 1 to n instead of looping over the elements of the dictionary.
for i in range(1, n+1):
print(" ".join(data.get(str(i), [])))
To handle similar names, write a function that tells if two names are similar:
def similar(name1, name2):
if len(name1) != len(name2):
return false
diffcount = sum(c1 != c2 for c1, c2 in zip(name1, name2))
return diffcount <= 1
Then use it when testing whether the name is already in the course student list:
if not any(similar(name, s) for s in data[course]):
data[course].append(name)

Is there a way to separate elements of a list by order when theyre in a string format?

x=input()
x=list(x)
amtcrs=''.join(x[0:x.index(' ')])
amtst=''.join(x[x.index(' ')+1:])
a=0
b=''
while a<int(amtst):
crsname=input()
crsname=list(crsname)
crs=''.join(crsname[0:crsname.index(' ')])
st=''.join(crsname[crsname.index(' ')+1:])
st=st.lower()
a=a+1
b=b+crs+st+' '
b=b.strip()
z=b.split(' ')
z.sort()
for l in range(0,int(amtcrs)):
print(z)
This is what I've come up with for now. It's incomplete but I'm getting there.
Basically what I've been tasked to do is to first take an input "n m" such that n is the amount of courses that will be taught, and m is the amount of students that will be applying to the courses.
Then I have to take in m lines of input so that each line is a number followed by a name, the number being which course the student wants to take (number will be 1<= x >=n) and the name of student.
for example:
if the input is 2 4, there will be 4 more inputs, lets say they are (1 david, 2 john, 2 Kevin, 1 jennifer)
What I must output is, in this case, 2 lines of the names of people enrolling in each course, with the people enrolling in course 1 being the first line of output and so on.
so the output here should be:
david jennifer
john Kevin
The tricky part is that if a person's name is similar to another person's name (i.e same length and at most 1 character different, mike and tike are similar, Mike and mime are similar (M and m count as the same char)) and they're applying to the same course, then whoever's name was inputted first would be registered for the course while the other one isn't.
For example: input is 3 4, then the next 4 inputs are ( 1 david, 1 davin, 2 john, 2 lola)
then the output should be:
david
john lola
also notice how the third line is empty because there is a third course but no one is signing up for it.
You overcomplicated it - and all code seems useless.
You should get text from input() and directly use .split(' ') (without using list())
And later you could put data in dictionary to create ie.{'1': ['david', 'jennifer'], '2': ['john', 'Kevin']} and next you should use for-loop to get lists with names and display them in line using " ".join(list).
Something like this (but not tested)
# --- get numbers ---
x = input()
n, m = x.split(' ')
#n = int(n)
m = int(m)
# --- get courses and names ---
data = {} # dict()
for _ in range(m)
line = input()
course, name = line.split(' ')
if course not in data:
data[course] = [] # list()
if name not in data[course]:
data[course].append(name)
#print(data)
# --- display results ---
#for key, value in data.items():
# print( " ".join(value) )
for key in sorted(data.keys()):
value = data[key]
print( " ".join(value) )
print("Enter course number,max student number ") # 3 4
course_student = str(input())
total_number_of_courses=course_student.split()[0]
max_student = course_student.split()[1]
hash_list= {str(course_id):[] for course_id in range( 1,int(total_number_of_courses))}
print("Enter course_id and name")
stu_course_ids=str(input()) #1 John, 2 Doe, 2 Johny
for stu_course_id in stu_course_ids.split(","):
course_stu = stu_course_id.split(" ")
course_stu = [ item for item in course_stu if item]
if hash_list[course_stu[0]]:
hash_list[course_stu[0]].append(course_stu[1])
else:
hash_list[course_stu[0]] = [course_stu[1]]
for key, value in hash_list.items():
print( f"course_id: {key} students: {' '.join(value)}")
my result:
course_id: 1 students: John
course_id: 2 students: Doe Johny

Python program to print the odd and even indices of an string not taking the first test case

Question
Given a string S of length N, that is indexed from 0 to N-1, print it's even indexed and odd indexed characters as 2 space separated strings on a single line. Assume input starts at index position 0(which is considered even)
Input
The first line contains an integer, T (the number of test cases). Each line i of the T subsequent lines contain a String, S.
Output
For each string S, print it's even-indexed characters, followed by space, followed by odd-indexed characters.
Sample Input
2
Hacker
Rank
Sample Output
Hce akr
Rn ak
My code is as follows
T=int(input().strip())
for i in range(T):
Str=(input().strip())
odd=""
even=""
l=len(Str)
for j in range(l):
if(j%2==0):
even += Str[j]
else:
odd += Str[j]
print(even,"",odd)
****The output I am getting is:**
Input
2
Hacker
Rank
My Output
Rn ak
please help me what I am doing wrong?**
hope this will help you.
T = list(input().split())
for j in T:
a = ""
b = ""
for i in range(0,len(j)):
if i%2 == 0:
a = a+j[i]
else :
b = b + j[i]
print(a+" "+b)
input:
hacker rank
output :
hce akr
rn ak

How can I isolate the first character of each word in a string?

I wrote this program, but it doesn't work because, I cannot figure out what it is doing when i input two words seperated by a space
sinput = input("Enter a sentence") #Collects a string from the user
x = len(sinput) #Calculates how many characters there are in the string
for n in range(x):
n = 0 #Sets n to 0
lsinput = sinput.split(" ") #Splits sinput into seperate words
lsinput = lsinput[n] #Targets the nth word and isolates it into the variable lsinput
print(lsinput[1]) #Prints the 1st letter of lsinput
n += 1 #Adds 1 to n so the loop can move on to the next word
i recommend starting with a beginner's book on python. not sure what. but definitely do some reading.
to answer your question to help get you going though, you can just do this:
[w[0] for w in sinput.split() if w]
The problem was that you:
set n back to 0 at every loop
you looped over the wrong amount of iterations
you used 1 to retrieve the first letter rather than 0 (indexes start at 0)
Adjusting this for your code:
sinput = input("Enter a string to convert to phonetic alphabet") #Collects a string from the user
lsinput = sinput.split(" ") #Splits sinput into seperate words
x = len(lsinput) #Calculates how many characters there are in the string
n = 0 #Sets n to 0
for n in range(x):
print(lsinput[n][0]) #Prints the 1st letter of the nth word in 5lsinput
n += 1 #Adds 1 to n so the loop can move on to the next word
I also moved lsinput forward so that you don't recalculate this list with every iteration.
I am not sure i really understood the question, but if you want to get all the first letters of each word in the input this code will do it
map(lambda x: x[0], sinput.split(" "))

Python programming - beginner

so i have to create a code in which it reads every third letter and it creates a space in between each letter, my code creates the spaces but it also has a space after the last letter, this is my code:
msg = input("Message? ")
length = len(msg)
for i in range (0, length, 3):
x = msg[i]
print(x, end=" ")
My output was:
Message?
I enter:
cxohawalkldflghemwnsegfaeap
I get back
c h a l l e n g e
when the output isn't meant to have the last " " after the e.
I have read by adding print(" ".join(x)) should give me the output i need but when i put it in it just gives me a error. Please and Thank you
In Python, strings are one kind of data structures called sequences. Sequences support slicing, which is a simple and fancy way of doing things like "from nth", "to nth" and "every nth". The syntax is sequence[from_index:to_index:stride]. One does not even a for loop for doing that.ago
We can get every 3th character easily by omitting from_index and to_index, and have stride of 3:
>>> msg = input("Message? ")
cxohawalkldflghemwnsegfaeap
>>> every_3th = msg[::3]
>>> every_3th
'challenge'
Now, we just need to insert spaces after each letter. separator.join(iterable) will join elements from iterable together in order with the given separator in between. A string is an iterable, whose elements are the individiual characters.
Thus we can do:
>>> answer = ' '.join(every_3th)
>>> answer
'c h a l l e n g e'
For the final code we can omit intermediate variables and have still a quite readable two-liner:
>>> msg = input('Message? ')
>>> print(' '.join(msg[::3]))
Try
>>> print " ".join([msg[i] for i in range(0, len(msg), 3)])
'c h a l l e n g e'

Categories

Resources