Home > Net >  How can I implement a function to print out for all similar strings?
How can I implement a function to print out for all similar strings?

Time:11-06

So I wrote this code, which returns the total time parse_time and total distance parse_int, and here is my code.

def getDigits(s):
answer = []
for char in s.split(";"):
    k = ""
    for split_s in char:
        if split_s.isdigit():
            k  = split_s
    if k:
        answer.append(k)
return answer

def parse_time(s):
    l = getDigits(s)
    r = (int(l[0])//100)*60
    t = ((int(l[0])//100)*100)
    s = int(l[0])-t
    return r s
print(parse_time(s='cycling;time:1,49;distance:2'))

def parse_dist(s):
    l = getDigits(s)
    return l[1]  'km'
print(parse_dist(s='cycling;time:1,49;distance:2'))

def jogging_average(activities: list[str]):

Now I just want to know that how can I program function jogging_average(activities: list[str]) to return the parse_dist and parse_time of every single string that has jogging on it. How can I do this??

By the way, all the inputs are going to come from activities: list, which is

activities = [
"cycling;time:1,49;distance:2",
"jogging;time:40,11;distance:6",
"swimming;time:1,49;distance:1.2",
"jogging;time:36,25;distance:5.3",
"hiking;time:106,01;distance:8.29"
]

CodePudding user response:

will loop sort it for you?

for activity in activities:
    if "jogging" in activity:
       print(parse_dist(activity))
       print(parse_time(activity))

CodePudding user response:

It can be easy to work with actual data struct. See Activity

from typing import NamedTuple,List 
from statistics import mean

class Activity(NamedTuple):
  type: str
  time: int
  distance: float

def get_digits(s):
  answer = []
  for char in s.split(";"):
      k = ""
      for split_s in char:
          if split_s.isdigit():
              k  = split_s
      if k:
          answer.append(k)
  return answer

def parse_time(l):
    l = get_digits(l)
    r = (int(l[0])//100)*60
    t = ((int(l[0])//100)*100)
    s = int(l[0])-t
    return r s

def parse(test:str) -> Activity:
  fields = test.split(';')
  type = fields[0]
  time = parse_time(fields[1][fields[1].find(':') 1:])
  distance = float(fields[2][fields[2].find(':') 1:])
  return Activity(type,time,distance)


def get_avg_time(lst:List[Activity],activity_type:str) -> float:
  return mean(act.time for act in lst if act.type == activity_type)

activities = [
"cycling;time:1,49;distance:2",
"jogging;time:40,11;distance:6",
"swimming;time:1,49;distance:1.2",
"jogging;time:36,25;distance:5.3",
"hiking;time:106,01;distance:8.29"
]
activities: List[Activity] = [parse(act) for act in activities]
activity_type = 'jogging'
avg_time: float = get_avg_time(activities,activity_type)
print(f'Avg activity time of {activity_type} is {avg_time}')

output

Avg activity time of jogging is 2298
  • Related