-1

My teachers has set me the task:

Write a sub-routine that

reads in the cities from text file cities.txt (which just contains the names of 7 cities within),

adds them to an array,

reverses the city names without using the inbuilt .reverse option in Python. ie. "london" would become "nodnol"

I have added them to an array however have not been able to reverse each letter then append the reversed string back into the array. right now the output is just the names of the 7 cities within the array whereas I want for each character in each name to be reversed my code is:


cities = []

def read_and_reverse():
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
  print(cities)

  

  for city in cities:
    for i in range(0,len(city)):
      index = len(int(i))
      while index:
        index -= 1                       
        reversedCities.append(city[index])
      return ''.join(reversedCities)
  print(reversedCities)
      
read_and_reverse()
  • by "reverse the city names" you mean as an array or every city name in the array? – cards Mar 15 '22 at 19:25
  • every city name i.e "london" would become "nodnol" – fiennesharris Mar 15 '22 at 19:27
  • Show us the output of this code and explain how it's different from what you wanted. – John Gordon Mar 15 '22 at 19:27
  • 1
    Can't you simply do `[i[::-1] for i in f.readlines()]`? – RJ Adriaansen Mar 15 '22 at 19:29
  • Also, `index = len(int(i))` is an error. You can't call len of an integer. This code won't even run. – John Gordon Mar 15 '22 at 19:29
  • `s = "london" `print(s[::-1])` a string is iterable and you can start reading it from the end with `[::-1]`... then iterate – cards Mar 15 '22 at 19:29
  • What's your question? Please read [How to ask and answer homework questions](https://meta.stackoverflow.com/q/334822/4518341) and [ask] in general. This code raises `TypeError: object of type 'int' has no len()`, so do you know how to fix that? Or, instead of rolling your own algorithm, are you allowed to use [slicing to reverse](/a/931095/4518341)? – wjandrea Mar 15 '22 at 19:30
  • Sidenote: best practice for opening files is using `with` like `with open(filename) as f: for line in f: ...`. It's covered in the official tutorial [here](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). – wjandrea Mar 15 '22 at 19:43
  • "inbuilt .reverse option"? On strings? Your teacher must be high. – Kelly Bundy Mar 15 '22 at 20:23

4 Answers4

0
city_text = """London
Berlin
Paris
Madrid
Milan"""

def reverse_string(s):
    return s[::-1]

cities = []
reverse_cities = []

if False:
    with open("city.txt","r") as f:
        cities = f.read().splitlines()
else:
    cities = city_text.split("\n")
    
for city in cities:
    reverse_cities.append(reverse_string(city))
    
print(reverse_cities)

Output

['nodnoL', 'nilreB', 'siraP', 'dirdaM', 'naliM']
FloLie
  • 1,820
  • 1
  • 7
  • 19
  • FWIW, it's cleaner as a comprehension: `reverse_cities = [reverse_string(city) for city in cities]` – wjandrea Mar 15 '22 at 19:37
  • Beside the point, but `cities.append(f.readline())` is incorrect. You want `for line in f: cities.append(line.rstrip('\n')`, or better yet, `cities = f.read().splitlines()`. – wjandrea Mar 15 '22 at 19:41
  • 1
    @wjandrea thanks, big mistake, i fixed it. Based on the question i assumed the course is not yet at list comprehension and I feel loops should be understood before. However, you are correct it is more pythonic – FloLie Mar 15 '22 at 19:50
0

assuming you have a text file wherein each line contains a city name and you want to produce a list in the same order but with the names of the cities being reversed, I would do it as follows:

def read_and_reverse():
  cities = []
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
    reversedCities.append(i[::-1])  #This reverses the string using slicing
  print(cities)
  print(reversedCities)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
itprorh66
  • 3,110
  • 4
  • 9
  • 21
  • Using ```f = open("cities.txt", "r")``` without ```f.close()``` leaves the file open! Best practice is to open files with context such as ```with open("filename","mode") as f:``` – FloLie Mar 15 '22 at 19:56
0

Personnaly, I would do something like that:

cities = []

for city in open("cities.txt", "r").readlines():
    cities.append(city[::-1].strip("\n"))
print(cities)

so if there is

abcde1
abcde2
abcde3

in cities.txt, the output would be:

['1edcba', '2edcba', '3edcba']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Senpai
  • 11
  • 1
-1
cities = []

def read_and_reverse():
  reversedCities = []
  f = open("cities.txt", "r")
  for i in f:
    i = i.strip("\n")
    cities.append(i)
  print(cities)

  

  for city in cities:
    reversed_city = ""
    for i in range(0,len(city)):
      reversed_city += city[len(city)-i-1]
    reversedCities.append(reversed_city)
  print(reversedCities)
      
read_and_reverse()
khan
  • 158
  • 4
  • Why use this instead of the obvious solution, `reversedCities.append(city[::-1])`? – wjandrea Mar 15 '22 at 19:35
  • The OP mentions not to use the built-in reverse function. From his code, it looks like he is trying to implement it on his own. – khan Mar 15 '22 at 19:37