6edited Flashcards
How do you calculate the length of a string in Python?
def string_length(s):
return len(s) @@@ Use the built-in len() function to get the length of a string.
How can you check if a number is prime in Python?
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True @@@ Use a loop to check divisibility and determine primality.
How do you find the sum of all numbers in a list?
numbers = [1, 2, 3, 4, 5]
sum_numbers = sum(numbers) @@@ Use the built-in sum() function to calculate the sum of a list.
How do you find the minimum value in a list?
def find_min(lst):
return min(lst) @@@ Use the built-in min() function to find the minimum value in a list.
How do you reverse a list in Python?
lst = [1, 2, 3, 4, 5]
reversed_lst = lst[::-1] @@@ Use slicing to reverse a list.
How do you iterate over keys and values in a dictionary?
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key, value in my_dict.items():
print(key, value) @@@ Iterate over dictionary keys and values using the items() method.
How do you concatenate two lists in Python?
def concatenate_lists(lst1, lst2):
return lst1 + lst2 @@@ Use the + operator to concatenate two lists.
How do you print the first 10 natural numbers using a loop?
for i in range(1, 11):
print(i) @@@ Use a for loop to print numbers in a range.
How do you check if a number is in a given range?
def is_in_range(num, start, end):
return start <= num <= end @@@ Use comparison operators to check if a number is within a range.
How do you find the GCD of two numbers in Python?
def gcd(a, b):
while b:
a, b = b, a % b
return a @@@ Use the Euclidean algorithm to find the greatest common divisor.
How do you calculate the area of a rectangle using a class?
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height @@@ Define a class with an __init__ method and an area method.
How do you find the largest of three numbers?
def largest_of_three(a, b, c):
return max(a, b, c) @@@ Use the built-in max() function to find the largest of three numbers.
How do you convert a list of integers into a single integer?
lst = [1, 2, 3, 4]
number = int(‘‘.join(map(str, lst))) @@@ Use join() and map() to convert a list of integers to a single integer.
How do you check if a string is a pangram?
def is_pangram(s):
alphabet = set(‘abcdefghijklmnopqrstuvwxyz’)
return alphabet <= set(s.lower()) @@@ Check if all alphabet letters are present in the string.
How do you merge two sorted lists into a single sorted list?
def merge_sorted_lists(lst1, lst2):
return sorted(lst1 + lst2) @@@ Use the sorted() function to merge and sort two lists.