Skip to content

Instantly share code, notes, and snippets.

@guestPK1986
Created August 23, 2020 01:25
Show Gist options
  • Save guestPK1986/7a77f464de3cbe931122a7d6468a4d84 to your computer and use it in GitHub Desktop.
Save guestPK1986/7a77f464de3cbe931122a7d6468a4d84 to your computer and use it in GitHub Desktop.
python functions
#Write a function named total that takes a list of integers as input,
#and returns the total value of all those integers added together.
def total(lst):
accum=0
for x in lst:
accum=accum+x
return accum
lst=[1,2,3,4]
total(lst)
#Write a function called count that takes a list of numbers as input and returns a count of the number of elements in the list.
def count(x):
y = len(x)
return y
x = [1,2,3,4,5,6]
#Write two functions, one called addit and one called mult.
#addit takes one number as an input and adds 5. mult takes one number as an input,
#and multiplies that input by whatever is returned by addit, and then returns the result.
def addit(x):
y = x+5
return y
def mult(z):
q = z * addit(z)
return q
count(x)
#Write a function, accum, that takes a list of integers as input and returns the sum of those integers.
def accum(lst):
y = 0
for x in lst:
y = y + x
return y
#Write a function, length, that takes in a list as the input.
#If the length of the list is greater than or equal to 5, return “Longer than 5”.
#If the length is less than 5, return “Less than 5”.
def length(lst):
if len(lst) >=5:
return "Longer than 5"
else:
return "Less than 5"
#You will need to write two functions for this problem.
#The first function, divide that takes in any number and returns that same number divided by 2.
#The second function called sum should take any number, divide it by 2, and add 6. It should return this new number.
#You should call the divide function within the sum function
def divide(x):
return x/2
def sum(y):
return divide(y) +6
y = 5
x = 1
print(sum(y))
#Write a function that will return the number of digits in an integer.
def numDigits(n):
str_n = str(n)
return len(str_n)
print(numDigits(555))
print(numDigits(22))
#Write a function that reverses its string argument.
def reverse(mystr):
reversed = ''
for char in mystr:
reversed = char + reversed
print(reversed)
return reversed
#OR
def reverse(p_phrase):
stringlength = len(p_phrase)
r_phrase = p_phrase[stringlength::-1]
return r_phrase
#Write a function that mirrors its string argument,
#generating a string containing the original string and the string backwards.
def mirror(p_phrase):
stringlength = len(p_phrase)
r_phrase = p_phrase[stringlength::-1]
return p_phrase+r_phrase
#OR
def reverse(mystr):
reversed = ''
for char in mystr:
reversed = char + reversed
return reversed
def mirror(mystr):
return mystr + reverse(mystr)
#Write a function that removes all occurrences of a given letter from a string.
def remove_letter(theLetter, theString):
if theLetter in theString:
return theString.replace(theLetter,"")
else:
return theString
#Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Implement a Python function that works like the following:
#count
#in
#reverse
#index
#insert
def count(obj, lst):
count = 0
for e in lst:
if e == obj:
count = count + 1
return count
def is_in(obj, lst):
for e in lst:
if e == obj:
return True
return False
def reverse(lst):
reversed = []
for i in range(len(lst)-1, -1, -1):
reversed.append(lst[i])
return reversed
def index(obj, lst):
for i in range(len(lst)):
if lst[i] == obj:
return i
return -1
def insert(obj, index, lst):
newlst = []
for i in range(len(lst)):
if i == index:
newlst.append(obj)
newlst.append(lst[i])
return newlst
lst = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
print(count(1, lst))
print(is_in(4, lst))
print(reverse(lst))
print(index(2, lst))
print(insert('cat', 4, lst))
#Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value.
#(Note: there is a builtin function named max but pretend you cannot use it.)
import random
def max(lst):
max = 0
for e in lst:
if e > max:
max = e
return max
lst = []
for i in range(100):
lst.append(random.randint(0, 1000))
print(max(lst))
#Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs.
def sum_of_squares(xs):
y = 0
for z in xs:
y = y + square(z)
return y
def square(x):
return x*x
lst = [1,2,3,4]
print(sum_of_squares(lst))
#Write a function to count how many odd numbers are in a list.
import random
def countOdd(lst):
odd = 0
for x in lst:
if x%2 !=0:
odd = odd + 1
return odd
new = [] # random list to test the function
for i in range(100):
new.append(random.randint(0,1000))
print(countOdd(new))
#Sum up all the even numbers in a list.
def sumEven(lst):
sum = 0
for x in lst:
if x % 2 == 0:
sum = sum +x
return sum
#Sum up all the negative numbers in a list.
def sumNegatives(lst):
sum = 0
for x in lst:
if x<0:
sum = sum +x
return sum
#Write a function findHypot. The function will be given the length of two sides of a right-angled triangle and
#it should return the length of the hypotenuse.
#c2=a2+b2
import math
def findHypot(a,b):
c = math.sqrt(a**2 + b**2)
return c
#Write a function called is_even(n) that takes an integer as an argument and
#returns True if the argument is an even number and False if it is odd.
def is_even(n):
if n % 2 == 0:
return True
else:
return False
#Write a function is_rightangled which, given the length of three sides of a triangle,
#will determine whether the triangle is right-angled.
#Assume that the third argument to the function is always the longest side.
import math
def is_rightangled(a, b, c):
x = math.sqrt((a*a+b*b))
if c == x:
return True
elif abs(c - x) < 0.0001:
return True
return False
print(is_rightangled(30,40,50))
#It will return True if the triangle is right-angled, or False otherwise.
@hadrocodium
Copy link

"""
Write a Python function that will
    take a the list of 100 random integers between 0 and 1000 and
    return the maximum value.
    (Note: there is a builtin function named max but pretend you cannot use
    it.)
"""


import random as r
lst = []

for i in range(100):
    num = r.randint(1, 1000)
    lst.append(num)

def largest(lst):
    """Returns the maximum value from the list."""
    # your code here
    best_value = None
    for current_value in lst:
        if best_value is None or best_value < current_value:
            best_value = current_value
    return best_value

print(largest(lst))

@hadrocodium
Copy link

hadrocodium commented Apr 16, 2022

#Write a function that will return the number of digits in an integer.

# Method I
def numDigits(n):
    # your code here
    count_digits = 0
    while True:
        # The line below is the shorthand for n = n // 10
        n //= 10
        count_digits += 1
        if n == 0:
            return count_digits

# Method II
# In order to get rid of if statement, we can use the fact that while statement is actually a condition. So, we can combine if and while statement into one.

def numDigits(n):
    
    count_digits = 0
    while n != 0:
        # The line below is the shorthand for n = n // 10
        n //= 10
        count_digits += 1
    return count_digits

# Method III
def numDigits(n):
    #convert the number into a string
    digits=str(n) 
    num_digits=0
    for digit in digits:
        num_digits+=1
    return num_digits

@hadrocodium
Copy link

"""
Write a function that reverses its string argument.
"""
# Method I
def reverse(astring):
    # your code here
    return astring[::-1]

# Method II
def reverse(astring):
    reversed_string = ''
    for current_char in astring:
        reversed_string = current_char + reversed_string
    return reversed_string
    
# Method III
def reverse(astring):
    return ''.join(reversed(astring))

@hadrocodium
Copy link

"""
Write a function that mirrors its string argument, generating a string containing the original string and the string backwards.
"""

# method I
def mirror(mystr):

    new_str = ''
    for current_char in mystr:
        new_str = current_char + new_str
    return mystr + new_str

# method II
def mirror(mystr):

    return mystr + mystr[::-1]

@hadrocodium
Copy link

"""
Write a function that removes all occurrences of a given letter from a string.
"""


# Method I
def remove_letter(theLetter, theString):
    # Converting a given string to list of characters.
    lst_theString = list(theString)
    
    for current_letter in lst_theString:
        if current_letter == theLetter:
            # List method remove removes the first matching element passed as an argument from the list.
            lst_theString.remove(current_letter)
    # Converting the list into a string
    return ''.join(lst_theString)

    
#  Method II - using a string method replace
def remove_letter(theLetter, theString):
    
    return theString.replace(theLetter, '')

@hadrocodium
Copy link

hadrocodium commented Apr 17, 2022

"""
Although Python provides us with many list methods, it is good practice and
very instructive to think about how they are implemented. Implement a Python
function that works like the following:

    a. count

    b. in

    c. reverse

    d. index

    e. insert
"""


def count(obj, lst):
    count = 0
    for e in lst:
        if e == obj:
            count = count + 1
    return count


def is_in(part, whole):
    for elem in whole:
        if elem == part:
            return True
    return False


def reverse(lst):
    new_lst = []
    for current_elem in lst[::-1]:
        new_lst.append(current_elem)
    return new_lst

# Another way to define reverse function.

def reverse(lst):
    return lst[::-1]
    


def index(elem, lst):
    count_iteration = -1
    for current_elem in lst:
        count_iteration += 1
        if current_elem == elem:
            return count_iteration
    return -1

# Another way to defined index function.

def index(elem, lst):
    for idx, current_elem in enumerate(lst):
        if current_elem == elem:
            return idx
    else:
        return f"ValueError: '{elem}' is not in list"


def insert(elem_to_be_inserted, idx, lst):
    new_lst = []
    count_iteration = -1
    for current_elem in lst:
        count_iteration += 1
        if count_iteration == idx:
            new_lst.append(elem_to_be_inserted)
        else:
            new_lst.append(current_elem)
    return new_lst

# Another way to define insert function.

def insert(elem, idx_postion, lst):
    for idx, current_elem in enumerate(lst):
        if idx == idx_postion:
            lst[idx:idx] = [elem]
            return lst

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment