0% found this document useful (0 votes)
15 views3 pages

InClassCoding 03112023

Uploaded by

Prajwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

InClassCoding 03112023

Uploaded by

Prajwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

mylist = [11, 22, 33, 44, 55]

list(map(lambda x: x * x, mylist))

[121, 484, 1089, 1936, 3025]

WAP to find the sum of all the multiples of 3 or 5 below 1000.


def mySum(n):
s = 0
for i in n:
if i % 3 == 0 or i % 5 == 0:
s += i
return s

mySum(range(1000))

233168

sum(range(3, 1000, 3)) + sum(range(5, 1000, 5)) - sum(range(15, 1000,


15))

233168

sum(set(range(3, 1000, 3)) | set(range(5, 1000, 5)))

233168
def myFunc1(n):
return n % 3 == 0 or n % 5 == 0

sum(filter(myFunc1, range(1000)))

233168

sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))

233168

sum([x for x in range(1000) if myFunc1(x)])

233168

What is the smallest positive number that is divisible by all of the


numbers from 1 to 20?
import math

myLCM = lambda x, y: math.lcm(x, y)

myLCM(10, 12)

60

def lcmOfMany(n):
if len(n) == 1:
return n[0]
if len(n) == 2:
return myLCM(n[0], n[1])
number = myLCM(n[0], n[1])
return lcmOfMany([number] + n[2:])

lcmOfMany(list(range(1, 21)))

232792560

import functools

functools.reduce(myLCM, list(range(1, 21)))

232792560

Find the sum of all the primes below two million.


def primeOrNot(x: int) -> bool:
if x < 2:
return False
if x in [2, 3]:
return True
if x % 2 == 0:
return False
factor = 3
while factor * factor <= x:
if x % factor == 0:
return False
factor += 2
return True

primeOrNot(31)

True

sum(filter(primeOrNot, list(range(1, 2000000))))

142913828922

sum([x for x in list(range(1, 2000000)) if primeOrNot(x)])

142913828922

2 + sum(filter(primeOrNot, list(range(3, 2000000, 2))))

142913828922

By considering the terms in the Fibonacci sequence whose


values do not exceed four
million, find the sum of the even-valued terms
def fib(n):
fiblist = []
x, y = 0, 1
while x < n:
fiblist.append(x)
x, y = y, x+y
return fiblist

fib(10)

[0, 1, 1, 2, 3, 5, 8]

isEven = lambda x: x % 2 == 0

sum([x for x in fib(4000000) if isEven(x)])

4613732

You might also like