0

I am new in Python and I would like to know how I can split by comma (,) and colon (:). I am trying to do the Gas Station question and I would like to read from text file which is built like that:

1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8

I also want to open and read from the file this data and store it in linked list.

Until now I made this :

def GasStation(strArr):
    strArr = []

    f = open('Details.txt', 'r')
    for line in f:
        strArr.append(line)

    amount, tank = int(strArr[0]),0
    stations = [amount.split(":") for i in (strArr[1:] + strArr[1:-1])]
    for curr in range(start, start+amount):
        tank = tank + int(stations[curr][0]) - int(stations[curr][1])
    if tank < 0: sys.exit()
    if tank >= 0: return start+1
    else: tank = 0
    return "not"

I also want to print the indexes which are the answer.

Please help me, I don't understand why is doesn't print me the answer.

Thanks.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
yahav10
  • 37
  • 6

2 Answers2

5

Presuming your question is how to split the given sequence by , then by :, you can use list comprehensions:

>>> numbers = '1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8'
>>> pairs = [pairs.split(':') for pairs in numbers.split(',')]
>>> print pairs
[['1', '1'],
 ['2', '2'],
 ['3', '3'],
 ['4', '4'],
 ['5', '5'],
 ['6', '6'],
 ['7', '7'],
 ['8', '8']]

In case you might want to flatten the list, you can use itertools.chain.from_iterable:

>>> import itertools
>>> print list(itertools.chain.from_iterable(pairs))
>>> ['1', '1', '2', '2', '3', '3', '4', '4', '5', '5', '6', '6', '7', '7', '8', '8']

For us being able to answer your other questions, we need to know what you meant by tank, amount and stations.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • That gives him a list of lists don't it? Shouldn't it be [1, 1, 2, 2]. Unless that's what he wants. Woah. itertools is solid #pro – FirebladeDan Aug 10 '15 at 21:28
1

Try this, I cleaned up your code and removed a bunch of errors, although I don't fully understand it. EDIT: I added 'global' that probably was the problem

# Did you import sys?
import sys
# You don't need to pass 'strArr', what, you want to initialize it? You don't need to in python.
# I renamed your functions and variables lowercase - its python style to do that
def gas_station():
    # IMPORTANT: you must first declare variables global to modify them
    global tank, stations
    f = open('Details.txt', 'r')
    # you must first read the lines
    # you don't need to loop over it and do that - readlines() returns a list, so you can assign it directly
    strarr = f.readlines()
    # Close your file! 
    # This can lead to memory leaks and make your application use more RAM (although python typically does this for you, you can't rely on that all the time.)
    f.close()
    amount, tank = int(strarr[0]), 0
    stations = [amount.split(":") for i in (strarr[1:] + strarr[1:-1])]
    # I don't understand "start". It was never initialized and I assume its just strarr[0]
    # range(start, start+1) is the same as the tuple(start, start+1), you do not need range
    for curr in (strarr[0], strarr[1]):
        tank = tank + int(stations[curr][0]) - int(stations[curr][1])
    if tank < 0:
        # Don't do that! It's ugly and against PEP 8: https://www.python.org/dev/peps/pep-0008/
        # Also don't exit - raise an exception
        raise ValueError('Tank is less than 0')
    elif tank >= 0:
        return strarr[0] + 1
    else:
        tank = 0
    # False is better and awesomer than just 'not', you can check it just like you can with 'not' and its more pythonic too.
    return False

PEP 8 is very important - it can make other developers fiddly to see non-PEP8 formatted code, its like naming variables lowercase in Java, only in python it's not tradition - its the law.

You're also changing global variables instead of running a function to return the new result and assign it to the variable.

My code:

# f = open('Details.txt', 'r')
# text = f.read()
# f.close()
text = '1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8'
# This is a list of the lines from the file seperated at the comma like this:
# ['1:1', '2:2', '3:3', '4:4', '5:5', '6:6', '7:7', '8:8']
comma_seperated = text.split(',')
# List comprehension here. This is a ninja skill you'll learn later on here:
# https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
# It's much faster and beautiful
nested_seperated = [element.split(':') for element in comma_seperated]
# This is the equivalent with a for loop:
nested_seperated = []
for element in comma_seperated:
    nested_seperated.append(element.split(':'))
print(nested_seperated)
# Output: [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8']]


# If you want to make them integers instead, replace the list comprehension with this other one:
nested_seperated = [[int(i) for i in element.split(':')] for element in comma_seperated]
# int() can turn strings into integers
# or this equivalent for loop:
nested_seperated = []
for element in comma_seperated:
    inner = []
    for i in element.split(':'):
        inner.append(int(i))
    nested_seperated.append(inner)
print(nested_seperated)
# Output: [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8]]

I assume you don't have any newlines in the input.

I don't understand why you need a linked list, since its a complex CS structure, but if you mean by a dictionary, simply do this:

dictionary_version = dict(nested_seperated)
# Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}
noɥʇʎԀʎzɐɹƆ
  • 9,967
  • 2
  • 50
  • 67
  • James Lu, thank you for the change, I took it into my mind and I will follow PEP 8 and will stick it. I would like to know if its printing the index when the algorithm find a solution ? if so in which line is it ? – yahav10 Aug 11 '15 at 10:52