-1

I am solving an average speed formula and the inputs depends on how many elements the user want to input for the distance. After inputting the distance, time will also be included. The distance should be multiply with the time sequentially. For example, I inputted 2 in elements for the distance

2 inputs (distance):

10

20

2 inputs (time):

2

3

I want it be like 10 * 2, 20 * 3. Multiply it sequentially. And the final answer would be 80 by multiplying the distance to specific time. This is the code of mine.

print("================================")
print("Average Speed Formula")
print("================================")
tryingagain = True
while tryingagain:
    print("DISTANCE")
    num_array = list()
    num = int(input("Enter how many elements of distance you want: "))
    for i in range (0,num):
        element = float(input(str(i + 1) + ". "))
        num_array.append(element)

    print ("TIME FOR DISTANCE (ENTER BASED ON DISTANCE INPUTTED (SEQUENTIALLY)")
    num_array2 = list()

    for i in range(0, num): 
        element1 = float(input(str(i + 1) + ". "))
        num_array2.append(element1)

I did not include the computation since mine is wrong. This is the code that only working

  • 1
    Instead of code that works and that you're not asking about (which is useless), better give us data code like `num_array = [10, 20]` that we can conveniently work with and your computation code attempt (so that we can tell you what's wrong with it and how to fix it). – Kelly Bundy Aug 21 '21 at 11:09
  • the inputs are based on user and not built in, that's why i provided an sample input for it – Maneki Autumn Aug 21 '21 at 11:33
  • 1
    Yeah and that is really inconvenient here. In your actual program, obviously don't hardcode the inputs, but here for the question, to ask about your problem, it's really inconvenient having to type in your data every time we want to test a potential solution (or hardcode the data ourselves). – Kelly Bundy Aug 21 '21 at 11:35

3 Answers3

2

First of all you are using wrong formula to convert average speed, the correct one is total distance/total time.

print("================================")
print("Average Speed Formula")
print("================================")
tryingagain = True
while tryingagain:
    print("DISTANCE")
    num_array = list()
    num = int(input("Enter how many elements of distance you want: "))
    for i in range (0,num):
        element = float(input(str(i + 1) + ". "))
        num_array.append(element)

    print ("TIME FOR DISTANCE (ENTER BASED ON DISTANCE INPUTTED (SEQUENTIALLY)")
    num_array2 = list()

    for i in range(0, num): 
        element1 = float(input(str(i + 1) + ". "))
        num_array2.append(element1)

    constituents = zip(num_array, num_array2)
    your_desired_result = list(map(lambda constituent: constituent[0]*constituent[1], constituents))
    print(your_desired_result)

what zip function does is that it concatnates eg see here

a = [3,4]
b = ['c','d']
print(zip(a,b))
# it would give this [(3,'c'), (4, 'd')]

lambda is just a one line function

An example of map and lambda:

a = [0,1,2,3]
print(list(map(lambda a_elem: a_elem+1, a)))
# it would give this output [1,2,3,4]

SOME BAD PRACTICES THAT YOU ARE FOLLOWING:

  1. You are calling a list an array might want to look at this Python List vs. Array - when to use?

  2. While using the range() function in for-loop you don't need to specify the 0 as first argument you only define the first argument if it is not zero eg for i in range(num) would also work

  3. As Kelly said in his answer you should use reasonable variable names not like num_array you could have named it distance_list

Ibrahim
  • 798
  • 6
  • 26
  • Tried this code but it does not show the output. And yes, I just did not include the actual computation for the average speed formula because I only want to know the algorithm of multiplying the 2 arrays sequentially. 1st distance x 1st time, 2nd distance x 2nd time. That's just I want it to work – Maneki Autumn Aug 21 '21 at 11:40
  • You recognize that the formula is wrong, provide the correct formula, and then compute neither of them... – Kelly Bundy Aug 21 '21 at 11:40
  • It's funny that you talk about "bad practices" and then use `list(map(lambda ...` :-D – Kelly Bundy Aug 21 '21 at 11:43
  • @KellyBundy I did that because I though the OP might just want to learn **multiplying 2 lists sequentially** – Ibrahim Aug 21 '21 at 11:43
  • @ManekiAutumn I edited the answer and added a print statement to print the output you can check if it outputs, the correct output – Ibrahim Aug 21 '21 at 11:45
  • @KellyBundy `list(map(lambda` is not a bad practise if it is then list the reason why it is and last time I check we were on stackoverflow not `english.stackexchange` – Ibrahim Aug 21 '21 at 11:58
  • It is bad practice. List comprehension is better. Even more so than generator expressions are better than `map(lambda` as shown in the second part of [this answer](https://stackoverflow.com/a/30413651/12671057). For pretty much the same reasons. – Kelly Bundy Aug 21 '21 at 12:02
  • @ManekiAutumn generally you don't say thank you as in the guidelines of comments in stackexchange websites you click the checkmark if it solves your problem and its best out here – Ibrahim Aug 21 '21 at 12:21
2

I know the question has no numpy tag, but for the reference, if your "lists" getting bigger and bigger, you could vectorize these computations.

import numpy as np


def avg_speed(distances, times):
    distances = np.array(distances)
    times = np.array(times)
    assert np.shape(distances) == np.shape(times)
    return np.sum(distances) / np.sum(times)


def your_formula(distances, times):
    distances = np.array(distances)
    times = np.array(times)
    assert np.shape(distances) == np.shape(times)
    return np.sum(distances * times)

I assumed your data will be one-dimensional. And the asserts are there because as I understood, you wanted to design your code in such a way, that only "lists of the same shape" should be operated on.

You should be able to use these formulae, to compute your results.

skyzip
  • 237
  • 2
  • 11
1

First of all, better use more meaningful variable names than num_array and num_array2. For example distances and times.

And then one way to multiply and add is this:

result = sum(distance * time
             for distance, time in zip(distances, times))

Another way:

from operator import mul

result = sum(map(mul, distances, times))
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65