Loading...
More Python Posts
my_list = ["blue", "red", "green"]#1- Using sort or srted directly or with specifc keysmy_list.sort() #sorts alphabetically or in an ascending order for numeric datamy_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.# You can use reverse=True to flip the order#2- Using locale and functoolsimport localefrom functools import cmp_to_keymy_list = sorted(my_list, key=cmp_to_key(locale.strcoll))
print("test")
filename = "data.txt"with open(filename, "r") as file:file_contents = file.readlines()file_contents = [line.strip() for line in file_contents]print("File contents:")for line in file_contents:print(line)
def generate_floyds_triangle(num_rows):triangle = []number = 1for row in range(num_rows):current_row = []for _ in range(row + 1):current_row.append(number)number += 1triangle.append(current_row)return triangledef display_floyds_triangle(triangle):for row in triangle:for number in row:print(number, end=" ")print()# Prompt the user for the number of rowsnum_rows = int(input("Enter the number of rows for Floyd's Triangle: "))# Generate Floyd's Trianglefloyds_triangle = generate_floyds_triangle(num_rows)# Display Floyd's Triangledisplay_floyds_triangle(floyds_triangle)
bytes_data = b'Hello, World!'string_data = bytes_data.decode('utf-8')print("String:", string_data)
# Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.# For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.# Python program to print all primes smaller than or equal to# n using Sieve of Eratosthenesdef SieveOfEratosthenes(n):# Create a boolean array "prime[0..n]" and initialize# all entries it as true. A value in prime[i] will# finally be false if i is Not a prime, else true.prime = [True for i in range(n + 1)]p = 2while (p * p <= n):# If prime[p] is not changed, then it is a primeif (prime[p] == True):# Update all multiples of pfor i in range(p * 2, n + 1, p):prime[i] = Falsep += 1prime[0]= Falseprime[1]= False# Print all prime numbersfor p in range(n + 1):if prime[p]:print (p)# driver programif __name__=='__main__':n = 30print("Following are the prime numbers smaller")print("than or equal to ", n)print("than or equal to ", n)SieveOfEratosthenes(n)