Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying odd or even numbers in a list [closed]

Tags:

python

I want to input a 8 digit number eg.'12345678', remove and save the last digit (eg. '8') reverse the 7 remaining digits (eg. '7654321') and multiply by 2 the 1st,3rd,5th,7th (Odd) numbers.

I think I have solved the first two tasks but struggling with how to go about multiplying the odd numbers.

Code so far is:

cardnumber = input("Enter a number")
check_digit = int(cardnumber[7])
revnumber = cardnumber[-2:-9:-1]

Example:

  • A user inputs '12345678'
  • I then remove the last digit and store this as a check digit '8'
  • I am then left with '1234567'
  • I reverse this and have 7654321

I then want to multiply the odd numbers in the sequence - 1st, 3rd, 5th and 7th number:
so 7,6,5,4,3,2,1 becomes 14,6,10,4,6,2,2.

I'm very new to python so if you could explain I'd be very grateful.

like image 250
Dave Jones Avatar asked Dec 05 '25 18:12

Dave Jones


1 Answers

  1. First step - read the input:

number = input("Enter the number: ")

12345678

  1. Second step - convert input to list:

numbers = map(int, str(number))

[1, 2, 3, 4, 5, 6, 7, 8]

  1. Third step - read last digit:

last = numbers[-1]

8

  1. Fourth step - reverse the list:

rev = list(reversed(numbers[:-1]))

[7, 6, 5, 4, 3, 2, 1]

  1. Last step - generate a list with multiplied every two numbers:

multiplied = [i*2 if j % 2 == 0 else i for j, i in enumerate(rev)]

[14, 6, 10, 4, 6, 2, 2]

like image 97
Tomasz Dzieniak Avatar answered Dec 10 '25 16:12

Tomasz Dzieniak