blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c7deb9493f88821b87cd24c7c834a329c7d9d49c
TewariSagar/Python
/dictionaryMethods.py
775
4.59375
5
dict1 = {"vendor" : "cisco", "model" : "2004", "ports" : "4"} print dict1 #retrieve value corresponding to a key print dict1["vendor"] #add a new key value pair to the dictionary dict1["RAM"] = "128" print dict1 #if we want to change the value corresponding to a key dict1["vendor"] = "netgear" print dict1 #we can also delete the key value pair by using the del function del dict1["vendor"] print dict1 #we can use the len() to find the number of key value pairs #we can also search if a key is present in the dictionary print len(dict1) print "RAM" in dict1 #print a list of all keys in the dictionary print dict1.keys() #print a list of all values print dict1.values() #print a list of tuples each tuple containing a key value pair print dict1.items()
true
032a5771f8ef1a75be2caa7dd9abe965aac76077
TewariSagar/Python
/stringSlices.py
584
4.53125
5
#allow us to extract various parts of the string x = "sagartewari" #this command gives the substring starting at the index before column and ending at index after colein but not including it print x[1:4] #if we dont give the second paramter after colen we get the string starting at the first index and till the end of string #we include negative indexes if we are traversing from right to left #if we would like to skip every second character when we are slicing print x[::2] #this string will have of indexes 0,2,4 and so on #print the string in reverse order print x[::-1]
true
75b50e6ea24bb630cfeabba5cdfd515b2b2001ab
TewariSagar/Python
/list.py
342
4.28125
4
#lists are mutable that is it can be modified after creation list = [] print list #add elements to the list of any data type list = ["ciseco", 10, -1, "sagar"] print list print len(list) #return the first element of the list print list[0] #show that the list is immutable by changing first element list[0] = "new element" print list
true
3e20489b796dd20344c8fc94e1a8391a7d8e6cae
outrageousaman/Python_study_marerial
/class_implimentation.py
1,802
4.28125
4
class Employee(object): """ base class for all employees """ empCount = 0 def __init__(self, name, salary): """ Constructor method :param name: name of the employee :param salary: salary of the employee """ self.name = name self.salary = salary Employee.empCount += 1 def display_employee(self): """ Displays the information of Employee """ print(f'name of the employee is {self.name} and age of employee is {self.age}') def display_emplaoyee_count(self): """ Displays total number of employees :return: """ print(f'number of employees are {Employee.empCount}') if __name__ == '__main__': print(Employee.__doc__) e1 = Employee('Aman', 2000) e2 = Employee('Pankaj', 4000) print(e1.name,e1.salary) print(e2.name, e2.salary) print(Employee.empCount) Employee.empCount =100 print(e2.empCount) print(e1.empCount) # getattr, hasttr, setattr, delattr print('e1 has name : ', hasattr(e1, 'name')) print('e1 has age : ', hasattr(e1, 'age')) print('name in e1', getattr(e1, 'name')) print('deleting e1.name', delattr(e1, 'name')) e1.name = 'Kamal' print('name in e1: ', e1.name) setattr(e1, 'name', 'aman again') print('name in e1 :', getattr(e1, 'name')) # buit in class attributes # __doc__ # __name__ # __dict__ (dictionary containing class namespace) # __module__ (module name in which class is defined) # __ bases__ base classes print('############ built in attributes ###########') print(Employee.__doc__) print(Employee.__name__) print(Employee.__module__) print(Employee.__bases__) print(Employee.__dict__)
true
6d1eb399b2c60063b5afa9237e850c7f9bb117c2
KevinKronk/multiple-regression
/multiple-regression/prediction.py
1,247
4.1875
4
import numpy as np def predict_price(sq_feet, bedrooms, theta, means, stds): """ Predicts the price of a house with given square feet and bedrooms using the given theta parameters. Uses the means and standard deviations to undo feature normalization. Parameters ---------- sq_feet : int Square feet of the house. bedrooms : int Number of bedrooms in the house. theta : array_like Shape (1, n+1). The multiple regression parameters. means : array_like Shape (n+1,). DataFrame of the means for the features and prices. stds : array_like Shape (n+1,). DataFrame of the standard deviations for the features and prices. Returns ------- price : int The predicted price of the house. """ # Feature normalize sq_feet and bedrooms to calculate the new price norm_feet = (sq_feet - means['sq_feet']) / stds['sq_feet'] norm_bedrooms = (bedrooms - means['bedrooms']) / stds['bedrooms'] prediction = np.array([1, norm_feet, norm_bedrooms]) norm_price = prediction @ theta.T price = int(norm_price * stds['price'] + means['price']) return price
true
5d2da25b3571c0c124181f1466a9b05e14c58173
ebanner/project_euler
/sieve.py
2,109
4.1875
4
# say we're trying to find the largest prime factor of 121 # we're only going to find primes up to sqrt(121) import math ### Functions def prime_huh(n): # determine if a number is prime for i in range(2,int(math.sqrt(n)+1)): if (n % i == 0): return False return True def mark_off_as_composite(primes, i): # mark off all multiples of the prime number as composite for i in range(i+i, len(primes), i): primes[i] = False ### End Functions if __name__ == '__main__': SIZE = 17 SUM = 0 primes = [True]*SIZE # holds a boolean for each number indicating compositness # Assume every number is prime until you find a composite factor # primes[2] = True, primes[3] = True, primes[4] = True, etc... # [True, True, True, True, True, ..., sqrt(...)] divisor = [None]*SIZE # list of possible divisors # [1, 2, 3, 4, 5, ..., sqrt(...)] nums = [None]*SIZE # list of all numbers we are going to check # [1, 2, 3, 4, 5, ..., sqrt(...)] for i in range(SIZE): nums[i] = i divisor[i] = i # we know 0 & 1 are not primes primes[0],primes[1] = False,False # we already know 2 & 3 are composite, so include them in the count of known # primes -- start the count at 2 count = 3 # mark off every even number in the sieve as composite mark_off_as_composite(primes,2) # now let's test to see if each one is composite for i in range(4,SIZE): count += 1 if (not primes[i]): # if composite, don't check to see if it's prime, go onto the next continue if prime_huh(nums[i]): # if we find it to be a prime, cross off every multiple of it in the # sieve mark_off_as_composite(primes, i) # increment count because we found another prime #SUM += nums[i] for i in range(1,SIZE): if (primes[i]): print(nums[i]) SUM += nums[i] print("SUM = {}".format(SUM)) print("count = {}".format(count)) print("SUM = {}".format(SUM))
true
6bbea3c8a7c49f317b4cd22a524595256c47e114
sathishmanthani/python-intro
/code/Assignment_10.1.py
2,631
4.34375
4
# File name: Assignment_10.1.py # Author: Sathish Manthani # Date: 08/09/2019 # Course Name: Introduction to Programming DSC510 # Description: This program uses object-oriented programming principles to create a CashRegister class and instances it. # It also calculates the Total price of the items along with the count of items. # Usage: This program expects user to select if he/she wants to add a new item followed by the price of the item. It returns count of items and total price. # Defining class CashRegister class CashRegister: # Initializing the class with the two variables we need in methods def __init__(self): self.totalPrice = 0 self.count_of_items = 0 # Method to add item to the cart. It keeps aggregating the price and increments the count def addItem(self, price): self.totalPrice += price self.count_of_items += 1 # Instance method to return the total price of the items def getTotal(self): return round(self.totalPrice, 2) # Instance method to return the count of items def getCount(self): return self.count_of_items # Main method instanciates the class and gets user input and returns the total price and count of items. def main(): # Welcome message print("Welcome! Enjoy your shopping today!\n") # Creating instance of the class cr = CashRegister() # Below While loop gets user input continuously till the users chooses not to continue while True: # Get user input user_selection = input("\nWant to add a new item to the register (Y/N)?") # If yes then get the price of the item. Handle the exceptions related to input if user_selection.upper() == 'Y': try: item_price = float(input("Enter the price of the item: ")) except ValueError: print("Please enter a valid price") continue # After getting price, add the item to the register cr.addItem(item_price) # If the user is done adding items then print the final output and exit elif user_selection.upper() == 'N': print("------------------------------------") print("\nTotal number of items you added:", cr.getCount()) print("Total price of the items: ${}".format(cr.getTotal())) print("\nThank you for shopping with us today!\n") print("------------------------------------") break else: print("Invalid selection, Please choose Y or N.") # Call the main program if __name__ == '__main__': main()
true
ce41465791589e7e3e301b9438b1e11b859ef3c7
enochgeorge9x9/automate-the-boring-stuffs-with-python
/Part I/Exercise19 Practice Questions ch4.py
1,342
4.5
4
''' 1. [] is to create a list, its a empty list value 2. to assign 'hello' in the third variable is by spam[2] = 'hello' 3. 'd' ( (Note that '3' * 2 is the string '33' , which is passed to int() before being divided by 11 . This eventually evaluates to 3 . Expressions can be used wherever values are used.) 4. 'd' 5. 'a','b' 6. bacon.index('cat') evaluates to 1 7. bacon.append(99) looks like [3.14, 'cat', 11, 'cat', True, 99]. 8. bacon.remove('cat') looks like [3.14, 11, 'cat', True, 99]. 9. for list concantenation it is '+' and for replication its is '*'. 10. append() adds a item at the end of the list/index whereas insert() adds item to a specific index. 11. two ways to remove value from list is by : list.remove() method and del statment 12. list and strings are similar in someways like: get a specfic index, slicing, finding the length, using for loops, using in and not in operators 13. list and tuples are different because list are mutable and tuples are immutable. 14. to write a single tuple value --> m = (42,) 15. we can use the list() and tuple() functions . like tuple([8,9,0]) and list[(3,5,76)]. 16. varibles that contain list values are not stored as list rather they are stored as reference. 17. copy.copy() helps to copy the list and copy.deepcopy helps to copy the lists inside the lists also.
true
3061bc1db7c7b0cc7a6cc341e3d2174b59407880
willmead/intro_to_python
/src/Day2/rpg.py
614
4.40625
4
house1 = {'location': 'London', 'beds': 2, 'garden': False } house2 = {'location': 'Paris', 'beds': 1, 'garden': True, } house3 = {'location': 'Berlin', 'beds': 3, 'garden': True, } houses = [house1, house2, house3] for house in houses: location = house['location'] beds = house['beds'] garden = house['garden'] print(f"Location: {location}") print(f"No. Beds: {beds}") print(f"Has Garden? {garden}") price = 100_000 + beds * 50_000 print(f"Estimated Price: £{price:,}") print()
false
e79902896f950b63f89c0da64faee80fdee2d563
salmanul-fares/py-automation
/1-simple/5-dictionary.py
1,149
4.34375
4
#learn to do dictionaries #25% completion of course!! birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'} def printit(array): for element in array: print(element) while True: print('Enter a name: (0 to quit, 1 for all names, 2 for all name and dates, 3 for all dates)') name = input() if name == '0': break if name == '1': printit(birthdays.keys()) continue if name == '2': printit(birthdays.items()) continue if name=='3': printit(birthdays.values()) continue if name in birthdays: print(birthdays[name] + ' is the birthday of ' + name) else: print('I do not have bday info for ' + name) print('What is their Bday: (blank if you dont know)') bday = input() if bday != '': birthdays[name]=bday print('Database updated') ''' get and set defualt methods picnicItems.get('cup', 0) >>>prints value of cup or zero if not defined cat.setdefault('color', 'white') >>>adds a new item to cat 'color':'white' iff color is not defined '''
true
38e13c6198202e4f200b28758c5b873bebb65149
tiilde/Paradigmas_de_Programacao_em_Python
/segundosEdias.py
1,077
4.34375
4
# Desenvolva utlizando Laços de Repetição # Escreva um programa em Python que pede ao utilizador que lhe forneça # um inteiro correspondente a um número de segundos e que calcula o número de dias # correspondentes a esse número de segundos. O número de dias é fornecido como um # real. O programa termina quando o utilizador fornece um número negativo. # O seu programa deve possibilitar a seguinte interação: # Escreva um número de segundos (um número negativo para terminar) # ? 45 # O número de dias correspondente é 0.0005208333333333333 # Escreva um número de segundos (um número negativo para terminar) # ? 6654441 # O número de dias correspondente é 77.01899305555555 # Escreva um número de segundos (um número negativo para terminar) # ? -1 diaEmSegundos = 24 * 60 * 60 num_segundos = 0 while ( num_segundos >= 0 ): num_segundos = int(input("Escreva um número em segundos: ")) if (num_segundos < 0): break num_dias = num_segundos / diaEmSegundos print("O número de dias correspondente é ", num_dias) print("Fim do programa!")
false
dcc5b958d23e73ca80d11239700d43b398998780
SDSS-Computing-Studies/003-input-ethanDe
/task1.py
392
4.6875
5
#! python3 """ Ask the user for their name and their email address. You will need to use the .strip() method for this assignment. Be aware of your (2 points) Inputs: name email Sample output: Your name is Joe Lunchbox, and your email is joe@koolsandwiches.org. """ x = str(input("What is your name?")).strip() y = str(input("What is your email?")).strip() print (f"Your name is {x}, and your email is {y}")
true
cd266aed52208a52a6e9d81dfa251f2d707cbfaf
HiiipowerDanni/Python-FILES-
/Danielle_Williams Assignment 2.py
535
4.21875
4
# Author: Danielle R. Williams # Date: June 6, 2021 # Input: User enters the amount of change due to the customer # Processing: The program calculates the coins that are due by using division properties and identifying int # Output: After doing the calculations, program displays the change in the amount of each denomination of coins def main(): n=int(input("How much change is due?:")) print(n//25, "quarters") n = n%25 print(n//10, "dimes") n = n%10 print(n//5, "nickles") n = n%5 print(n//1, "pennies") main()
true
1c421fe2497082504ea88c781eb3fb787c69ca5c
jkkimGH/learning-opencv
/threshold.py
1,636
4.15625
4
# OpenCV Tutorial 13 import cv2 as cv img = cv.imread('/Users/jkkim/Documents/PycharmProjects/testingOpenCV/images/cats.jpeg') cv.imshow('Cats', img) # Thresholding: a binary realization of an image - if a pixel's intensity is less than the threshold, set it equal to # black, or 0. If greater, set it to white, or 1. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) cv.imshow('Grayscale', gray) # 1. Simple Thresholding # Returns the threshold value (150) as threshold_value & the converted image as thresh threshold_value, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY) cv.imshow('Simple Thresholding', thresh) # Inverse version threshold_value, thresh_inverse = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV) cv.imshow('Inverse Simple Thresholding', thresh_inverse) # 2. Adaptive Thresholding # Simple Thresholding has a downside where you have to define a value every time; this won't work in many cases. # Adaptive Thresholding lets the computer do the job for you by finding the optimal threshold value on its own! # Last param here -> c, used as (average of a kernal window) - c, which lets us fine tune. # max value ~kernal size # | | adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3) cv.imshow('Adaptive Thresholding', adaptive_thresh) # Inverse works too, just cv.THRESH_BINARY -> cv.THRESH_BINARY_INV # Try the Gaussian method (cv.ADAPTIVE_THRESH_GAUSSIAN_C) cv.waitKey(0)
true
5ffaef010cefd2fe93e9ba0212ac6c9d3339771c
rogerlog/python-studies
/intro/pythonStrings.py
1,083
4.1875
4
#print("Hello") #print('Hello') #Multiline Strings a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" #print(a) a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' #print(a) #Strings are Arrays a = "Hello, World!" #print(a[1]) #Looping Through a String #for x in "banana": # print(x) #String Length a = "Hello, World!" #print(len(a)) #Check String txt = "The best things in life are free!" #print("free" in txt) txt = "The best things in life are free!" #if "free" in txt: # print("Yes, 'free' is present.") #Check if NOT txt = "The best things in life are free!" #print("expensive" not in txt) txt = "The best things in life are free!" #if "expensive" not in txt: # print("Yes, 'expensive' is NOT present.") b = "Hello, World!" print(b[2:5]) a = " Hello, World! " print(a.strip()) print(len(a)) a = "Hello, World!" print(a.lower()) print(a.upper()) print(a.replace("H", "J")) b = a.split(",") print(b)
false
9a1edc2119395bba3989b6ecea709c2fea2d9114
felipemfp/py-exercicios
/exercicios-iv/questao1.py
664
4.25
4
# Crie uma classe que modele um quadrado, com um atributo lado e os # métodos: mudar valor do lado, retornar valor do lado e calcular área. class Square(object): def __init__(self, side = 1): self.__side = side @property def side(self): return self.__side @side.setter def side(self, value): self.__side = value @property def area(self): return self.side ** 2 if __name__ == "__main__": square = Square(2) print("Valor do lado =>", square.side) square.side += square.side print("Novo valor do lado =>", square.side) print("Aréa do quadrado =>", square.area) # Valor do lado => 2 # Novo valor do lado => 4 # Aréa do quadrado => 16
false
acc2d7bff8a8323b28259621532265cfaba11b70
Anastasia849/Python-practice
/practic1/task2_353.py
1,072
4.375
4
# Написать функцию commas, которая преобразует заданное число в строку с добавлением # запятых для удобства чтения. Число должно быть округлено до 3 значащих цифр, # а запятые следует добавлять с интервалом в три цифры перед десятичной точкой. # # Примеры: # commas(100.2346) ==> "100.235" # commas(-1000000.123) ==> "-1,000,000.123" import traceback def commas(number): number = round(number, 3) if number == int(number): number = int(number) return "{:,}".format(number) # Тесты try: assert commas(1) == "1" assert commas(1000) == "1,000" assert commas(100.2346) == "100.235" assert commas(1000000000.23) == "1,000,000,000.23" assert commas(-999.9999) == "-1,000" assert commas(-1234567.0001236) == "-1,234,567" except AssertionError: print("TEST ERROR") traceback.print_exc() else: print("TEST PASSED")
false
ed324de00eaaebfc9cb179b1b89bb976c48ed123
psharma228/Python3
/Python Mini Projects/nextPrime.py
971
4.21875
4
# Script to generate prime numbers # until the user chooses to stop #function to check if the number is prime def isPrime(num): if num == 2: return True if num % 2 == 0: return False for i in range(3, int(num**0.5)+1, 2): if num % i == 0: return False return True #funtion to generate prime number def genPrime(primeNum): nextPrime = primeNum + 1 while True: if not isPrime(nextPrime): nextPrime += 1 else: break return nextPrime #MAIN function starts here def main(): #starat with the first prime number primeNum = 2 while True: choice = input('Do you want to see the next prime number? (Y/N) ') if choice.lower().startswith('y'): print(primeNum) primeNum = genPrime(primeNum) else: break if __name__ == '__main__': main()
true
0e378ba3f3fe2e66187b8927a4f4993317f9fb27
Sindhujavarun/Training
/Python/marksarray.py
220
4.15625
4
# read and print 5 marks using array. marksArray = [] for counter in range(0, 5): marks = int(input("Enter the marks of 5 subjects: ")) marksArray.append(marks) print("\nMarks of 5 subjects are: ", marksArray)
true
aa94397df34ebcea9cab188385e21c36cb4450c1
sirenatroxa/python
/practice/input.py
373
4.1875
4
# Initialize a variable with a user-specified value. user =input( "I am Python. What is your name?:") # Output a string and a variable value. print( "Welcome" , user) # Initialize another variable with a user-specified value lang = input( "Favorite programming languarge? :") # Output a string and a variable value. print( lang,"Is", "Fun", sep= " * ", end= "!\n")
true
a028d39851e9924bb7a7e9a82054eb1abcb2c121
mahbubcseju/Python
/dynamic_programming/rod_cutting.py
1,710
4.125
4
from typing import List def rod_cutting(prices: List[int],length: int) -> int: """ Given a rod of length n and array of prices that indicate price at each length. Determine the maximum value obtainable by cutting up the rod and selling the pieces >>> rod_cutting([1,5,8,9],4) 10 >>> rod_cutting([1,1,1],3) 3 >>> rod_cutting([1,2,3], -1) Traceback (most recent call last): ValueError: Given integer must be greater than 1, not -1 >>> rod_cutting([1,2,3], 3.2) Traceback (most recent call last): TypeError: Must be int, not float >>> rod_cutting([], 3) Traceback (most recent call last): AssertionError: prices list is shorted than length: 3 Args: prices: list indicating price at each length, where prices[0] = 0 indicating rod of zero length has no value length: length of rod Returns: Maximum revenue attainable by cutting up the rod in any way. """ prices.insert(0, 0) if not isinstance(length, int): raise TypeError('Must be int, not {0}'.format(type(length).__name__)) if length < 0: raise ValueError('Given integer must be greater than 1, not {0}'.format(length)) assert len(prices) - 1 >= length, "prices list is shorted than length: {0}".format(length) return rod_cutting_recursive(prices, length) def rod_cutting_recursive(prices: List[int],length: int) -> int: #base case if length == 0: return 0 value = float('-inf') for firstCutLocation in range(1,length+1): value = max(value, prices[firstCutLocation]+rod_cutting_recursive(prices,length - firstCutLocation)) return value def main(): assert rod_cutting([1,5,8,9,10,17,17,20,24,30],10) == 30 # print(rod_cutting([],0)) if __name__ == '__main__': main()
true
a769798c8137622e4384da846ce14c1b832814a9
munishdeora/python_training_2019
/Day 4/bricks.py
953
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 11:29:33 2019 @author: de """ """ Code Challenge Name: Bricks Filename: bricks.py Problem Statement: We want to make a row of bricks that is target inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Make a function that prints True if it is possible to make the exact target by choosing from the given bricks or False otherwise. Take list as input from user where its 1st element represents number of small bricks, middle element represents number of big bricks and 3rd element represents the target. Input: 2, 2, 11 Output: True """ usr_ip=input("Enter the number of small bricks,big bricks and target row : ") list1=usr_ip.split(" ") small_brick = int(list1[0]) big_brick = 5*int(list1[1]) trg_inch=int(list1[2]) if (small_brick+big_brick>=trg_inch): print("True") else: print("False")
true
87ec91344422e4955f64745c7ba180b5680a9ebf
munishdeora/python_training_2019
/Day 4/pangram.py
974
4.28125
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 5 17:11:48 2019 @author: de """ """ Code Challenge Name: Pangram Filename: pangram.py Problem Statement: Write a Python function to check whether a string is PANGRAM or not Take input from User and give the output as PANGRAM or NOT PANGRAM. Hint: Pangrams are words or sentences containing every letter of the alphabet at least once. For example: "The quick brown fox jumps over the lazy dog" is a PANGRAM. Input: The five boxing wizards jumps. Output: NOT PANGRAM """ ip_str=input("Entr a string you want to check PANGRAM or not : ") ip_str2=ip_str.lower() alp=("abcdefghijklmnopqurstuvwxyz") list1=list(ip_str2) list2=list(alp) listc=[] c=0 for char in list2: if char not in list1: listc.append("NOT PANGRAM") c=0 else: listc.append("PANGRAM") c=c+1 if(c==len(listc)): print("PANGRAM") else: print("non panagram")
true
5e5a5159b4f6d9827abf9f855ac05a86a99afb5b
munishdeora/python_training_2019
/Day 4/handson1.py
1,048
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 11:02:24 2019 @author: de """ # Hands On 1 # Make a function to find whether a year is a leap year or no, return True or False def leap_year (leap_year): if (leap_year%4==0): print("True") else: print("False") usr_ip=int(input("Enter the year you want to check : ")) leap_year (usr_ip) # Hands On 2 # Make a function days_in_month to return the number of days in a specific month of a year def days_in_month (mnth_ip): if(mnth_ip=="january" or mnth_ip=="march" or mnth_ip=="may" or mnth_ip=="july" or mnth_ip=="august" or mnth_ip=="octumber" or mnth_ip=="december"): x=31 return x elif(mnth_ip=="feb"): x=28 return x elif(mnth_ip=="april" or mnth_ip=="june" or mnth_ip=="september" or mnth_ip=="november"): x=30 return x else: print("Enter valid input!!!") mnth1_ip=input("Enter the month you want to check : ") mnth_ip=mnth1_ip.lower() days_in_month (mnth_ip)
false
0c7a35c6c53754412036c2d82632aa6cbd192ced
munishdeora/python_training_2019
/Day 4/handson.py
432
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 30 15:04:13 2019 @author: de """ # Hands On 1 # Create a list of number from 1 to 20 using range function. # Using the slicing concept print all the even and odd numbers from the list #using slicing concept my_list = list () for n in range (1,2): my_list.append( n ) print("even no : " + str(my_list[1::2])) print("odd no : "+ str(my_list[::2]))
true
f47d9ffdc88ebc3f4bf49532677d0a446d3c5975
MeTwo99/Cloud9TestPrograms
/fibb.py
434
4.21875
4
#fibb returns the n'th number in the Fibonacci sequence def fibb(number): if number < 0: print("Integer must be >= 0") return seq = [0,1] while len(seq) < number+1: index = len(seq)-1 seq.append(seq[index-1] + seq[index]) number += 2 return seq[number] i = input("Enter which number in the Fibonacci sequence you would like: ") print("The number is " + str(fibb(int(i))))
true
87164df5207aee91931762d2b03bd945b0cf5a3b
AyaAymanMohamed/Image_Captioning_Engine
/word_dictionary.py
892
4.125
4
""" Generates a dictionary that takes the word and output its encoded number Generates a reversed dictionary that takes the encoded number and output the word encode all annotations and write the encoded string in a text file called "encoded_annotations" Implemented by: Rawan Abubakr """ def get_dictionaries(annotations_path): """ Generates a dictionary that takes the word and output its encoded number and a reversed dictionary that takes the encoded number and output the word :param annotations_path: path of json annotation file :return dictionary, reversed_dictionary """ # TODO: dictionaries by Rawan Abubakr def encode_annotations(annotations_path): """ Encode all annotations and write the encoded result in a file called "encoded_annotations" :param annotations_path: path of json annotation file """ # TODO: encode annotations by Rawan Abubakr
true
73a78ccd974aa70e19132b2bb31caae24dafb661
ZdrStr/Validating-email-adress
/validating_email.py
868
4.21875
4
#Email validation ##Let's say you've created a registration form for people wanting to take part in your online book club. In order to send them invitations, you need to know their email address, so you are writing a program to check whether the field "email" is filled correctly. #Write a function that takes a string and checks that: #it doesn't contain spaces, #it contains the @ symbol, #after @, there's a dot, but in a correct address a dot shouldn't stand immediately after @, #(@. should not be in the string). #Note that dots may also occur before @! #The function should return True if all of the conditions are true, and False otherwise. #You are not supposed to handle input or call your function, just implement it. import re def check_email(string): return bool(re.fullmatch(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", string)) and True
true
12ed0cd893c23f2f90c0c599a6fb19e199eda111
xiaodongzi/pytohon_teach_material
/05/exec01.py
1,015
4.21875
4
# coding:utf-8 # 计算阶乘的函数 # 一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。自然数n的阶乘写作n!。 # 1. 增加浮点数的判断, # 2. 判断边界 不能大于65535 # return 返回的要保持类型一直,特定类型,实现单一类型。 def factorial(num): if not isinstance(num, int): # num is not a int return -2 if num < 0: # num is less than 0 return -1 if num == 0: return 1 # num > 0 result = 1 for i in xrange(1, num + 1): result *= i return result print type(factorial(1000)) print factorial(0) print factorial(-5) print factorial(30) def factorialRecursion(num): if num < 0: return 'Error, num must bigger than 0' elif num == 0: return 1 else: return num * factorialRecursion(num - 1) print factorialRecursion(0) print factorialRecursion(-1) print factorialRecursion(30)
false
e295dda570c76000fa7a810b939245b11a43c4c3
gustahvo/python_start
/GUESS_NUMBER/main.py
886
4.28125
4
#A MINI GAME IN PYTHON, WHERE WE HAVE TO GUESS A NUMBER BETWEEN 1 AND 10. #first we have to import the random library. import random #create a function guess for generate the random number. def guess(x): random_number = random.randint(1, x) # defining the range of the random_number. guess = 0 #geting a valor for the guess. while guess != random_number: # using the while loop to still running the prog at the user guess correctly( when the guess == random_number loop stop) . guess= int(input(f'Guess a number between 1 and {x}:\n')) if guess < random_number: print ('Sorry, guess again. Too low.') # tip. elif guess > random_number: print('sorry, guess again. Too high') #tip. print(f'congrats, you have guessed the number') #the end game. guess(10) # limit.
true
2140140e5b050a66c05128516c1bbb58d645a8a7
devangdayal/Data-Structures-Algorithm
/Search_Tech/BinarySearch.py
2,060
4.40625
4
# In this code, We will be discussing the implementation of Binary Search Algorithm # Config Python3 # Function to Search the key in the array. def binarySearch(arr, arrLen, num): # Lower Bound of Search nLow = 0 # Higher Bound of Search nHigh = arrLen - 1 center=0 while (nLow <= nHigh): center = (nLow + nHigh) // 2 # Check whether the number is less than the center if (arr[center] > num): # In this case , the higher bound is assigned to center nHigh = center-1 #Check whether the number is greater than the center elif (arr[center] < num): # In this case, the lower bound is assigned to the center nLow = center+1 #Number is in the Center else: return center # In case, the number doesn't exist in the array. return -1 # Function to input the array def inputArray(arrLen): arr = [] for x in range(arrLen): temp = int(input("Enter the Number ::")) arr.append(temp) return arr # Sorting the array # Thou we can simply use sort() function given in the python library, but we will use one of the Sorting Algorithm to Sort the array # In this case,we will use Bubble Sort Technique def sortArray(arr, arrLen): # Need to Traverse thru all the element in the Array for x in range(arrLen): # Need to Traverse till the last unsorted element for y in range(0, arrLen - x - 1): # If it is larger than the succeeding number it will perform swap if (arr[y] > arr[y + 1]): arr[y], arr[y + 1] = arr[y + 1], arr[y] return arr # Get the Input n = int(input("Enter the Length of Array ::")) arr = inputArray(n) # Sort the Array arr = sortArray(arr, n) print("The Sorted Array ::",arr) findNum = int(input("Enter the Number You want to Search ::")) location = binarySearch(arr, n, findNum) if (location == -1): print("The Number Doesn't Exist..!!") else: print("The Number found at index ::", location+1)
true
f63acfd1c5b0ec41f3395f3058d3f56a9a5d5db5
dailinou/507
/week1_hw/ttt.py
1,369
4.46875
4
''' SI 507 Fall 2018 Homework 1 ''' # Create board - Setup the data structure for storing board data # Loop until game is over # Step 1: Print board ''' This function will take in current board data and print out the board in the console as shown in the instructions. parameter: board_data - a data structure used for holding current moves on the board return: None ''' def print_board(board_data): pass # Step 2: Determine who is to move ''' This function will take in previous player data and determine which player is to take the move. parameter: previous player data return: information about current player data ''' def current_player(previous_player_data): pass # Step 3: Ask the user to take the move ''' This function will ask the player to take their move and update the board data. parameter: user input return: updated board data ''' def current_board(player_input): pass # Step 4: Determine if game is over ''' Take in the current board data and determine if one player wins the game or the game draws. If the game is over, terminate the loop, or continue the loop. parameter: board_data - current board data return: information about current game status ''' def determine_over(board_data): pass
true
2cd0ce66d5d8ba6dfacb78c3fb29ebf83d8276ac
RickyCaoCao/ProgrammingNotes
/python/python_review/ex21.py
548
4.3125
4
# Exercise 21 - Write to a File # 'r+' means both read and write mode # opening a file with 'w' will immediately delete file contents # numbers and objects must be strings in order to write to file f_name = raw_input("Enter file name: ") + ".txt" # Better Programming Practice for this # because we use and close # similar to C# 'using' with open(f_name, 'w') as a_file: a_file.write("Hello World!") # Alternative open_file = open(f_name, 'r') print(open_file.readline()) open_file.close() # this is bad if the program crashes before this
true
2df1d316523da1cf757131ff435bfedc245dba83
CamiloYate09/Python_3_Total
/Regular Expressions/Metacharacters_2.py
1,962
4.5
4
''' Metacharacters Metacharacters are what make regular expressions more powerful than normal string methods. They allow you to create regular expressions to represent concepts like "one or more repetitions of a vowel". The existence of metacharacters poses a problem if you want to create a regular expression (or regex) that matches a literal metacharacter, such as "$". You can do this by escaping the metacharacters by putting a backslash in front of them. However, this can cause problems, since backslashes also have an escaping function in normal Python strings. This can mean putting three or four backslashes in a row to do all the escaping. ''' # Metacharacters # # The first metacharacter we will look at is . (dot). # This matches any character, other than a new line. # Example: import re pattern = r"gr.y" if re.match(pattern, "grey"): print("Match 1") if re.match(pattern, "gray"): print("Match 2") if re.match(pattern, "blue"): print("Match 3") print('***********************************************************') # # Metacharacters # # The next two metacharacters are ^ and $. # These match the start and end of a string, respectively. # Example: import re pattern = r"^gr.y$" if re.match(pattern, "grey"): print("Match 1") if re.match(pattern, "gray"): print("Match 2") if re.match(pattern, "stingray"): print("Match 3") print('*******************************************************') # Curly Braces # # Curly braces can be used to represent the number of repetitions between two numbers. # The regex {x,y} means "between x and y repetitions of something". # Hence {0,1} is the same thing as ?. # If the first number is missing, it is taken to be zero. If the second number is missing, it is taken to be infinity. # Example: import re pattern = r"9{1,3}$" if re.match(pattern, "9"): print("Match 1") if re.match(pattern, "999"): print("Match 2") if re.match(pattern, "9999"): print("Match 3")
true
aa8704cb4924123135fc55c995434ecd82f2550d
wetorek/datastructures
/binary_tree/binary_tree_to_DLL.py
2,881
4.25
4
# Problem URL: https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/ { class Node: """ Class Node """ def __init__(self, value): self.left = None self.data = value self.right = None class Tree: #Binary tree Class def createNode(self, data): return Node(data) def insert(self, node, data, ch): if node is None: return self.createNode(data) if(ch=='L'): node.left = self.insert(node.left, data, ch) return node.left else: node.right = self.insert(node.right, data, ch) return node.right def search(self, lis, data): # if root is None or root is the search data. for i in lis: if i.data == data: return i def traverseInorder(self, root): if root is not None: self.traverseInorder(root.left) print(root.data, end=" ") self.traverseInorder(root.right) import sys def printDLL(head): #Print util function to print Linked List prev = None sys.stdout.flush() while(head != None): print(head.data, end=" ") prev=head head=head.right print('') while(prev != None): print(prev.data, end=" ") prev=prev.left print('') if __name__=='__main__': t=int(input()) for i in range(t): n=int(input()) arr = input().strip().split() tree = Tree() lis=[] root = None root = tree.insert(root, int(arr[0]), 'L') lis.append(root) k=0 for j in range(n): ptr = None ptr = tree.search(lis, int(arr[k])) lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2])) # print arr[k], arr[k+1], ptr k+=3 # tree.traverseInorder(root) # print '' head = None #head to the DLL head = bToDLL(root) printDLL(head) } ''' This is a function problem.You only need to complete the function given below ''' ''' class Node: """ Class Node """ def __init__(self, value): self.left = None self.data = value self.right = None ''' def leftMostNode(root): if root is None: return None if root.left is None: return root return leftMostNode(root.left) def rightMostNode(root): if root is None: return None if root.right is None: return root return rightMostNode(root.right) #Your task is to complete this function #function should return head to the DLL def bToDLL(root): if root is None: return None left = rightMostNode(bToDLL(root.left)) root.left = left if left is not None: left.right = root right = bToDLL(root.right) root.right = right if right is not None: right.left = root return leftMostNode(root)
true
640ae8add02efca205a9493c98c2572ef6564e02
ChallengerCY/Python-ListDemo
/pythonList/listdemo6.py
1,110
4.46875
4
#3、分片赋值 #修改 name=list('perl') name[2:]=list('ar') print(name) #可以替换原长度 name=list('perl') name[1:]=list('ython') print(name) #可以在不替换任何元素的情况下插入新元素 number=[1,5,5] number[1:1]=[2,3,4] print(number) #可以删除序列 number=[1,2,3,4,5,7,8,9] number[1:2]=[] print(number) #九、列表方法 #1、append方法(用于在列表末尾追加新的对象) list1=[1,2,3] list1.append(4) print(list1) #2、count方法统计某个元素在列表中出现的次数 list2=[1,1,1,2,3] print(list2.count(1)) #3、extend方法可以在列表的末尾一次追加序列中的多个值,可以扩展多个序列(返回的序列是list3,而使用list3+list4会得到一个全新的序列,效率会比较低,分片操作也可以实现,不过可读性差) list3=[1,2,3] list4=[4,5,6] list3.extend(list4) print(list3) #4、index方法用于从列表中找出某个值第一个匹配项的索引位置 print(list1.index(2)) #5、insert方法用于将对象插入到列表中,分片操作也可以实现,但是可读性较差 list1.insert(1,5) print(list1)
false
b3ec432f787de44fc90bd88b7aebb14fc00ad033
eclipse-ib/Software-University-Entry-Module
/Programing_Basics_with_Python/2 Conditional Statements/More/dema.py
321
4.125
4
# num = int(input()) # # if num > 5: # print(">5") # # elif num < 5: # print("<5") # # elif num == 5: # print("=5") # # else: # print("none") # # --------------------------------------- day = input() print("Enter number: ") if day == "Monday": num1 = float(input()) else: num2 = float(input())
false
c7520b1d4cbbd5ca2d3af979590b70cb68191ad2
eclipse-ib/Software-University-Entry-Module
/Programing_Basics_with_Python/7 Nested Loops/3-Суми_прости_и_непрости_числа.py
1,017
4.21875
4
import math prime_sum = 0 not_prime_sum = 0 is_prime = True while True: number = input() if number == "stop": break intiger_num = int(number) if intiger_num < 0: print(f"Number is negative.") continue else: end_i = math.sqrt(intiger_num) for num in range(2, int(end_i) + 1): if intiger_num / num == intiger_num // num: is_prime = False else: is_prime = True if is_prime: prime_sum += intiger_num else: not_prime_sum += intiger_num # if int(number) > 1: # # for i in range(2, int(number)//2): # if int(number) % i == 0: # not_prime_sum += int(number) # else: # prime_sum += int(number) # # elif int(number) < 0: # print(f"Number is negative.") # continue print(f"Sum of all prime numbers is: {prime_sum}") print(f"Sum of all non prime numbers is: {not_prime_sum}")
false
09d1cc8c544520546ab74fe9dafbd30d9c3a2ebb
SSJ1Joey/PDXCGLabs
/anagram.py
783
4.21875
4
def check_palindrome(): x = input('Give me a word: ').lower() print(f'You typed the word: {x}') word = list(x) s_word = list(x) word.reverse() if word == s_word: print(f'{x}: is a palindrome.') else: print(f'{x}: is not a palindrome...') #check_palindrome() def check_anagram(): f_word = input('Please give me a word to check: ').lower() s_word = input('Please give a second word to check: ').lower() print(f'You typed {f_word} and {s_word}.') word1 = list(f_word) word2 = list(s_word) word1.sort() word2.sort() if word1 == word2: print(f'{f_word} and {s_word}: are anagrams.') else: print(f'{f_word} and {s_word}: are not anagrams...') #check_anagram()
false
9e748ac9d2d8018ab0bfc84a28121135079c7072
SMathewsMMC/myProject
/Random Number Generator/Algorithims_and_Data_Structures.py
2,288
4.1875
4
# -*- coding: utf-8 -*- """ Program Name: Random Number Generator and Factors of 3 Writen by: Sean Mathews Date: 11 September 2020 Synopsis: This will take a set of random numbers between 1 and 1 million and put them in an array of 10 integers. Then will factor each integer in the array by 3 and if it is valid true, will add them to a new array. It will also output the total time it took in seconds the program took to complete. """ import time # Import library that for random numbers import random # sets the current time as the start_time variable start_time = time.time() """ # sets int1 variable to random int between 1 and 1 million int1 = random.randint(1, 1000000) # Print a concatenated string with random generated variable print("Random int between 1 and 1M:", int1) """ # Create array called randomInArray. randomIntArray = [] # Sets array length to 10 integers. for i in range(0, 100): # Any random numbers from 0 to 1M. randomIntArray.append(random.randint(0, 1000000)) # Print a concatenated string of the random integers in the array print("Random Int Array values are:\n", randomIntArray, "\n") # Creates array called factoredArray. factoredArray = [] # loads each int in the array. for n in randomIntArray: # Checks to see if the int from the array is factorable by 3. if n % 3 == 0: # Add each int that was factorable by 3 to a new array. factoredArray.append(n) # print a concatenated string of the factored integers in the array print ("The factored list is:\n", factoredArray, "\n") # prints the number of random ints added to the randomIntArray print("# of integers in randomIntArray is:", len(randomIntArray)) # prints to console the ints that were factors of 3 into factored Array print("# of integers in factoredArray is:", len(factoredArray), "\n") # sets the current time as the end_time variable end_time = time.time() # math magic taking the end_time and subracts the start_time total_time = float(end_time - start_time) # prints the math results of you total time in seconds print ("You waited [", total_time, "] seconds")
true
5fe4a9f01ec0d148318d90b26b167214d447b215
Jason30102212/python_basics_refresher
/4.WorkingWithStrings.py
890
4.1875
4
# 4.WorkingWithStrings print("Test String") # Basic string print("Test\nString") # New line (\n) print("Test \"String") # Escape character (\") # concat phrase = "This is " print(phrase + "a test string") # string functions phrase = "Random Phrase" print(phrase.upper()) # Conver to upper print(phrase.isupper()) # determines if upper print(phrase.upper().isupper()) #conver to upper and determine if so print(len(phrase)) # Length of string print(phrase[0]) # Print specific letter at location print(phrase.index("a")) # Print index of first instance # print(phrase.index("z")) # Print index of first instance #Error. No instance of 'Z' print(phrase.replace("Phrase", "String")) # custom function randomString = "This is a random string" def stringFormatter(stringToFormat): formattedString = stringToFormat.upper() return formattedString print(stringFormatter(randomString))
true
5de9303e9148c88d3f6762437e8a424eaf2a861a
anitanavgurukul/ifelsepython
/leap year.py
376
4.21875
4
# year=int(input("enter the year")) # if year%4==0 and year%100!=0 or year%400==0: # print("is leap year") # else: # print("is not leap year") year=int(input("enter the year:")) if year%4==0: pass if year%100!=0 or year%400==0: print("is leap year") else: print("not leap year") else: print("invalid year")
false
4bba7576def382893b127d17f72e66ad23f58946
janavarro95/Python-iDTech-Cryptography
/ShiftCypher/SimpleShiftCypher/main.py
1,419
4.125
4
from Alphabet import Alphabet; #Make a mode for encrypting or decrypting a message. val=input("Please chose to encrypt(e), decrypt(d), or brute force(b) a message"); base=Alphabet(0); while(val!="d" and val!="e" and val!="b"): print("Invalid input. Please try again."); val=input("Please chose to encrypt(e), decrypt(d), or brute force(b) a message"); val=val.lower(); #Unify input. if(val=="e"): message=input("Enter a secret message!: "); offset=input("Enter a number 0-26 to offset these values by: "); while(not offset.isdigit()): print("Invalid input. Please try again."); offset=input("Enter a number 0-26 to offset these values by: "); offset=int(offset)%len(base.letters); alph=Alphabet(offset); print("Your secret message is: "+alph.encryptMessage(message)); if(val=="d"): message=input("Enter a secret message!: "); offset=input("Enter a number 0-26 to offset these values by: Hint if you know the offset type it in. "); offset=int(offset)%len(base.letters); alph=Alphabet(offset); print("Your secret message is: "+alph.decryptMessage(message)); if(val=="b"): message=input("Enter a secret message!: "); for i in range(0,len(base.letters)): offset=i; offset=offset%len(base.letters); alph=Alphabet(offset); print("Your secret message is: "+alph.decryptMessage(message));
true
a69945b30339eb7541deb87afb750523a6388adb
DPinson/transposer
/transpose.py
2,693
4.25
4
"""Author: Denis Pinson Date : 16/05/2020 Goal : to change a text letter by letter, consonant to consonant and voyel to voyel, in a different order you can choose between 3 languages in: the text you want to change (exemple : Hello World) out: the new changed text (exemple : Byffe Qelfw) """ import tkinter as tk import transposerLanguage as tL # Language constants to choose starting language and which changes to make FRANCAIS = 1 ENGLISH = 0 ARABIAN = 2 class Transpose(): """Where you can find the function to change the text to the new version """ def changeText(self, *args): """ This function return the new text """ message = base_text.get() new_text = "" lang = var_lang.get() for i in range(len(message)): if lang == ENGLISH: new_text += tL.transposerEnglish(message[i]) elif lang == FRANCAIS: new_text += tL.transposerFrancais(message[i]) else: new_text += tL.transposerArabian(message[i]) i =+ 1 var_new_text.set(new_text) transposer = tk.Tk() transposer.wm_state('zoomed') # for full screen transposer.configure(bg="lightgreen") transposer.positionfrom("user") transposer.title("Transposer un texte") page = tk.LabelFrame(transposer, border=0, background="lightgreen", text="Appli pour transposer du texte") choose_lang = tk.LabelFrame(page, width=20, background="lightgreen", text="Choisissez votre langue de départ") var_lang = tk.IntVar() radioEnglish = tk.Radiobutton(choose_lang, text="Anglais", value=ENGLISH, variable=var_lang, background="lightgreen", width="10") radioFrancais = tk.Radiobutton(choose_lang, text="Français", value=FRANCAIS, variable=var_lang, background="lightgreen", width="10") radioArabian = tk.Radiobutton(choose_lang, text="Arabe", value=ARABIAN, variable=var_lang, background="lightgreen", width="10") entries = tk.LabelFrame(page, background="lightgreen", text="Entrer un texte à transcoder") var_base_text = tk.StringVar() var_base_text.trace("w", Transpose.changeText) base_text = tk.Entry(entries, textvariable = var_base_text) outsees = tk.LabelFrame(page, background="lightgreen", text="Voici le texte modifié") var_new_text = tk.StringVar() new_text = tk.Entry(outsees, textvariable = var_new_text) page.pack(fill=tk.BOTH) outsees.pack(fill=tk.X, side="bottom") new_text.pack(fill=tk.X) entries.pack(fill=tk.X, side="bottom") base_text.pack(fill=tk.X) choose_lang.pack(side="left") radioArabian.pack() radioFrancais.pack() radioEnglish.pack() transposer.mainloop()
true
4eec3c7d410a90a69b1d66fbd70b65c9f00a5c96
tobias-fyi/vela
/ds/practice/daily_practice/20-07/assets/code/merge_two_linked_lists.py
2,522
4.15625
4
from __future__ import annotations # Definition for singly-linked list. class ListNode: def __init__(self, val: int = 0, next: ListNode = None): self.val = val self.next = next def __str__(self): return f"ListNode({self.val}, {self.next})" # Helper function to (re)construct linked lists from integers def int_to_linked_list(num: int, last_node: ListNode = None) -> ListNode: """Constructs a linked list from an integer, with digits stored in reverse order, each node containing a single digit. """ # === Base case: no more numbers === # # But if number starts as 0, should be added as node if num == 0 and last_node is not None: return None # Last digit is first to be added # To return last digit, take modulo 10 last_digit = num % 10 # Then to remove the last digit, floor divide by 10 new_num = num // 10 print(f"{new_num} -> {last_digit}") # Create ListNode using last_digit node = ListNode(last_digit) # Assign to last node's next, if exists if last_node: last_node.next = node # Call function recursively int_to_linked_list(new_num, node) return node def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: # Compare values of two nodes if l1.val <= l2.val: # Instantiate ListNode from lesser value first_node = ListNode(l1.val) l1 = l1.next else: first_node = ListNode(l2.val) l2 = l2.next last_node = first_node while l1 or l2: if l1 is None: node = ListNode(l2.val) l2 = l2.next elif l2 is None: node = ListNode(l1.val) l1 = l1.next else: # Compare values of two nodes if l1.val <= l2.val: # Instantiate ListNode from lesser value node = ListNode(l1.val) # Increment pointer for that list l1 = l1.next else: # Instantiate ListNode from lesser value node = ListNode(l2.val) # Increment pointer for that list l2 = l2.next # Set last node's next to current node last_node.next = node last_node = node # Return the first node return first_node # === Test it out === # # Create linked lists list1 = int_to_linked_list(421) print(list1) list2 = int_to_linked_list(431) print(list2) # === Merge! === # list3 = mergeTwoLists(list1, list2) print(list3)
true
d0653ad0b66d892cb8934c5a7273d4f21ef51cfa
tobias-fyi/vela
/cs/lambda_cs/02_algorithms/Sorting/src/iterative_sorting/iterative_sorting.py
2,809
4.25
4
""" Algorithms :: Iterative sorting """ # Import time to track algorithm runtime import time # Test list to use while writing functionality unsorted = [18, 70, 1, 54, 84, 48, 7, 28, 96, 13, 2, 77, 63, 46, 87, 73, 52, 29] # Implement the Bubble Sort function below def bubble_sort(arr: list): """Simple implementation of the Bubble Sort algorithm. Loops through the array, comparing the value at each index, `i`, with that of its neighbor, `i + 1`. If `i` is greater, swap the two values. :param arr (list) : List to be sorted. :return (list) : Sorted list. """ # Variable to keep track of if the algorithm should continue or stop swap_count = 0 # Loop through n-1 elements for i in range(0, len(arr) - 1): # Compare with neighbor if arr[i] > arr[i + 1]: # Lower index is higher value - swap # Pop first item out of list into temporary variable tmp_val = arr.pop(i) # Insert popped value after current index (which now holds i+1's value) arr.insert(i + 1, tmp_val) swap_count += 1 # Count as a swap # else: # Lower index is lower value - don't swap # If a swap occurred during the loop, restart it - aka call the function again if swap_count > 0: bubble_sort(arr) return arr start = time.time() bubble_sorted_list = bubble_sort(unsorted) end = time.time() print(bubble_sorted_list) print(f"Bubble sort runtime: {end - start}") def selection_sort(arr: list): """Simple implementation of the Selection Sort algorithm. Loops through the array, looking for the smallest item to the right of the current one and swapping those two values. :param arr (list) : List to be sorted. :return (list) : Sorted list. """ # Loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # Find next smallest item to the right of current item for j in range(cur_index + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # Swap the values at the two indices in question # First, extract the two values cur_index_val = arr[cur_index] smallest_index_val = arr[smallest_index] # Assign each to the other's index arr[cur_index] = smallest_index_val arr[smallest_index] = cur_index_val return arr start = time.time() select_sorted_list = selection_sort(unsorted) end = time.time() print(select_sorted_list) print(f"Selection sort runtime: {end - start}") # Confirm the sorting resulted in the same order assert bubble_sorted_list == select_sorted_list # TODO: STRETCH - Implement the Count Sort function below def count_sort(arr, maximum=-1): return arr
true
5b595cc8e0cc5ebc7b4202b1d1cd78717d16e4b3
tobias-fyi/vela
/cs/lambda_cs/07_computer_architecture/notes/674/twoscomplement.py
2,122
4.125
4
""" Why does bitwise NOT (~) produce negative numbers? It has to do with how negative numbers are represented in memory. It's done with something called _2's Complement_. For this week, we've been assuming all numbers are unsigned, i.e. only positive. Which means that an 8 bit 255 is 0b11111111. And 0 is 0b00000000. But there's no room there for negatives. So 2's complement was created. It uses the same bit patterns for positive numbers, but reserves others for negatives. Notably, any number with a 1 bit for the high (left) bit is a negative number. The output of this program is: Signed: 8 0b00001000 7 0b00000111 6 0b00000110 5 0b00000101 4 0b00000100 3 0b00000011 2 0b00000010 1 0b00000001 0 0b00000000 -1 0b11111111 -2 0b11111110 -3 0b11111101 -4 0b11111100 -5 0b11111011 -6 0b11111010 -7 0b11111001 -8 0b11111000 Unsigned: 8 0b00001000 7 0b00000111 6 0b00000110 5 0b00000101 4 0b00000100 3 0b00000011 2 0b00000010 1 0b00000001 0 0b00000000 255 0b11111111 254 0b11111110 253 0b11111101 252 0b11111100 251 0b11111011 250 0b11111010 249 0b11111001 248 0b11111000 Notice how the bit pattern for 255 is exactly the same as the bit pattern for -1! So the NOT is working... it's taking 0b00000000 and turning it into 0b11111111. And that _would_ be 255 unsigned. However, Python prints things out as _signed_ by default, so your 0b11111111 becomes -1. You can override this behavior by bitwise ANDing the number with a mask to force it positive, like the bin8() function does, below. """ def bin8(v): # AND with 0b11111111 # vvv return f'0b{v & 0xff:08b}' # ^^^ # Print binary with field width 8 and pad with leading zeros print("Signed:\n") for i in range(8, -9, -1): print(f'{i:3} {bin8(i)}') print("\nUnsigned:\n") for i in range(8, -1, -1): print(f'{i:3} {bin8(i)}') for i in range(255, 247, -1): print(f'{i:3} {bin8(i)}')
true
adaed7a683ad2ec78f6f2af531f83c1129139d5e
tobias-fyi/vela
/cs/lambda_cs/03_data_structures/queue_and_stack/dll_queue.py
1,048
4.21875
4
""" Data Structures :: Queue """ import sys sys.path.append("../doubly_linked_list") from doubly_linked_list import DoublyLinkedList class Queue: def __init__(self): """Implementation of a Queue (FIFO). A doubly-linked list is used as the underlying data structure because the methods for manipulating the two data structures are very similar.""" self.storage = DoublyLinkedList() def enqueue(self, value): """Adds an item to the back of the queue. :param value : Item to be added to the queue. """ self.storage.add_to_tail(value) def dequeue(self): """Removes an item from the front of the queue. :return value : Value of dequeued item or None. """ # Empty queue case is handled by DLL method value = self.storage.remove_from_head() return value def len(self): """Calls `len()` on the queue. :return length (int) : Length of queue. """ return len(self.storage)
true
4b8c710bbba9d609c91948488ace2f8965fc2723
tobias-fyi/vela
/cs/lambda_cs/02_algorithms/Sorting/src/iterative_sorting/notes/insertion_sort.py
665
4.1875
4
""" Algorithms :: Sorting """ the_list = [4, 5, 8, 2, 1, 8, 9, 3, 5] def insertion_sort(arr): # Separate first element, think of it as sorted # For all other indices, starting at 1 for i in range(1, len(arr)): # Put current number in a temp var temp = arr[i] # Look left, until we find where it belongs j = i while j > 0 and temp < arr[j - 1]: # As we look left, shift items to the right as we iterate arr[j] = arr[j - 1] j -= 1 # When left is smaller than temp, or we're at 0, put at this spot arr[j] = temp return arr (insertion_sort(the_list))
true
e7bfcb307fb56c6812251350b3414fbb189fbf66
bhawana01/Python-Basic-Practices
/find_angle.py
245
4.15625
4
def another_angle(): print('\n\n************ Find another angle of Triangle **************') a = input('First angle') b = input('Second angle') a = int(a) b = int(b) c = 180 - (a + b) print('Third angle :', c)
true
56445945f919ee175790c234783392aec87525df
Yucheng7713/CodingPracticeByYuch
/Easy/703_kthLargestElementInAStream.py
1,213
4.125
4
import heapq class KthLargest: # Keep a fixed k size min heap to keep the top ( minimum ) as the k-th largest element def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ self.k = k self.heap = nums heapq.heapify(self.heap) # Get rid of the elements smaller than k-th largest element # Those elements won't affect the result while len(self.heap) > k: heapq.heappop(self.heap) def add(self, val): """ :type val: int :rtype: int """ if len(self.heap) < self.k: heapq.heappush(self.heap, val) # If the answer is changed elif val > self.heap[0]: # Pop the old k-th largest element and insert the new val # After heapify, return the new k-th largest element heapq.heapreplace(self.heap, val) return self.heap[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val) obj = KthLargest(3, [4,5,8,2]) print(obj.add(3)) print(obj.add(5)) print(obj.add(10)) print(obj.add(9)) print(obj.add(4))
false
e3bdd28b0b01367e451d0af72d4dba1cc110b9e3
Yucheng7713/CodingPracticeByYuch
/CTC_Practice/Ch1_4_palindromePermutation.py
1,110
4.28125
4
# Given a string, write a function to check if it is a permutation of a palindrome. # The definition of palindrome : a word or phrase that is the same forwards and backwards. # There are two types of palindrome : # 1. bab # 2. baab # Notice the number of occurences of each character, each character appears even number of times. # Only at most one character is allowed to appear odd number of times # If there are more than one character appear odd number of times, then there is no way for this string to # form a palindrome. # Therefore, we just need to check the number of occurences of each character. # if there appears no odd occurences character or only one odd occurences character, then return True. # Time complexity : O(n) # Space complexity : O(n) def palindromePermutation(str): from collections import Counter p_str = str.lower().replace(" ", "") p_counter = Counter(list(p_str)) n = 0 for v in p_counter.values(): if v % 2 == 1: n += 1 return n == 0 or n == 1 if __name__ == "__main__": str = "aab" print(palindromePermutation(str))
true
68577ce475dd2c0bece5fadb36d29701c2cc1d80
Yucheng7713/CodingPracticeByYuch
/Hard/23_mergeKSortedList.py
1,234
4.125
4
import heapq # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # Use heap to populate the minimum node among the lists def mergeKLists(self, lists): heap = [] # Store the candidate minimum nodes to the heap for i, l_node in enumerate(lists): if l_node: heap += [(l_node.val, i, l_node)] heapq.heapify(heap) temp = result = ListNode(0) while heap: # Each time pop the minimum node from the heap # The popped node is guarantee to be the minimum node among the lists n_value, seq, n = heapq.heappop(heap) # If there is still node behind the popped node, push it into the heap if n.next: heapq.heappush(heap, (n.next.val, seq, n.next)) # Regular node concatenation temp.next = n temp = temp.next return result.next a, b, c = ListNode(1), ListNode(4), ListNode(5) a.next, b.next = b, c d, e, f = ListNode(1), ListNode(3), ListNode(4) d.next, e.next = e, f g, h = ListNode(2), ListNode(6) g.next = h print(Solution().mergeKLists([a, d, g]))
true
a9543aae3bf8b11c2b177589db7b3ca678c7c863
akshatdodhiya/Guess-the-number-python-program-game
/Guess_the_number_game.py
1,614
4.375
4
# Program Developed by Akshat Dodhiya # Exercise - 3 from random import random n = int(random() * 10) # Generating random number tries = 3 # Initializing the number of tries in the beginning of the game guess = 1 # Initializing the number of guesses print("This game is made by ~ Akshat Dodhiya") print("About this game :\n" "1.You have to guess the numbers between 0 to 10.\n" "2.You will get three tries to guess the number.\n") # Printing about of the game while True: # An infinite loop to start the game if tries == 0: # Printing statement if the user ran out of chances print("\n!! GAME OVER !! :( \n") print("The correct number was", n) break print("You have ", tries, " tries left !!\n") # Printing number of chances left for the user inp = int(input("Guess the number between 0 to 10\n")) # Taking the input of the user for number if inp > n: # Condition if the guessed number is greater than the number to be guessed print("\nYour number is too big guess smaller number\n") tries = tries - 1 guess = guess + 1 continue elif inp < n: # Condition if the guessed number is smaller than the number to be guessed print("\nYour number is too small guess bigger number\n") tries = tries - 1 guess = guess + 1 continue else: # Condition if the user guesses the correct number print("\nCongratulations you have guessed correct number :)\n") print("\nYou took ", guess, " guesses to finish !! ^_^") tries = tries - 1 break
true
8374dccabc09ae74c2e06017c4451326a3815deb
WillSchick/LeetCode-Solutions
/DynamicProgramming/climbStairs.py
1,479
4.1875
4
## Climbing Stairs ## Will Schick ## 10/3/2019 ## # You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? ## # Recursive solution def climbStairsRecursion(n): # n = number of stairs # Base case: We're on the floor or the first step if n == 0 or n == 1: return 1 else: # Step is GREATER than 1 (2 or above) return climbStairsRecursion(n-1) + climbStairsRecursion(n-2) # I'm only just getting into Memoized and bottom up solutions, so forgive me if this doesn't work quite right! # Dynamic Programming solution (Memoized Solution) def climbStairsDynamic(n, memo): if memo[n] is not None: # If the index exists, return it instead of computing it. return memo[n] # This allows us to save on repetitious computation time (Better than our recursive solution!!!!) else: # If we need to compute it if n == 0 or n == 1: # If we're on the floor or bottom step... memo[n] = 1 return 1 else: # If we're step 2 or higher... memo[n] = climbStairsDynamic(n-1, memo) + climbStairsDynamic(n-2, memo) return memo[n] def main(): # Set stairs n = 10 print(climbStairsRecursion(n)) memo = [None] * (n+1) # Create an empty list with n+1 elements for memoing print(climbStairsDynamic(n,memo)) main()
true
6e36119974af00a9be29f24bd9bc8ecc86daa65b
ayazabbas/python-exercises
/solutions/2/2.py
636
4.1875
4
import random # import random so we can use the randint() function numbers = [] # Create an empty list evenNumbers = [] while len(numbers) < 20: # While the length of our list is less than 20 numbers.append(random.randint(1, 100)) # Add a random number between 1 and 100 to the list print(numbers) # Here, we look at each element in the list one at a time and treat it as a variable 'x' for x in numbers: if x % 2 == 0: # Here we use the % operator to check if x is even or odd evenNumbers.append(x) # If it's even we add it to the list, if not we do nothing and move on to the next element print(evenNumbers)
true
91bd9c8999b70cb97117c0e57beb4130655afc13
staskur/infa_2020
/labs/proba/sortirovki N2.py
1,439
4.125
4
# сортировки def insert_sort(A): """ сортировка списка А вставками """ N = len(A) for verh in range(1,N): k=verh while k>0 and A[k-1] > A[k]: A[k],A[k-1] = A[k-1],A[k] k-=1 def choice_sort(A): """ сортировка списка А выбором """ N=len(A) for poz in range(0,N-1): for k in range(poz+1, N): if A[k] < A[poz]: A[k], A[poz] = A[poz], A[k] def bubble_sort(A): """ сортировка списка А пузырьком """ N = len(A) for obhod in range(1,N): for k in range(0, N-obhod): if A[k] > A[k+1]: A[k],A[k+1] = A[k+1],A[k] def test_sort(sort_algoritm): print("Тестируем :", sort_algoritm.__doc__) print("testcase #1: ", end="") A=[4,2,5,1,3] A_sorted= [1,2,3,4,5] # B=A[:] sort_algoritm(A) print("Ok" if A == A_sorted else "Fail") print("testcase #2: ", end="") A = list(range(10,20))+list(range(0,10)) A_sorted = list(range(20)) # B=A[:] sort_algoritm(A) print("Ok" if A == A_sorted else "Fail") print("testcase #3: ", end="") A = [4, 2, 4, 2, 1] A_sorted = [1, 2, 2, 4, 4] sort_algoritm(A) print("Ok" if A == A_sorted else "Fail") if __name__ == "__main__": test_sort(insert_sort) test_sort(choice_sort) test_sort(bubble_sort)
false
d261f4ec31c63f4de6d116b18fc26e3c395204c6
DIT-Python/list-file-io-example
/memo_예제.py
507
4.34375
4
## 메모장 프로그램 예제 ## 사용자 입력을 파일에 기록하는 함수 def write_your_memo(mode): f = open("D:\\memo.txt",mode) memo =input("input your memo> ")+"\r\n" f.write(memo) f.close ## 파일열기 선택 mode = input("w: New memo note, a: Append your memo? ") ## 열기 모드에 따른 동작 if mode == "w" or mode == "a": write_your_memo(mode) if mode == "w": print("Wrote your memo to a new note") else: print("Appended your memo...") else: print("Wrong command!")
false
084e77ec9105f26d656a46750dee82333b6b905d
melihcanyardi/Python-Crash-Course-2e-Part-I
/ch8/user_albums.py
634
4.3125
4
def make_album(artist, title, num_songs=None): """Returns a dictionary of artist name, album title, and number of songs.""" return {'artist_name': artist, 'album_title': title, 'number_of_songs': num_songs} while True: print("Please enter the details of the album.") print("(enter 'q' at any time to quit.") artist = input('Enter artist name: ') if artist == 'q': break title = input('Enter album title: ') if title == 'q': break num_songs = input('Enter the number of songs in the album: ') if num_songs == 'q': break print(make_album(artist, title, num_songs))
true
f0602e4a009265a41305ac566cb1d7cbe6eb3fa7
thej123/Lamda
/inheritance.py
1,978
4.28125
4
class Person(object): def __init__(self, first, last, age): self._firstname = first self._lastname = last self._age = age """ # Getter method def Name(self): return self._firstname + " " + self._lastname """ # Generate a `string casting` for our classes and we can simply print out instances. This makes a leaner design. def __str__(self): return self._firstname + " " + self._lastname + ", " + str(self._age) # Employee inherits from Person class Employee(Person): def __init__(self, first, last, age, staffnum): # The __init__methof of Person class is explicitly invoked. # Person.__init__(self, first, last) # Instead we can use super instead. super(Employee, self).__init__(first, last, age) self._staffnum = staffnum """ def GetEmployee(self): return self.Name() + ", " + self._staffnum """ """ def __str__(self): return self._firstname + " " + self._lastname + ", " + self._staffnum """ # Method `Overriding` is an object-oriented programming feature that allows a subclass to provide a different implemetation of a method that is already defined by its superclass or by one of its superclasses. The implementation in the subclass overrides the implementation of the superclass by providing a method with the same name, same parameters or signature, and same return type as the method of the parent class. # `Overloading` is the ability to define the same method, with the same name but with a different number of arguments and types. It's the ability of one function to perform different tasks, depending on the number of parameters or the types of the parameters. def __str__(self): return super(Employee, self).__str__() + ", " + self._staffnum x = Person("Marge", "Simpson", 28) y = Employee("Homer", "Simpson", 36, "1007") print(x) print(y) # print(x.Name()) # print(y.GetEmployee())
true
c71d54ba2026ca1ca49ebe0c4630e911988a16e3
andresgerz/python-course
/data_structure
1,650
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 9 15:49:55 2019 @author: andres """ """ Learn all data structure Use modules as NumPy, Pandas, time, sys, ... """ import time ############ 1) Bubble sort ######## list1 = [2, 9, 5, 10, -1, -5] print("Original order: ", list1) start = time.time() def bubble_sort(arr): def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swapped = True x = -1 while swapped: swapped = False x += 1 for i in range(1, n - x): if arr[i - 1] > arr[i]: swap(i - 1, i) swapped = True return arr print("\n\n", bubble_sort(list1)) print("Bubble sort --> Time: ", (time.time() - start) * 1000, "ms") print("=======================================================") ######## 2) Selection sort start3 = time.time() def selection_sort(arr): for i in range(len(arr)): min = i for j in range(i + 1, len(arr)): if arr[j] < arr[min]: min = j arr[min], arr[i] = arr[i], arr[min] return arr print(selection_sort(list1)) print("Selection sort --> Time: ", (time.time() - start3) * 1000, "ms") print("=======================================================") ######## 3) Insertion sort ######## # def insertion_sort(arr): """ for i in range(list1): """ ######## 7) Sorted function ########## start4 = time.time() print(sorted(list1)) print("Sorted function --> Time: ", (time.time() - start4) * 1000, "ms") # then make all methods with the list, after that excercise order with matrixs
false
f08129d5ceeb5dec0fc89172e3829809c2556533
FatemehRezapoor/LearnPythonTheHardWay
/LearnPythonTheHardWay/inheritance(class).py
2,221
4.59375
5
# June 8, 2018 # Parents and Subclass # Source: https://www.digitalocean.com/community/tutorial_series/object-oriented-programming-in-python-3 """ A parents class which can define some of the main properties of a fish""" class Fish(object): def __init__(self, firstname, lastname='fish', body='bone'): # This means the last name is always fish self.firstname = firstname self.lastname = lastname self.body = body def swim(self): print('%s is swiming' % self.firstname) def swimback(self): print('%s can swim backward' % self.firstname) Dokme = Fish('Dokme') Dokme.swim() print(Dokme.body) """ Child class called goldfish""" class newfish(Fish): pass # passes everything from the class Goldfish = newfish('Goldy') Goldfish.swim() """ Another child class which has some functions""" class catfish(Fish): def food(self): print('%s eats carrots' % self.firstname) # Function just for this child Catty = catfish('Catty') Catty.swim() Catty.food() # HOW TO OVERRIDE A PARENT CLASS class shark(Fish): # Because we want to over write parents we need to start with init def __init__(self, firstname, lastname='Shark'): self.lastname = lastname self.firstname = firstname def swim(self): print('%s%s can not swim' % (self.firstname, self.lastname)) sharky = shark('Sharky') print(sharky.lastname) # print(sharky.body) # Becasue you use init, you have changed the whole attributes # * IMPORTANT: When ever you use init in the child, you are changing the parents * # How to change a part of parents but use other attributes? # Super() function will do this class domsia(Fish): def __init__(self, Behaviour='Bad Boy'): # over writes the whole parents self.Behaviour = Behaviour super().__init__(self) # Re read the whole parents Domy = domsia() # starts the class with your new sets. print(Domy.Behaviour) # To call sth from paretns you need ti initialise the paretns # Parents needs a first name to initialise Domy.firstname = 'Domy' # parents is called print(Domy.lastname) Domy.swim()
true
831115c27768d56bf6d0b582699ca27cd5b4338e
FatemehRezapoor/LearnPythonTheHardWay
/LearnPythonTheHardWay/E20FunctionFile.py
1,086
4.59375
5
# June 1 , 2018 # This exercise is used to make function to read a text file # IMPORTANT POINT: Whenever you read a file, the cursor gors to the end of the file. So if you want to read it again the # out put will be EMPTY unless you use txt.seek(0) which will remove the cursor to the beginning of the file or to the # location you want to # function is dealing in bytes, not lines. So that’s going to the 0 byte (first byte) in the file from sys import argv script, file = argv txt = open(file, 'r') def read_all(arg1): print(arg1.read()) def read_half(arg1): print(arg1.seek(0)) # moves the cursor to the beginning of the file def read_line(linecount, arg2): print(linecount, arg2.readlines()) read_all(txt) read_half(txt) read_line(1, txt) # Mini project: how to read the whole text file with readline() txt.seek(0) for line in txt: print(line) # Important point: If you go txt.readline(3) it only prints out the 3 charactros of your line txt.seek(5) # moves the cursor to the 5th charactor print(txt.read())
true
07ddb19ef4cb74573fc201d0cc135fb5929baf61
FatemehRezapoor/LearnPythonTheHardWay
/LearnPythonTheHardWay/E1_10Variable.py
890
4.21875
4
# Updated July 8, 2020 # Exercise 1-10 ( Variable ) # ** Different Types ** a = 2 b = 2.0 c = 'salam' d = True e = None print(type(a),type(b),type(c),type(d),type(e)) # ** LIST AND TULIPS # List is mutable which means we can rewrite and change the length al = [1, '2', True] print(al,al[1],type(al),type(al[2])) al[1] = 'sara' print('This is a new list: {}'.format(al[1])) al.append('Omid') al.insert(0,'Maman') print('This is a new list: {}'.format(al)) # Tulip is not as flexible as a list and you can not add or change anything at = (1, '2', [True]) print(at,at[1],type(at),type(at[2])) # ** How to check if two variables are the same object? if a is b: print('a is the same type') else: print('a is a different type') # ** How to check if the object is specific type? if isinstance(at,list): print('yep') else: print('Nope')
true
40f0327685f03067cd8ac09e4911a5426e9491c5
cseai/python-crash-course
/lecture-04/numbers.py
702
4.34375
4
# Making Numerical Lists # Using the range() Function for value in range(1,5): print(value) # Using range() to Make a List of Numbers N_numbers = list(range(1, 11)) print(N_numbers) Even_numbers = list(range(2, 11, 2)) print(Even_numbers) num_data = [12, 34, 5, 0, 39000] print(f"Min number : {min(num_data)}") print(f"Max number : {max(num_data)}") print(f"Sum number : {sum(num_data)}") # square of natural number squares = [] for value in range(1, 11): # square = value ** 2 # squares.append(square) squares.append(value ** 2) print(squares) # List Comprehensions N_squares = [ value ** 2 for value in range(1, 11) ] print(f"List comprehension n_squares value: {N_squares}")
true
0018c596b94baba6e32cf96beed45ce6c2e28a2b
cseai/python-crash-course
/lecture-07/prompts.py
781
4.3125
4
# How the input() Function Works # Writing Clear Prompts # message = input("Tell something, and I will repeat it back: ") # print(message) # name = input("Please enter your name: ") # print(f"Hello, {name}") # prompt = "If you tell me your name, we can personalize your message." # prompt += "\nWhat is your name? " # prompt = prompt + "\nWhat is your name? " # name = input(prompt) # print(f"Hello, {name}") # Using int() to Accept Numerical Input # age = input("Tell me your age: ") # age = int(age) # if age >= 18: # print("U r allowed") # print(type(age)) # The Modulo Operator number = input("Enter a number: ") number = int(number) if number % 2 == 0 : print(f"The number {number} is even.") else: print(f"The number {number} is odd.") print(number % 2)
true
8ed6977c3a24c98dc4d7802f4ec704eefa3cba49
Muntaha-Islam0019/Hello-World
/Codes/Challenges/Challenge_9.py
947
4.1875
4
# You'll have a car. The user can tell you to start, stop and quit the # program. Help keyword will help user to understand the commands. key = '' print("Enter 'help' for help.") isStarted = False while True: key = input("Your Command: ") if key == 'help': print(''' Commands: start - starts the car 🚗, stop - stops the car 🚧, quit - quits the game 👋🏻. Enjoy! ''') elif key == 'start' and not isStarted: isStarted = True print('Car started! 🚗') elif key == 'start' and isStarted: print('Car already started.') elif key == 'stop' and isStarted: isStarted = False print('Car stopped! 🚧') elif key == 'stop' and not isStarted: print("Car isn't moving.") elif key == 'quit': break else: print("Hey, I don't understand what you're saying 😥") isStarted = False print('Game closed. 👋🏻')
true
0f149c7fc18468d27df2b0ac1b40ff5d290deeda
Muntaha-Islam0019/Hello-World
/Codes/23 - Truthy-Falsy.py
629
4.21875
4
a = 0 b = 1 c = 5 if a: print(f'ALright, it is {a}') else: print('Ehhe') if b: print(f'ALright, it is {b}') else: print('Ehhe') if c: print(f'Alrigth, it is {c}') else: print('Ehhe') # Now, Values that evaluate to False are considered Falsy. # And, Values that evaluate to True are considered Truthy. # Like, 0, "", () refers to false. # But, 1, any value, refers to true. # Likewise, look at this code: def print_even(data): if len(data) > 0: for value in data: if value % 2 == 0: print(value) else: print("The argument cannot be empty") # This can be shortened to: 'if data:'
true
db0155090e185774ec51d55e788b91e5766ff4e2
Muntaha-Islam0019/Hello-World
/Codes/Challenges/Challenge_7.py
401
4.5625
5
# Enhanced weight converter what takes any unit # (pounds or kgs) and converts to the opposite one. weight = input("Please enter your weight: ") unit = input("What is it's unit? ") if unit.lower() == 'kg' or unit.lower() == 'k' or unit.lower() == 'kgs': print(f"Your weight is {round(float(weight) * 2.205, 3)} pounds.") else: print(f"Your weight is {round(float(weight) / 2.205, 3)} KGs.")
true
43e8126ca50020fc4b301f6a620cc0b050a97321
goga-nakagawa/leetcode
/python/376_WiggleSsubsequence.py
1,935
4.1875
4
""" A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. """ from itertools import izip class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ wiggle_l = 0 max_l = 0 flg = None start = 0 for curr, next in izip(nums, nums[1:]): dif = curr - next start += 1 if dif == 0: continue else: flg = dif > 0 wiggle_l = 2 max_l = 2 break for curr, next in izip(nums[start:], nums[start+1:]): dif = curr - next if dif == 0: continue elif (dif > 0) ^ flg: wiggle_l += 1 max_l = max([wiggle_l, max_l]) flg = not flg else: wiggle_l = 2 return max_l s = Solution() print s.wiggleMaxLength([1,7,4,9,2,5]) print s.wiggleMaxLength([1,7,4,5,5]) print s.wiggleMaxLength([1,17,5,10,13,15,10,5,16,8]) print s.wiggleMaxLength([1,2,3,4,5,6,7,8,9])
true
e93db100e5f20a3bc094712b63d55b592759774f
SebastianoFazzino/Fundamentals-of-Computing-Specialization
/Principles of Computing/2048 Game Project_part1.py
1,166
4.40625
4
'''This function reproduces a simple version of the game 2048''' def merge(number_list): """This function takes a list as input, if two consecutive numbers are the same, we add those two numbers At the end we'll have a modified list that has the same length as the original one""" # we start creating a new list that contains all numbers passed in number_list, as long as they're not zero result = [element for element in number_list if element != 0] # using some logic, if a number in result is equal to its previos number, we add those two numbers for element in range(0, len(result) - 1): if result[element] == result[element + 1]: result[element] *= 2 result[element + 1] = 0 # we modify result so that it contains only numbers different from zero result = [element for element in result if element != 0] # to finish, we add as many zeros as needed to result, so that its length is the same as the original number_list while len(result) < len(number_list): result.append(0) # we return result return result
true
0cbec61c1e5548ea9488e27153876ea3a17c61f0
wanckit/pythontestprojects
/program_16.py
216
4.21875
4
def factorial(num): result = 1 for x in range (1, num+1): result = result*x return result in_variable = input ("Enter a number to calulate the factorial of") print factorial(in_variable)
true
d3f040a569702f1db149d799bd23746457f58cb4
AnaBenn/Practice
/Python/RMOTR/week_1_challenges.py
2,822
4.1875
4
#if list is greater than 3 it returns True def more_than_3_elements(a_list): if len(a_list) > 3: return(True) else: return(False) #if variable is a str it returns True def is_string(variable): if type(variable) == str: return(True) elif type(variable) != str: return(False) #that receives two numbers and returns the sum of them ONLY if #they’re both integers def add_only_integers(a, b): if (type(a) == int and type(b) == int): return (a + b) else: return("invalid parameters") #receives a number and returns True if it is greater than 10 OR less than #0 and False otherwise. def check_out_of_boundaries(number): if number > 10 or number < 0: return(True) else: return(False) #Define a function traffic_light that receives a color and returns: #'stop' if the color is red #'slow down' if the color is yellow #'go' if the color is green def traffic_light(color): if color == 'red': return('stop') elif color == 'yellow': return('slow down') elif color == 'green': return('go') #Define a function color_mixer that receives two colors color1 and color2 #and returns the color resulting from mixing them in EITHER ORDER. #The colors received are either red, blue, or yellow and you should return: #Magenta if the colors mixed are red and blue #Green if the colors mixed are blue and yellow #Orange if the colors mixed are yellow and red def color_mixer(color1, color2): if (color1 == 'red' and color2 == 'blue') or (color1 == 'blue' and color2 == 'red'): return('Magenta') elif (color1 == 'blue' and color2 == 'yellow') or (color1 == 'yellow' and color2 == 'blue'): return('Green') elif (color1 == 'yellow' and color2 == 'red') or (color1 == 'red' and color2 == 'yellow'): return('Orange') #Define a function get_grade_letter that receives a score and you should return: #'A' if the score is 90 or above #'B' if the score is 80 to 89 #'C' if the score is 70 to 79 #'D' if the score is 60 to 69 #'F' if the score is less than 60 def get_grade_letter(score): if score >= 90: return('A') elif score >= 80: return('B') elif score >= 70: return('C') elif score >= 60: return('D') elif score < 60: return('F') #Define a function powers_of_two that receives a power and uses a for loop #to calculate and return 2 to that power. Do not use the math.pow or or the x**y #operator for this assignment. def powers_of_two(power): raised = 1 for _ in range(power): raised *= 2 return raised #Define a function sum_of_numbers_in_list that receives a list of #numbers a_list of an unknown length and calculates the sum of those #numbers using a for loop. Do not use the sum function. def sum_of_numbers_in_list(a_list): sum = 0 for i in a_list: sum = sum + i return sum
true
78b32fef6f97f98c71673e74fcdc22eb866b8752
xiaofuz/xiaojiayu
/Python/0--(练习)字典编写通讯录程序.py
2,450
4.15625
4
print('|--- 欢迎进入通讯录程序 ---|') print('|--- 1:查询联系人资料 ---|') print('|--- 2:插入新的联系人 ---|') print('|--- 3:删除已有联系人 ---|') print('|--- 4:退出通讯录程序 ---|') inpute = 0 data1 = {} while inpute != 4: #inpute 输入的相关指令代码放里面的原因是,下面的输入错了,可以返回到这个循环,再重新输入指令 inpute = int(input('请输入相关的指令代码:')) if inpute < 0 or inpute >=5: #查询联系人资料 print('输入错误,请重新输入') continue if inpute == 1: name = input('请输入联系人姓名:') if name in data1.keys(): print(data1[name]) continue else: print('未查找到此联系人,请插入新的联系人') continue if inpute == 2: #插入新的联系人 name = str(input('请输入联系人姓名:')) if name in data1: print('您输入的姓名在通讯录中已存在 -->> %s:%d'% (name,data1[name])) whether = input('是否修改用户资料(YES/NO):') if whether == 'YES': data1[name] = int(input('请输入联系电话:')) print('联系人:%s --联系电话:%d 更新成功' % (name,data1[name])) elif whether == 'NO': print('通讯录未修改') else: telephone = int(input('请输入用户联系电话:')) data1[name] = telephone print('添加联系人:%s --联系电话:%d 成功' % (name,telephone)) #删除已有的联系人 elif inpute == 3: name = input('请输入联系人姓名:') if name in data1.keys(): whether = input('确定删除:YES/NO:') if whether == 'YES': del data1[name] print('删除成功') elif whether == 'NO': print('联系人未删除……返回中…………') else: print('输入错误,请重新输入:') continue else: print('未查到该联系人……') #退出通讯录程序 else: print('|--- 感谢使用通讯录程序 ---|') inpute = 4
false
a3b13a8ee47b54ecc9e0d14e86357d4f548d3eef
sojojo/PyPractice
/LearnPythonTheHardWay/ex40.py
923
4.1875
4
#Exercise 40 - Modules, Classes, And Objects #Modules, classes, and objects -> 3 types of key value type storage #Using classes and object oriented practice class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line #split up and concatenate a string by putting into an array happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song(["They rally around the family", "With pockets full of shells"]) #EC - make a string to pass to song instead with a new song coconut_song = [""" I've got a lovely bunch of coconuts. Doodelee doo. here they are a standing in a row. Two, Three, Four. Big ones small ones, some as big as your head. """] Song(coconut_song).sing_me_a_song() happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
true
3b77fed5a63e957b090bdc4f871f350c8db0ecfb
sanderbruynoghe/CB
/venv/Smappee_Database/SQLite_Database_Example.py
1,853
4.4375
4
# SQLite_Database.py import sqlite3 # Step 1: create 'connection object' representing the database: conn = sqlite3.connect('example.db') #Do the same for accessing the database later on # Step 2: create Cursor object to be able to perform SQL commands on the database: c = conn.cursor() # Step 3: adding data to the database: # Create table #c.execute('''CREATE TABLE stocks # (date text, trans text, symbol text, qty real, price real)''') # Insert a row of data #c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") # Always have to save (commit) the changes #conn.commit() # Step 4: querying the database: # Put the query in an execute statement # fetchall() returns a list [] of tuples (rows) a = c.execute("SELECT * FROM stocks WHERE symbol = 'RHAT'").fetchall() #Use "" (double) so you can use '' (single) in query # To use variables from Python in the query, use ? as placeholder # and provide tuple as second argument to placeholder: symbol = ('RHAT',) #Tuple with only one value here print(c.execute('SELECT * FROM stocks WHERE symbol=?', symbol).fetchall()) # Step 5: inserting multiple rows at once: c.executemany: purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] #c.executemany("INSERT INTO stocks VALUES (?,?,?,?,?)", purchases) #Executemany takes list of tuples as second argument #conn.commit() #Don't forget commit! try: # Deal with last part of the data: general data without publishIndex publish_index = sensor['publishIndex'] except: publish_index = 17 # Last element on the device list is the 'general element' # Step 5: close the connection (changes are lost if not commited before closing) #conn.close()
true
37754ed470fff7ddfb74e1313ae60f7cd883a290
ExpressoJava/Data-Structures-Algorithms-Python
/Algorithms/selectionSort.py
1,951
4.25
4
""" Selection Sort: Is about picking/selecting the smallest element from the list and placing it in the sorted portion of the list. Initially, the first element is considered the minimum and compared with other elements. During these comparisions, if a smaller element is found then that is considered the new minimum. After completion of one full round, the smallest element found is swapped with the first element. this process continues till all the elements are sorted. Algorithm: 1. consider the first element to be sorted and the rest to be unsorted 2. Assume the first element to be the smallest element 3. Check if the first element is the smaller than each of the other elements: 1. if yes, do nothing 2. if no, choose the other smaller element as min and repeat step 3. 4. After completion of one iteration through the list, swap the smallest element with the first element of the list 5. Now consider the second element in the list to be the smallest and so on till all elements in the list are covered. """ # def selectionSort(alist): # for i in range(len(alist)): # # Find the minimum element in the remaining # minPosition = i # for j in range(i+1, len(alist)): # if alist[minPosition] > alist[j]: # minPosition = j # # Swap the found minimum element with minPosition # temp = alist[i] # alist[i] = alist[minPosition] # alist[minPosition] = temp # return alist # print(selectionSort([5, 2, 1, 9, 0, 4, 6])) # 0, 1, 2, 4, 5, 6, 9 # Another implementation array = [1, 45, 10, 35, 100, 13, 147, 600, 80] def selectionSort(array): size = len(array) for i in range(0, size): for j in range(i+1, size): if array[j] < array[i]: min = array[j] array[j] = array[i] array[i] = min print(array) # 1, 10, 13, 35, 45, 80, 100, 147, 600
true
5c076244757878ea80cf974b40adc3ea2c21de7f
tishacodes/Algorithms
/rock_paper_scissors/rps.py
1,217
4.3125
4
#!/usr/bin/python """ Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}. """ import sys from itertools import permutations def rock_paper_scissors(n): game = [] if n == 0: return [[]] if n == 1: return [['rock'], ['paper'], ['scissors']] if n == 2: return [['rock', 'rock'], ['rock', 'paper'], ['rock', 'scissors'], ['paper', 'rock'], ['paper', 'paper'], ['paper', 'scissors'], ['scissors', 'rock'], ['scissors', 'paper'], ['scissors', 'scissors']] else: for possibilities in rock_paper_scissors(n - 1): game.append(possibilities + ["rock"]) game.append(possibilities + ["paper"]) game.append(possibilities + ["scissors"]) return game if __name__ == "__main__": if len(sys.argv) > 1: num_plays = int(sys.argv[1]) print(rock_paper_scissors(num_plays)) else: print('Usage: rps.py [num_plays]')
true
a744ddb6515acc6c27a7142a5afcc583425e86a2
stella-pliatsiou/python
/python1/Introduction to Data Science in Python/Week1/python_functions.py
780
4.3125
4
# This function should add the two values if the value of the "kind" parameter is "add" # or is not passed in, otherwise it should subtract the second value from the first. # Can you fix the function so that it works? # def do_math(?, ?, ?): # if (kind=='add'): # return a+b # else: # return a-b # do_math(1, 2) def do_math(a, b, kind='add'): if (kind=='add'): return a+b else: return a-b do_math(1, 2) #------------------------------------------------------------------------------------- # Question 2 # Here's our first bit of interaction, why don't you try and change this function to # accept three parameters instead of two and return the sum of all three. def add_numbers(x, y, z): return x+y+z print(add_numbers(1, 2, 3))
true
3eaa904e738f5d2b469d97c409ce6f78dd2f6851
preethi101/Python-Programming-Tasks
/MyCaptain Task 6.py
507
4.34375
4
#Task 6 To determine whether a given triangle is equilateral, isosceles or scalene side1=int(input('Enter the length of the first side of your triangle')) side2=int(input('Enter the length of the second side of your triangle')) side3=int(input('Enter the length of the third side of your triangle')) if((side1==side2) and (side2==side3)): print('Equilateral Triangle') elif((side1==side2)or(side2==side3)or(side3==side1)): print('Isosceles Triangle') else: print('Scalene Triangle')
true
5824b70f5917ad695c8d33cbdf01f4830924c659
JLionPerez/cs325
/week1/mergeTime.py
2,009
4.21875
4
# Title: HW 1 - Merge Sort # Description: Sorts through arrays in a file and output results into a new file. # Author: Joelle Perez # Date: 15 January 2020 import numpy as np import time # Function name: mergSort() # Purpose: Sort a passed array using an merge sort. # Arguments: integer array # Returns: none # Citation: https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheMergeSort.html def mergSort(arr): arrLen = len(arr) i, j, k = 0, 0, 0 if arrLen > 1: m = arrLen // 2 #divide in half lHalf = arr[:m] #sub-list of arr from the middle index to the very left index rHalf = arr[m:] #sub-list of arr from the middle index to the very right index mergSort(lHalf) #sort the left side mergSort(rHalf) #sort the right side while i < len(lHalf) and j < len(rHalf): if lHalf[i] < rHalf[j]: arr[k] = lHalf[i] #main arr filled from least to greatest i += 1 else: arr[k] = rHalf[j] j += 1 k += 1 #move to next index in main array while i < len(lHalf): arr[k] = lHalf[i] #adds in left sublist to main array i += 1 k += 1 while j < len(rHalf): arr[k] = rHalf[j] #adds in right sublist to main array j += 1 k += 1 # Function name: main() # Purpose: Runs all of the functions and the main parts of the program, such as randomizings arrays. # Arguments: none # Returns: none # Citation: http://www.learningaboutelectronics.com/Articles/How-to-create-an-array-of-random-integers-in-Python-with-numpy.php def main(): n = 20000 #harcoded size, must change to get tests randArr = np.random.randint(0, 10000, n) mergSort(randArr) print("Size of array is %s." % n) # Runs the main function if __name__ == "__main__": startTime = time.time() main() print("Time is %s seconds." % (time.time() - startTime))
true
35e25ec31879c74035fe0fcc95074135f0729d33
billyateallcookies/python
/Insertionsort/insertionsort.py
433
4.25
4
""" Basic Insertionsort program. """ def insertion_sort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move element of arr[0...i-1], that are greater than key, # to one position ahead of their current position j = i - 1 while j >= 00 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr
true
f759697178e2d6e93e002534abe7a4f9972a50dc
borgr/intro2cs
/ex8/sllist.py
1,898
4.40625
4
class Node: """ This class represents the Node of the List. The Node contains the data and points to next element (Node). """ def __init__(self, data, next=None): """ Constructor for Node. data - The data the Node holds next - The next Node in the list """ self.data = data self.next = next def get_next(self): """ Returns the Node this Node is pointing to. """ return self.next def get_data(self): """ Returns the data of this Node. """ return self.data def set_next(self,next): """ Sets the Node that will follow this Node to the one given in the parameter. next - the Node that will now follow this Node """ self.next = next class List: """ This class represents a single-linked list. The only data member the class contains is the head of the list. """ def __init__(self): """ Constructs an empty list. """ self.head = None def add_first(self,data): """ Adds a data item to the beginning of the list. """ self.head = Node(data, self.head) def remove_first(self): """ Removes the first node from the list and return its data or null if the list is empty. """ if (self.head is None): return None res = self.head.data self.head = self.head.next return res class SkipiNode: """ This class represents a Node for SkipiList. The SkipiNode contains the data, points to next element (Node) and to a node that is previous to its previous node. """ def __init__(self, data, next=None, skip_back=None): self.data = data self.next = next self.skip_back = skip_back
true
2ce0210217c9082a9945eb10024e6c54bd8333e6
ankurg0806/Python
/MinimumDiffPairInTwoList.py
1,995
4.3125
4
# Write a function that takes in two non-empty arrays of integers. The function should find the pair of numbers (one from the first array, one from the second array) whose absolute difference is closest to zero. The function should return an array containing these two numbers, with the number from the first array in the first position. Assume that there will only be one pair of numbers with the smallest difference. # Instead of generating all possible pairs of numbers, try somehow only looking at pairs that you know could actually have the smallest difference. How can you accomplish this? # Would it help if the two arrays were sorted? If the arrays were sorted and you were looking at a given pair of numbers, could you efficiently find the next pair of numbers to look at? What are the runtime implications of sorting the arrays? # Start by sorting both arrays, as per Hint #2. Put a pointer at the beginning of both arrays and evaluate the absolute difference of the pointer-numbers. If the difference is equal to zero, then you've found the closest pair; otherwise, increment the pointer of the smaller of the two numbers to find a potentially better pair. Continue until you get a pair with a difference of zero or until one of the pointers gets out of range of its array. # Sample input: [-1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17] def smallestDifference(arrayOne, arrayTwo): # Write your code here. arrayOne.sort() arrayTwo.sort() smallest = float("inf") i = 0 j = 0 smallestpair = [] while i < len(arrayOne) and j < len(arrayTwo): if arrayOne[i] < arrayTwo[j]: current = arrayTwo[j] - arrayOne[i] if (current < smallest): smallest = current smallestPair = [arrayOne[i],arrayTwo[j]] i += 1 elif arrayOne[i] > arrayTwo[j]: current = arrayOne[i] - arrayTwo[j] if (current < smallest): smallest = current smallestPair = [arrayOne[i],arrayTwo[j]] j += 1 else: return [arrayOne[i],arrayTwo[j]] return smallestPair
true
de819be03e78021de120dfc0098426ec721c787b
ankurg0806/Python
/DynamicProgramming/LongestCommonSubsequence.py
1,730
4.125
4
# # Longest Common Subsequence # Implement a function that returns the longest subsequence common to two given strings. A subsequence is defined as a group of characters that appear sequentially, with no importance given to their actual position in a string. In other words, characters do not need to appear consecutively in order to form a subsequence. Assume that there will only be one longest common subsequence. # Sample input: "ZXVVYZW", "XKYKZPW" # Sample output: ["X", "Y", "Z", "W"] # Using tabulation method the table will look like this # 0 1 2 3 4 5 6 7 # X K Y K Z P W # 0 [['', '', '', '', '', '', '', ''], # 1 Z ['', '', '', '', '', 'Z', 'Z', 'Z'], # 2 X ['', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], # 3 V ['', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], # 4 V ['', 'X', 'X', 'X', 'X', 'X', 'X', 'X'], # 5 Y ['', 'X', 'X', 'XY', 'XY', 'XY', 'XY', 'XY'], # 6 Z ['', 'X', 'X', 'XY', 'XY', 'XYZ', 'XYZ', 'XYZ'], # 7 W ['', 'X', 'X', 'XY', 'XY', 'XYZ', 'XYZ', 'XYZW']] # this is a typical dynamic programming problem that can be solved with top down (recursive) approach and bottom up(tabulation approach) def longestCommonSubsequence(str1, str2): mat = [['' for x in range(len(str2)+1)] for y in range(len(str1)+1)] for x in range(0,len(str1)): for y in range(0,len(str2)): if str1[x] == str2[y]: mat[x+1][y+1] = mat[x][y] + str1[x] else: mat[x+1][y+1] = max(mat[x+1][y],mat[x][y+1], key = len) return [x for x in mat[len(str1)][len(str2)]] print(longestCommonSubsequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "CCCDDEGDHAGKGLWAJWKJAWGKGWJAKLGGWAFWLFFWAGJWKAGTUV")) Time Complexity = Space Complexity = O(m*n)
true
a1751dff07706f84264b37c07dcb2b1a5fdc1a3b
ankur8/python
/learning/tuple.py
1,561
4.46875
4
t=(1,2,3,4) t1=1, print(t1) print(t) ################ #nested tuple and mutuable nested element can be reassigned t3=('mouse',[1,2,3],('cat','boll')) #t3[0]=9 # gives error as tuple can not be reassigned t3[1][0]=8 # no error as nested list in tuple can be change #3[2][0]=100 #nested tuple can not be reassigned print(t3) # but item of mutable element can be changed #################### my_tuple = 3, 4.6, "dog" print(my_tuple) # tuple unpacking is also possible # Output: # 3 # 4.6 # dog a, b, c = my_tuple print(a) print(b) print(c) my_tuple = ("hello",) print(type(my_tuple)) #type tell you type of class object # parentheses is optional # Output: <class 'tuple'> my_tuple = "hello", print(type(my_tuple)) #########slicing ##### my_tuple = ('p','r','o','g','r','a','m','i','z') # elements 2nd to 4th # Output: ('r', 'o', 'g') print(my_tuple[1:4]) # elements beginning to end # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple[:]) #########We can also assign a tuple to different values (reassignment). my_tuple = ('p','r','o','g','r','a','m') #### addition or concatination print((1, 2, 3) + (4, 5, 6)) # Output: ('Repeat', 'Repeat', 'Repeat') print(("Repeat",) * 3) #But deleting a tuple entirely is possible using the keyword del. del my_tuple #print(my_tuple) ######## my_tuple = ('a','p','p','l','e',) # Count # Output: 2 print(my_tuple.count('p')) # Index # Output: 3 print(my_tuple.index('l')) print('a' in my_tuple) ############# iteration for name in ('John','Kate'): print("Hello",name)
true
e2a2214a11e9e5e82afe1f33a388e7086c271258
CarolineVantiem/CMSC-201-HW
/hw5/hw5_part3.py
1,812
4.375
4
# File: hw5_part3.py # Author: Caroline Vantiem # Date: 10/10/2017 # Section: 3 # E-mail: Cvantie1@umbc.edu # Description: Checks the punctuation and capitilization of a sentence. ############################################################################# # checkCapital() Checks to see if the sentence starts with a capital letter # # Input: aSent; the sentence the user enter # # Output: Whether or not the sentence begins with a capital letter # ############################################################################# def checkCapital(aSent): #Checks the first INDEX of the word firstSent = aSent[0:1] if firstSent != firstSent.upper(): print("WRONG - Sentences start with a capital letter.") elif firstSent == firstSent.upper(): print("Correct capitalization!") #################################################################### # checkPunctuation() Checks to see if the sentence has punctuation # # Input: aSent; to checkfor punctuation # # Output: Whether or not the sentence has punctuation # #################################################################### def checkPunctuation(aSent): #Checks the last INDEX of the word lastSent = aSent[len(aSent) - 1] if lastSent != "." and lastSent != "!" and lastSent != "?": print("WRONG - Sentences use punctuation.") elif lastSent == "." or lastSent == "!" or lastSent == "?": print("Correct punctuation!") END = "" def main(): aSent = input("Enter a sentence (Enter nothing to quit): ") #Prompts the user to keep entering until nothing is entered while aSent != END: checkCapital(aSent) checkPunctuation(aSent) aSent = input("Enter a sentence (Enter nothing to quit): ") main()
true
b83e5e10614196664f1dbfc3ba37839cc4387dec
CarolineVantiem/CMSC-201-HW
/hw6/hw6_part2.py
1,161
4.65625
5
# File: hw6_part2.py # Author: Caroline Vantiem # Date: 11/15/2017 # Section: 3 # E-mail: cvantie1@umbc.edu # Description: generates a triangle based # on the users input #################################################### # recurTri() takes in the height and char and # # returns the right triangle # # Input: height; height of the triangle # # char; the user inputs symbol # # Output: None (the function keeps printing out # # lines of the triangle) # #################################################### def recurTri(char, height): # BASE CASES # if height == 0: print() elif height == 1: # when the height is maxed / 1 # print(char * height) # RECURSIVE CALL # elif height > 1: recurTri(char, height - 1) # recursive call # print(char * height) # print triangle # ####################### def main(): # user input # height = int(input("Please enter the height of the triangle: ")) char = str(input("Please enter the symbol to use: ")) recurTri(char, height) # run recursive function # main()
true
b07ecdca498c5b865bcef6c3deb46718ce2cfc25
CarolineVantiem/CMSC-201-HW
/hw6/hw6_part1.py
1,090
4.46875
4
# File: hw6_part1.py # Author: Caroline Vantiem # Date: 11/14/2017 # Section: 3 # E-mail: cvantie1@umbc.edu # Description: Calculates the summation of a number # stopping at a second number. ###################################################### # summation() calculates the summation of the number # # Input: numOne; number to sum from # # numTwo; number to sum to # # Output: None (numbers are summed) # ###################################################### def summation(numOne, numTwo): # BASE CASES # if numOne == numTwo - 1: return 0 # return final value # # RECURSIVE CALL # else: return numOne + summation(numOne - 1, numTwo) # summation of numbers # ######################## def main(): # user input # numOne = int(input("Please input the number you want to sum from: ")) numTwo = int(input("Please input the number you want to sum down to: ")) # print summation # print("The summation from", numOne, "to", numTwo, "is", summation(numOne, numTwo)) main()
true
2f0f3a11fb02f8c74a517eb0ee83aa4f9466cc72
CarolineVantiem/CMSC-201-HW
/hw2/hw2_part1.py
833
4.25
4
# File: hw2_part1.py # Author: Caroline Vantiem # Date: 9/18/2017 # Section: 3 # E-mail: cvantie1@umbc.edu # Description: Asks the user how many days they had left on # their design and project. Outputs a designated # answer depending on the input. def main(): print("Project 1 has just come out, and you have 6 days to complete the design and 13 days to complete the project") startDesign = int(input("Days left when you start the design: ")) startProject = int(input("Days let when you start the project: ")) if startDesign == 0 or startProject == 0: print("Why would you wait so long?! :( ") elif startDesign >= 6 and startProject >= 10: print("Wow, you started really early! Great job! :)") else: print("Good luck on the project! You can do it!") main()
true
daa745dda0bb75bf6d4994d8ee32bd30da366451
muremwa/Python-Pyramids
/inverted_triangle.py
281
4.15625
4
""" Triangle in the following manner ******** ******* ****** ***** **** *** ** * """ def inverted_right(num_rows): num_rows += 1 for i in range(1, num_rows): line = "*"*(num_rows-i) print(line) rows = int(input("How many rows?: ")) inverted_right(rows)
false
cec091fd1504e6362afe03dfd4f4c944c62097d1
mfsalama/Homework
/drift.py
2,073
4.34375
4
# coding: utf-8 # # Part 3: # In[1]: #We start by importing scipy , which we will use to draw random numbers,and we write the first function, generating a population import scipy # for random numbers def build_population(N, p): """The population consists of N individuals. Each individual has two chromosomes, containing allele "A" or "a", with probability p and 1-p, respectively. The population is a list of tuples. """ population = [] for i in range(N): allele1 = "A" if scipy.random.rand() > p: allele1 = "a" allele2 = "A" if scipy.random.rand() > p: allele2 = "a" population.append((allele1, allele2)) return population # In[2]: #build_population(10, 0.7) # In[3]: #Now we write the second function, which is used to produce a genotype count for the population: def compute_frequencies(population): """ Count the genotypes. Returns a dictionary with counts for each genotype. """ AA = population.count(( 'A', 'A')) Aa = population.count(('A', 'a')) aA = population.count(('a', 'A')) aa = population.count(('a', 'a')) return({'AA': AA, 'aa': aa, 'Aa': Aa, 'aA': aA}) # In[4]: #my_pop = build_population(6, 0.5) #my_pop #compute_frequencies(my_pop) # In[5]: def reproduce_population(population): """ Create a new generation through sexual reproduction For each of N new offspring: - Choose the parents at random - The offspring receives a chromosomes from each of the parents """ new_generation = [] N = len(population) for i in range(N): dad = scipy.random.randint(N) # random integerbetween 0 and N-1 mom = scipy.random.randint(N) chr_mom = scipy.random.randint(2) # which chromosome comes from mom offspring = (population[mom][chr_mom], population[ dad][1 - chr_mom]) new_generation.append(offspring) return(new_generation) # In[ ]: #reproduce_population(my_pop)
true
40fa1f2dd13fd381b180b7e3c83a92ef62e1bcca
rjcahalan/5578_RJC
/Code_it_Wk2.py
686
4.125
4
## Code It- Week 2 ## Enter a user input and count the characters if input is a string uput = input('Enter input: ') if isinstance(uput, str) == True: print 'string' elif isinstance(uput, int) == True: print 'integer' elif isinstance(uput, float) == True: print 'float' else: print 'not sure what it is' ulist = [] udic = dict() ## counts the letters in a string by adding to a dictionary if isinstance(uput, str) == True: for l in uput: if l not in udic: ##adds the letter to the dictionary if it is not already there udic[l] = 1 else: udic[l] = udic[l] + 1 print udic print "*" * len(uput) print uput print "*" * len(uput)
true
db1e11d63c75cb2651a5fb8a3b7689ee4a0ed100
asedimbi/LearningPythonTheHardWay
/ex33.py
345
4.125
4
#While loops i = 0 numbers = [] while i<6: print(f"At the top i is {i}") numbers.append(i) i = i+1 print("Numbers are now: ", numbers) print(f"At the bottom i is {i}") print("The numbers: ") for num in numbers: print(num) def looper(start, end, inc): return list(range(start, end, inc)) print(looper(5,15,2))
true
c250e4f485b7fce21a029b284b13c8b137f81aea
h10gforks/corePythonProgramming
/c3/readTextFile.py
295
4.125
4
#coding:utf-8 import os #get filename fname = raw_input('Enter filename:') print #attempt to open file for reading if os.path.exists(fname): fobj = open(fname,'r') for eachLine in fobj: print eachLine.strip() fobj.close() else: print "***file open error:No Such File."
true
1cc7909e6af28c1f7216ec698041472728b5738d
Gprinziv/Projects
/Python/Numbers/findDigits.py
626
4.5
4
""" A series of practice problems for Python involving numbers and math. by Giovanni Prinzivalli """ import math from numHelp import get_int_in_range def find_float_digits(float, n): """Returns a float to the nth digit as specified by the caller""" return '{:.{width}f}'.format(float, width=n) if __name__ == "__main__": n = get_int_in_range("Select the digits (max 50) of Pi and e you want to find -> ") #Exercises 1 and 2: Finding pi/e to the nth digit. print "Pi to " + n + " digits:" print find_float_digits(math.pi, n) + "\n" print "e to " + n + " digits:" print find_float_digits(math.e, n) + "\n"
true
7f5f9d1dc25f27a132fd012a4eceb064fd6ab832
FernandoVidal1/Sistema
/script.py
1,785
4.1875
4
usuarios = [] def intercaoInicial(): print("\nQual processo vc deseja fazer: \n") print("[1] - Cadastrar usuario") print("[2] - Exibir usuario") print("[3] - Remover usuario") print("[4] - Editar usuario por e-mail") print("[5] - Sair\n") return int(input()) def inputsCadastroUsuario(): print("\n\nCadastro de usuario") print("Digite o nome desejado: \n") nome = input() print("Digite o e-mail desejado: \n") email = input() print("Digite a senha desejado: \n") senha = input() return [nome, email, senha] def cadastro(id): dadosDoUsuario = inputsCadastroUsuario() usuarioModelo = { "id": id, "nome": "", "email": "", "senha": "" } usuarioModelo["nome"] = dadosDoUsuario[0] usuarioModelo["email"] = dadosDoUsuario[1] usuarioModelo["senha"] = dadosDoUsuario[2] usuarios.append(usuarioModelo) print("\n\nUSUARIO CADASTRO COM SUCESSO!!\n") def inputsLista(): print("\n\n\nVoce deseja listar usuarios usando qual filtro") print("[1] - Listar todos por ordem de criacao") print("[2] - Listar todos por ordem alfabetica") print("[3] - Listar apenas um usuario por nome") print("[4] - VOLTAR\n\n") return int(input()) def listar(): sair = False def main(): sair = False countId = 0 while(not(sair)): tarefaEscolhida = intercaoInicial() if (tarefaEscolhida == 1) : print("função de cadastro") if (tarefaEscolhida == 2) : print("função de cadastro") if (tarefaEscolhida == 3) : print("função de cadastro") if (tarefaEscolhida == 4) : print("função de cadastro") if (tarefaEscolhida == 5): print("\n\nVoce saiu do sistema!!\n\n") sair = True countId =+ 1 if __name__ == "__main__": main()
false
b869f201d5f1bf40290692e027263e1684ee398f
rishikeshanilmishra/python-programing-lab
/temo.py
284
4.375
4
x=int(input("Enter temperature:")) # take input from the user y=input("is it in celcius or fahrenhite") # ask for the unit of temperature if y is "celcius": f=(9*x/5)+32 # celcius to fahrenhite formula print(f) else: c=(5/9)*(x-32) # fahrenhite to celsius formula print(c)
true
0b25f8f38f9e9f9f35a6f4b5b446e7529190d045
kitsmart/pythonbooklet
/Chapter 6/Practice Exercise 6/6 If Palindrome.py
223
4.21875
4
print ("\nExercise 6\n") word = list(input("Input a word: ")) word2 = word word3 = word2.reverse() def is_palindrome(word): if word == word2: print("true") else: print("false") is_palindrome(word)
false
a1a6aa06454fe17269e1d03bfd3bdd3821e34251
LuiMagno/Aulas-e-Exemplos
/Aulas de Python/Objetos e estruturas de dados avançados/Strings avançadas.py
318
4.40625
4
s = 'hello world' print(s.capitalize()) # Transformando apenas a primeira letra em maiúscula print(s.upper) # Todas as letras maiúsculas print(s.lower) # Todas as letras minúsculas print(s.count('o')) # Contando quantas vezes a letra 'o' aparece print(s.find('o')) # Achando a primeira localização da letra 'o'
false