blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
33103fb8b53fb56435e21c014a1fea4cc3d648a3
rettka30/CUS1166_rettka30_Lab1
/playground.py
1,748
4.28125
4
print("Basic program: ") print("\nHello Word") # Display a message # Get user input and display a message. myname = input("What is your name: ") print("Hello " + str(myname)) # Alternative way to format a string print("Hello %s" % myname) print("Done Practicing The Basic Program") print("\nVariables: ") i = 120 print(f"\nVariable i has the value {i}") f = 1.6180339 print(f"Variable f has the value {f} and its type is {type(f)}") b = True print(f"Variable b has the value {b}") n = None print(f"Variable n has the value of {n}") # tuple c = (10,20,10) print(f" c[0] has the value {c[0]} and is of type: {type(c)}") # list l = ["Anna", "Tom", "John"] l = [10,20,30] print(f" l[0] has the value {l[0]} and is of type: {type(l)}") # Sets variables. s = set() s.add(1) s.add(4) s.add(6) print(s) # Dictionary grades = {"Tom" : "A", "Mark": "B-"} grades["Tom"] grades["Anna"] = "F" # Create an empty dictionary . mydictionary = dict() print("Done Practicing Variables") print("\nConditionals: ") x=10 if (x > 0): print("\nThe number x is positive") elif (x<0): print("\nThe number x is negative") else: print("\nThe number x is zero") print("Done Practicing Conditionals") print("\nLoops: ") for i in range(5): print(i) for i_idx, i_value in enumerate(range(2,10)): print(f"{i_idx} - {i_value}" ) print("Done Practicing Loops") print("\nFunctions: ") def is_even(x): if (x % 2) == 0: return True else: return False print("Done Practicing Functions") print("\nClasses: ") class Book: def __init__(self, title="Software Engineering", isbn=""): self.title = title self.isbn = isbn def printBook(self): print(self.title + ", " + self.isbn) print("Done Practicing Classes")
true
e24baf2bc6e4c75cabb9a650694c77a06cb409cf
nestorcolt/smartninja-july-2020
/project/lesson_004/lesson_004.py
2,086
4.65625
5
# List and dictionaries - data structures ############################################################################################## """ Resources: https://www.w3schools.com/python/python_ref_list.asp """ # Primitives data types some_num = 4 # integer (whole number) some_decimal = 3.14 # float (decimal number) some_str = "Hello, SmartNinja!" # string human = True # boolean (either True or False) # Arrays (Lists in Python) - Data structure some_list = [1, 34, 12, 17, 87] # print(some_list) another_list = ["tesla", "toyota", "nissan"] # print(another_list) mixed_list = [22, "elon", True, "SmartNinja", 3.14] # print(mixed_list) # Iterating over a list for item in mixed_list: # print(item) pass # Indexing element = mixed_list[4] # print(element) # negative indexing element = mixed_list[-5] # print(element) # slicing elements = mixed_list[0:-2] # print(elements) # list methods # append new_list = [] new_list.append(2) new_list.append(True) new_list.append(False) new_list.append("kaka") # print(new_list) # remove new_list.remove(True) # print(new_list) # pop pop_element = new_list.pop(0) # print(pop_element) # count counter = new_list.count(False) # print(counter) # -------------- # List length mixed_list = [22, "elon", True, "SmartNinja", 3.14] # print(len(mixed_list)) ############################################################################################## # Dictionaries box = {"height": 20, "width": 45, "length": 30, 2: "kaka"} # Referencing a element in a dictionary element = box["width"] # print(element) # get method element_1 = box.get("height", None) # exist element_2 = box.get("Heights", None) # no exist # print(element_1) # print(element_2) # dictionary keys keys = box.keys() # print(keys) # dictionary values values = box.values() # print(values) # dictionary items items = box.items() # print(items) # Iterating over a dictionary for key, value in box.items(): # print(key, value) pass ##############################################################################################
true
224ad99452a12881e5e51bafe17d37a74b003602
Henrysyh2000/Assignment2
/question1_merge.py
1,125
4.34375
4
def merge(I1, I2): """ takes two iterable objects and merges them alternately required runtime: O(len(I1) + len(I2)). :param I1: Iterable -- the first iterable object. Can be a string, tuple, etc :param I2: Iterable -- the second iterable object. Can be a string, tuple, etc :return: List -- alternately merged I1, I2 elements in a list. """ res = [] index = 0 while index < min(len(I1), len(I2)): res.append(I1[index]) res.append(I2[index]) index += 1 if len(I1) > len(I2): for i in range(index, len(I1)): res.append(I1[i]) elif len(I2) > len(I1): for i in range(index, len(I2)): res.append(I2[i]) return res ''' Note: To get autograded on gradescope, you program can't print anything. Thus, please comment out the main function call, if you are submitting for auto grading. def main(): print([i for i in merge("what",range(100,105))]) print([i for i in merge(range(5),range(100,101))]) print([i for i in merge(range(1),range(100,105))]) if __name__ == '__main__': main() '''
true
6702c7ad5f3b4b1f11f09bb0e402f835909d7c53
KoryHunter37/code-mastery
/python/leetcode/playground/built-in-functions/bin/bin.py
758
4.375
4
# bin(x) # Convert an integer number to a binary string prefixed with "0b". # The result is a valid Python expression. # This method is reversed by using int() if the "0b" has been removed. # Alternatives include format() and f-string, which do not contain "0b". # > 0b1010 # The binary representation of 10, with 0b in front. print(bin(10)) # > 1010 # The binary representation of 10 (format() method) print(format(10, 'b')) # > 1010 # The binary representation of 10 (f-string method) print(f"{10:b}") # > 10 # Reverses the binary transformation print(int(bin(10), 2)) # > 10 # Reverses the binary transformation (format() method) print(int(format(10, 'b'), 2)) # > 10 # Reverses the binary transformation (f-string method) print(int(f"{10:b}", 2))
true
cd0a7956774aec6af702ed12f3aa0cee380a121a
bss233/CS126-SI-Practice
/Week 3/Monday.py
2,002
4.25
4
#Converts a number less than or equal to 10, to a roman numeral #NOTE: You normally shouldn't manipulate your input, ie how I subtract from num, # but it saves some extra checking. There is most certainly a cleaner way to do # this function def romanNumeral(num): #define an empty string to add characters to result = '' #if num is 10, then the roman numeral is X if num == 10: result += 'X' num -= 10 #if the num is greater than or equal to 5, add V to the string then subtract # 5 so that we can just use our other 4 comparisons elif num >= 5: result += 'V' num -= 5 #as long as our num isn't 0, meaning it wasn't originally 5, we add more to # our return string if num > 0: #check if it's 1 if num == 1: result += 'I' #check if it's 2 elif num == 2: result += 'II' #check if it's 3 elif num == 3: result += 'III' #check if it's 4 else: result = 'I' + result #return out finished string return result #Returns true or false based on whether or not a given year is a leap year def isLeapYear(year): #set initial status so that we only use 1 return statement status = False #check if the year is divisible by 400 if year % 400 == 0: status = True #check if the year is divisible by 4 elif year % 4 == 0: #if the year is divisible by 4, make sure it isn't divisible by 100 if year % 100 != 0: status = True #return the status return status #Tests print(romanNumeral(10)) #should print X print(romanNumeral(4)) #should print IV print(romanNumeral(7)) #should print VII print(romanNumeral(5)) #should print V print(romanNumeral(9)) #should print IX print(isLeapYear(2006)) #should print False print(isLeapYear(2000)) #should print True print(isLeapYear(2016)) #should print True print(isLeapYear(2100)) #should print False
true
ca8ce04997f9d6fde7c2d45e0532bcf5e030693c
nishants17/Python3
/dictionaries.py
498
4.15625
4
friend_ages = {"Nish" : 10 , "Adam" : 10} print(friend_ages["Nish"]) friend_ages["Nish"] = 30 print(friend_ages["Nish"]) #Dictionaries have order kept in python 3.7 but cannot have duplicate keys friends = ({"name" : "Rolf SMith", "age" : 24}, {"name" : "John", "age": 33}) print(friends[0]["name"]) #Accessing first element in the tuple and then Accessing first key in the dictionary friend_ages = [("Rolf", 24), ("Adam",30)] friend_ages = dict(friend_ages) print(friend_ages)
true
15f5ca39b9bcab582fc777e42d4b38b997c82bb0
unixtech/python
/150_py/2_Area_box.py
308
4.5
4
# Enter the width & Length of a box. # The program should compute the area. Enter values as floating point numbers # Enter the units of measurement used. width = float(input("Enter the width: ")) length = float(input("Enter the length: ")) area = width*length print('Area is:\t', area, 'Centimeters')
true
1d3f7b5029c39a9389268e180900869a38459ead
adamabarrow/Python
/comparisonOperators/comparisonOutline.py
1,297
4.3125
4
''' This outline will help solidify concepts from the Comparison Operators lesson. Fill in this outline as the instructor goes through the lesson. ''' #1) Make two string variables. Compare them using the == operator and store #that comparison in a new variable. Then print the variable. a = "hi" b = "hello" c = (a == b) print(c) #2) Make two int variables. Compare them using the == operator and store #that comparison in a new variable. Then print the variable. d = 1 e = 1.0 f = (d == e) print(f) #3) Make two int variables. Compare them using the > operator and store #that comparison in a new variable. Then print the variable. g = 9 h = 3 i = (g > h) print(i) #4) Make two int variables. Compare them using the < operator and store #that comparison in a new variable. Then print the variable. j = 7 k = 7 l = (j < k) print(l) #5) Make two int variables. Compare them using the >= operator and store #that comparison in a new variable. Then print the variable. m = 8 n = 12 o = (m >= n) print(o) #6) Make two int variables. Compare them using the <= operator and store #that comparison in a new variable. Then print the variable. p = 5 q = 5 r = (p <= q) print(r) #7) Make a comparison with any operator, with one of the common SYNTAX errors. s = 3 t = 2 u = (s = t) print(u)
true
19c7fb4bb5b612ef584ea7faab4eb1117d08783c
oguzhanun/10_PythonProjects
/challange/repdigit.py
553
4.4375
4
# A repdigit is a positive number composed out of the same digit. # Create a function that takes an integer and returns whether it's a repdigit or not. # Examples # is_repdigit(66) ➞ True # is_repdigit(0) ➞ True # is_repdigit(-11) ➞ False # Notes # The number 0 should return True (even though it's not a positive number). # Check the Resources tab for more info on repdigits. def is_repdigit(num): if num < 0 : return False if len(set(str(num))) > 1: return False else : return True print(is_repdigit(1001))
true
93eaade2a4ba280220cc021ff2837b6534d5ee17
oguzhanun/10_PythonProjects
/challange/descending_order.py
584
4.15625
4
# Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. # Examples: # Input: 21445 Output: 54421 # Input: 145263 Output: 654321 # Input: 123456789 Output: 987654321 def descending_order(num) : #num = sorted(str(num),) number = list(str(num)) number.sort(reverse=True) result = "" for i in number : result= result + i return int(result) print(-5/2) print(descending_order(2019384668362))
true
89df322925cb3bd2cdad24105a4350b963f12c4a
fatemizuki/good-good-study-day-day-up
/python基础/basic/1-2.py
1,990
4.5
4
# 1-2.06 交互式编程 # 在pycharm里底下的python console点下可以开启交互式编程 # 直接在底下输代码就行,比如输3-5 # pycharm关项目:close project # 1-2.07 注释 # #号表示单行注释 ''' 三个单引号/双引号中间是多行注释 快捷键:command + / ''' print('hello world') # 按住command点print会跳出来这个函数的用法和注释 # 1-2.09 数据类型 ''' 数字类型: int 整型 float 浮点型 complex 复数 字符串类型: 要求使用一对单引号或双引号包裹 布尔类型: 只有两个值:True False 列表类型: [ ] 字典类型: { A:B } 元组类型: ( ) 集合类型: { } ''' # 1-2.10 查看数据类型 a = 1 b = 'two' # 使用type函数 print(type(a)) # pycharm里写 type(a).print 然后回车或tab会变成 print(type(a)) # 我们所说变量的数据类型,其实是变量对应的值的数据类型 # 1-2.11 标识符的命名规则和规范 # 规则: # 1. 由数字,字母和下划线组成,不能以数字开头 # 2. 严格区分大小写 # 3. 不能使用关键字(在python里有特殊含义的单词) # 规范: # 1. 顾名思义 # 2. 遵守一定的命名规范 # 1. 小驼峰命名:第一个单词的首字母小写,以后每个单词的首字母都大写 # 2. 大驼峰命名:每个单词的首字母都大写(python里的类名使用这个) # 3. 使用下划线连接(python里的变量、函数和模块名用这个) # 1-2.12 print语句的使用 # print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) print('ju','zi') # 可以用逗号连接多个要打印的东西 print('ju','zi',sep = '+') # sep表示连接之间使用的东西,默认是空格,这里改成加号 # end表示末尾要怎么做,默认是换行 # file表示输出的地方,比如可以输出保存为文件 # 1-2.13 input语句的使用 # input("文本") # input输入保存的是字符串 password = input("password please:")
false
d6af6d9581328120bc0a9130650caba6bb9ea818
Ferihann/Encrypted-Chat
/rsa.py
1,843
4.15625
4
# This class make encryption using RSA algorithm import random large_prime = [] # Is array for storing the prime numbers then select into it randomly class Rsa: def generate_prime(self, lower, upper): # this function simply generate prime numbers for num in range(lower, upper+1): if num > 1: for i in range(2, num): if(num % i) == 0: break else: large_prime.append(num) def generate_public_and_private_key(self): # generates public and private keys q = random.choice(large_prime) p = random.choice(large_prime) n = p * q e = 2 z = (q - 1) * (p - 1) while e < z: # e is co-prime with toitient number , its gcd should equals 1 if self.gcd(e, z) == 1: break else: e += 1 w = 1 while((e*w) % z) != 1: # de = 1 modz w += 1 d = w # print("n is : ", n , " e is : ", e) return [(e, n), (d, n)] # public key (e,n) private key (d,n) def gcd(self, a, h): # Calculation of great common divisor temp = 0 while 1: temp = a % h if temp == 0: return h a = h h = temp def encrypt(self, public_key, plaintext): # Encrypt the plain text ciphertext = "" key, n = public_key for i in plaintext: c = (ord(i) ** key) % n ciphertext += chr(c) return ciphertext def decrypt(self, private_key, ciphertext): # Decrypt the plain text plaintext="" key, n = private_key for i in ciphertext: m = (ord(i) ** key) % n plaintext += (chr(m)) return plaintext
true
9cda8a2020ac38f5074f0be75666e825ca842856
skygarlics/GOF_designpattern
/builder.py
1,263
4.1875
4
import abc """ Example of string builder """ class Director: """ construct object using Builder interface """ def __init__(self): self._builder = None def construct(self, builder): self._builder = builder self._builder._build_part_a() self._builder._build_part_b() class Builder(metaclass=abc.ABCMeta): """ specify abstract interface for Product object """ def __init__(self): self.product = Product() def get_product(self): return self.product @abc.abstractmethod def _build_part_a(self): pass @abc.abstractmethod def _build_part_b(self): pass class Builder1(Builder): """ concrete builder """ def _build_part_a(self): self.product += "Part A\n" def _build_part_b(self): self.product += "Part B\n" class Product: """ Complex object """ def __init__(self): self._str = "" def __add__(self, X): return self._str + X def __str__(self): return self._str def main(): builder1 = Builder1() director = Director() director.construct(builder1) product = builder1.product print(product) if __name__ == "__main__": main()
false
721e7a53934cff06f6b2dedca6224105f625e56e
marb61a/Course-Notes
/Artificial Intellingence/Python/Notebooks/PyImageSearch University/OpenCV 102/simple_thresholding.py
2,216
4.3125
4
# USAGE # python simple_thresholding.py --image images/coins01.png # The accompanying text tutorial is available at # https://www.pyimagesearch.com/2021/04/28/opencv-thresholding-cv2-threshold/ # Thresholding is a basic image segmentation technique # The goal is to segment an image into foreground and background pixels/objects # Thresholding is used a lot in computer vision and image processing # The biggest pain using this type of thresholding is that you have to # manually set the threshold value, it will require a lot of experimentation # and can be difficult to be successful. There may be occasions when due to # lighting parts of images may need different thresholds # import the necessary packages import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", type=str, required=True, help="path to input image") args = vars(ap.parse_args()) # load the image and display it image = cv2.imread(args["image"]) cv2.imshow("Image", image) # When thresholding an image it will be grayscale or a single channel image # convert the image to grayscale and blur it slightly gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Removes the high frequency noise and smoothes out details blurred = cv2.GaussianBlur(gray, (7, 7), 0) # apply basic thresholding -- the first parameter is the image # we want to threshold, the second value is is our threshold # check; if a pixel value is greater than our threshold (in this # case, 200), we set it to be *black, otherwise it is *white* # Typically when constructing an image we will want black pixels as the background # and white as the foreground, the final parameter is usually set to 255 (T, threshInv) = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY_INV) cv2.imshow("Threshold Binary Inverse", threshInv) # using normal thresholding (rather than inverse thresholding) (T, thresh) = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY) cv2.imshow("Threshold Binary", thresh) # visualize only the masked regions in the image using bitwise # operations (foreground region) masked = cv2.bitwise_and(image, image, mask=threshInv) cv2.imshow("Output", masked) cv2.waitKey(0)
true
21c4e3dc082242c5efe4e4ee022ab830b01c6488
markk628/SortingAlgorithms
/IntegerSortingAlgorithm/bucket_sort.py
2,911
4.25
4
import time def merge(items1, items2): merged_list = [] left = 0 right = 0 while left < len(items1) and right < len(items2): if items1[left] < items2[right]: merged_list.append(items1[left]) left += 1 else: merged_list.append(items2[right]) right += 1 merged_list.extend(items1[left:]) merged_list.extend(items2[right:]) return merged_list def merge_sort(items): if len(items) <= 1: return items middle = len(items) // 2 left = items[:middle] right = items[middle:] print(middle, left, right) return merge(merge_sort(left), merge_sort(right)) def bucket_sort(numbers, num_buckets=10): """Sort given numbers by distributing into buckets representing subranges, then sorting each bucket and concatenating all buckets in sorted order. TODO: Running time: O(n + k) Why and under what conditions? Must iterate through numbers first to find max value (O(n)). Then for each value is run through sort of a hash function to determine where in the bucket list it will go (k) TODO: Memory usage: O(n) Why and under what conditions? A bucket must be created for each value in numbers""" # TODO: Find range of given numbers (minimum and maximum values) # TODO: Create list of buckets to store numbers in subranges of input range # TODO: Loop over given numbers and place each item in appropriate bucket # TODO: Sort each bucket using any sorting algorithm (recursive or another) # TODO: Loop over buckets and append each bucket's numbers into output list # FIXME: Improve this to mutate input instead of creating new output list """ iterate through the array and find the max value of the array create an empty list create a list of buckets with the amount of buckets being the same as the amount of items in array for item in array make a variable that equals to item times the number of items divided by max value plus 1 insert this item into the bucket list where index equals the variable sort the buckets in bucket list append values of bucket list into empty list return empty list """ max_value = max(numbers) bucket_list = [] sorted_list = [] for i in range(len(numbers)): bucket_list.append([]) for i in range(len(numbers)): bucket_list_index = int(numbers[i] * num_buckets / (max_value + 1)) bucket_list[bucket_list_index].append(numbers[i]) merge_sort(bucket_list[bucket_list_index]) # for i in range(len(numbers)): # merge_sort(bucket_list[i]) for i in range(len(numbers)): sorted_list += bucket_list[i] return sorted_list items = [18,24,12,4,9,44,32,50,36,25] start = time.time() print(bucket_sort(items)) end = time.time() print("%.10f" % (end - start))
true
596bbb9f084a59722466deb904cd5b534541af20
EnusNata/conhecendo-linguagens
/python/exercicios/8.6.py
607
4.28125
4
#8.6 – Nomes de cidade: Escreva uma função chamada city_country() que #aceite o nome de uma cidade e seu país. A função deve devolver uma string #formatada assim: "Santiago, Chile" #Chame sua função com pelo menos três pares cidade-país e apresente o valor #devolvido. def city_country( cidade , país ): city_countr = cidade + ', ' + país return city_countr city_countr = city_country( 'Rio De Janeiro' , 'Brasil' ) print( city_countr ) city_countr = city_country( 'París' , 'França' ) print( city_countr ) city_countr = city_country( 'Tokyo' , 'Japão' ) print( city_countr )
false
d47b7f3bc91e948d4295a99a506a66739aa6efe6
EnusNata/conhecendo-linguagens
/python/exercicios/4.1.py
1,002
4.5
4
#4.1 – Pizzas: Pense em pelo menos três tipos de pizzas favoritas. Armazene os #nomes dessas pizzas e, então, utilize um laço for para exibir o nome de cada #pizza. #• Modifique seu laço for para mostrar uma frase usando o nome da pizza em #vez de exibir apenas o nome dela. Para cada pizza, você deve ter uma linha #na saída contendo uma frase simples como Gosto de pizza de pepperoni. #• Acrescente uma linha no final de seu programa, fora do laço for, que informe #quanto você gosta de pizza. A saída deve ser constituída de três ou mais #linhas sobre os tipos de pizza que você gosta e de uma frase adicional, por #exemplo, Eu realmente adoro pizza! pizzas = ['calabresa','mucarella','portuguesa'] for pizza in pizzas: if pizza == 'calabresa': print('eu gosto pouco de pizza de calabresa') elif pizza == 'mucarella': print('eu gosto mais ou menos de mucarella') else: print('eu gosto muito de portuguesa') print('eu gosto dessas tres pizzas')
false
9b934134b5ceaf533479a7f92d34c95f36b26af8
EnusNata/conhecendo-linguagens
/python/exercicios/3.6.py
924
4.125
4
#3.6 – Mais convidados: Você acabou de encontrar uma mesa de jantar maior, #portanto agora tem mais espaço disponível. Pense em mais três convidados #para o jantar. #• Comece com seu programa do Exercício 3.4 ou do Exercício 3.5. Acrescente #uma instrução print no final de seu programa informando às pessoas que #você encontrou uma mesa de jantar maior. #• Utilize insert() para adicionar um novo convidado no início de sua lista. #• Utilize insert() para adicionar um novo convidado no meio de sua lista. #• Utilize append() para adicionar um novo convidado no final de sua lista. #• Exiba um novo conjunto de mensagens de convite, uma para cada pessoa #que está em sua lista. convidados = ['hamlet','ophelia','lear','azenath'] convidados.insert(0,'hermes') convidados.insert(3,'macbeth') convidados.append('electra') for convidado in convidados: print('seja bem vindo {}'.format(convidado))
false
c8eb5bbc98196f3fe7341e70136d98977822c81e
EnusNata/conhecendo-linguagens
/python/exercicios/4.8.py
385
4.25
4
#4.8 – Cubos: Um número elevado à terceira potência é chamado de cubo. Por #exemplo, o cubo de 2 é escrito como 2**3 em Python. Crie uma lista dos dez #primeiros cubos (isto é, o cubo de cada inteiro de 1 a 10), e utilize um laço for #para exibir o valor de cada cubo. cubos = [] for numero in range(1,11): cubos.append( numero**3 ) for cubo in cubos: print( cubo )
false
a52ed5c8d11c47a6f40b0d1981f6901d611af66b
priya8936/Codewayy_Python_Series
/Python-task-2/Dictionary.py
705
4.125
4
#Students detail student_detail = { "Name" : "Priya Aggarwal", "College" : "DIT University", "year" : "3rd" } print(student_detail) #Using key() function print(student_detail.keys()) #using get() function stu = student_detail.get("college") print("\nModel of the car :-",stu) #using value() function print(student_detail.values()) #using item function print("\nDetails of a student :-") for i,j in student_detail.items(): print(i,j) #using len() function print("\nLength- ",len(student_detail)) #printing all key value one by one for x in student_detail: print(x) #adding new items student_detail["course"] = "Computer Science" print(student_detail)
false
7de66659c2cfe58e23c57090703c6a788eb1eb1c
Klauss-Preising/Weekly-Challenges
/Fall - 2018/Week 4/Week 4.py
712
4.21875
4
""" Make a function that takes a list and returns the list sorted using selection sor The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. """ def selectionSort(unsortedList): lst = unsortedList[::] for i in range(len(lst)): temp = i for j in range(i, len(lst)): if lst[temp] > lst[j]: temp = j lst[i], lst[temp] = lst[temp], lst[i] return lst print(selectionSort([2, 1, 54, 5, 345, 3, 45, 13, 21, 3])) print(selectionSort([0, 2, 89, 3, 6, 57, 65, 76, 57, 653, 4546, 43]))
true
bbba0d4cfc89e9f65a1fcc9eaaa6a836c197daf5
fares-ds/Algorithms_and_data_structures
/00_algorithms_classes/merge_sort_iterative.py
1,328
4.125
4
def merge_sort(lst): sorted_lst = [None] * len(lst) size = 1 while size <= len(lst) - 1: sort_pass(lst, sorted_lst, size, len(lst)) print(sorted_lst) size = size * 2 def sort_pass(lst, sorted_lst, size, length): low_1 = 0 while low_1 + size <= length - 1: up_1 = low_1 + size - 1 low_2 = low_1 + size up_2 = low_2 + size - 1 if up_2 >= length: up_2 = length - 1 merge(lst, sorted_lst, low_1, up_1, low_2, up_2) low_1 = up_2 + 1 for i in range(low_1, length): sorted_lst[i] = lst[i] copy(lst, sorted_lst, length) def merge(lst, sorted_lst, low_1, up_1, low_2, up_2): i, j, k = low_1, low_2, low_1 while i <= up_1 and j <= up_2: if lst[i] <= lst[j]: sorted_lst[k] = lst[i] i += 1 else: sorted_lst[k] = lst[j] j += 1 k += 1 while i <= up_1: sorted_lst[k] = lst[i] i += 1 k += 1 while j <= up_2: sorted_lst[k] = lst[j] j += 1 k += 1 def copy(lst, sorted_lst, length): for i in range(length): lst[i] = sorted_lst[i] list_1 = [91, 88, 16, 35, 52, 12, 28, 67, 29] print(f"This list {list_1} sorted using 'Merge Sort'") merge_sort(list_1) print(list_1)
false
1c1aa1f96da08dbd95ed078b87e8e4bfc3a05a9d
fares-ds/Algorithms_and_data_structures
/04_recursion/reverse_string.py
207
4.125
4
def reverse_string(string): # Basic Case if len(string) <= 1: return string # Recursion function return reverse_string(string[1:]) + string[0] print(reverse_string('Hello world'))
false
661a13971faf750ec454dc6ce878c7bbf4bb1f92
NatalyaDomnina/leetcode
/python/05. [31.08.17] Merge Two Binary Trees.py
2,032
4.15625
4
''' Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def add_left(self, x): self.left = x def add_right(self, x): self.right = x def printTree(self): print(self.val) if self.left != None: self.left.printTree() if self.right != None: self.right.printTree() class Solution(object): def mergeTrees(self, t1, t2): if t1 == None: return t2 if t2 == None: return t1 t1.val = t1.val + t2.val t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) return t1 ####################################################################### t1 = TreeNode(1) t2 = TreeNode(3) t4 = TreeNode(5) t3 = TreeNode(2) t2.add_left(t4) t1.add_left(t2) t1.add_right(t3) print (t1.printTree()) t5 = TreeNode(2) t6 = TreeNode(1) t7 = TreeNode(4) t8 = TreeNode(3) t9 = TreeNode(7) t6.add_right(t7) t5.add_left(t6) t8.add_right(t9) t5.add_right(t8) print (t5.printTree()) s = Solution() t10 = s.mergeTrees(t1, t5) print (t10.printTree())
true
42ae6ae0d309950914bdbc6350a180c24a1a5d92
fancy0815/Hello-Hello
/Python/5_Functions/1_Map and Lambda Function.Py
436
4.21875
4
cube = lambda x: x**3 # complete the lambda function def fibonacci(n): # return a list of fibonacci numbers if n==1: return [0] if n==0: return [] fib = [0,1] for i in range (2,n): fib += [sum(fib[i-2:i])] return fib # return fib[0:n] # return[sum(fib[i-2:i]) for x in range(n)] if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
true
fe6bb27b70808ee72441d9aba87040d52d09b6a1
skybohannon/python
/w3resource/basic/4.py
378
4.59375
5
# 4. Write a Python program which accepts the radius of a circle from the user and compute the area. # The area of circle is pi times the square of its radius. # Sample Output : # r = 1.1 # Area = 3.8013271108436504 from math import pi radius = float(input("Please enter the radius of your circle: ")) area = pi * (radius**2) print("Radius: {}\nArea: {}".format(radius, area))
true
334fb0bde5f0c2fddee9b27d104aa54a233f45d8
skybohannon/python
/w3resource/string/11.py
323
4.15625
4
# 11. Write a Python program to remove the characters which have odd index values of a given string. def remove_odds(str): new_str = "" for i in range(len(str)): if i % 2 == 0: new_str = new_str + str[i] return new_str print(remove_odds("The quick brown fox jumped over the lazy dog"))
true
6612b6f86f022b90b5e41f4aff4586aacf41e1ce
skybohannon/python
/w3resource/25.py
333
4.25
4
# 25. Write a Python program to check whether a specified value is contained in a group of values. # Test Data : # 3 -> [1, 5, 8, 3] : True # -1 -> [1, 5, 8, 3] : False def in_values(i, lst): if i in lst: return True else: return False print(in_values(3, [1, 5, 8, 3])) print(in_values(-1, [1, 5, 8, 3]))
true
d31125e3528c4ce3fbde12349bacfcc20d4fd5d9
skybohannon/python
/w3resource/string/32.py
256
4.125
4
# 32. Write a Python program to print the following floating numbers with no decimal places. x = 3.1415926 y = -12.9999 print("Original number: {}\nFormatted number: {:.0f}".format(x, x)) print("Original number: {}\nFormatted number: {:.0f}".format(y, y))
true
e6ad416dcbc20283cd2ed283872f6362118c1efc
skybohannon/python
/w3resource/string/26.py
461
4.34375
4
# 26. Write a Python program to display formatted text (width=50) as output. import textwrap text_block = "Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. " \ "Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts " \ "in fewer lines of code than possible in languages such as C++ or Java." print(textwrap.fill(text_block, width=50))
true
6e63b95872bcfa0c0c2e5d81568a398c146cd393
skybohannon/python
/w3resource/string/38.py
366
4.25
4
# 38. Write a Python program to count occurrences of a substring in a string. str1 = "FYI man, alright. You could sit at home, and do like absolutely nothing, and your name goes through like 17 computers a day. 1984? Yeah right, man. That's a typo. Orwell is here now. He's livin' large. We have no names, man. No names. We are nameless!" print(str1.count("man"))
true
c6a50a2cc4250618428fe74a9b35b215db56f07f
skybohannon/python
/w3resource/string/7.py
540
4.15625
4
# 7. Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string, # if 'bad' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string. # Sample String : 'The lyrics is not that poor!' # Expected Result : 'The lyrics is good!' def bad_poor(str): nots = str.find('not') poors = str.find('poor') if poors > nots: str = str.replace(str[nots:(poors + 4)], 'good') return str print(bad_poor("The lyrics is not that poor!"))
true
e00cb16e158ea45b54c71ddfb6d8f2ece9db06b0
Dragnes/Automate-the-Boring-Stuff-with-Python
/Lesson 15 pg 89-92.py
1,211
4.375
4
#Lesson 15 pages 89-92 'Method is similar to function, except it is "called on" a value.' # Finding a Value in a List with the index() Method spam = ['hello', 'hi', 'howdy', 'heyas'] spam.index('hello') spam.index('heyas') # Adding Values to a List using append() and insert() Methods spam = ['cat', 'dog', 'bat'] spam.append('moose') spam.insert(2, 'chicken') # Remove Values from Lists with remove() Method spam = ['cat', 'bat', 'rat', 'elephant'] spam.remove('bat') spam = ['cat', 'bat', 'rat', 'cat', 'hat', 'cat'] spam.remove('cat') # Sorting the Values in a List with the sort() Method # Increasing order spam = [2, 5, 3.14, 1, -7] spam.sort() spam = ['ants', 'dogs', 'baggers', 'elephants', 'cats'] spam.sort() # Decreasing order spam = [2, 5, 3.14, 1, -7] spam.sort(reverse = True) spam = ['ants', 'dogs', 'baggers', 'elephants', 'cats'] spam.sort(reverse = True) # Integers and Strinigs can't be sorted, due to silliness python spam = [1, 2, 3, 4, 'Alice', 'in', 'land'] spam.sort() # Caps vs non-Caps spam = ['Alice', 'ants', 'AAbob', 'Bob', 'baggers','Carol', 'AABob', 'cats'] spam.sort() spam = ['A', 'Z', 'a', 'z'] spam.sort(key = str.lower)
true
09afad6687e6dffbda763514f059c9c44b35f69a
byugandhara1/assessment
/polygon.py
432
4.21875
4
''' Program 1 : Check if the given point lies inside or outside a polygon? ''' from shapely.geometry import Point, Polygon def check_point_position(polygon_coords, point_coords): polygon = Polygon(polygon_coords) point = Point(point_coords) print(point.within(polygon)) polygon_coords = input('Enter polygon coordinates -') point_coords = input('Enter point coordinates -') check_point_position(polygon_coords, point_coords)
true
bf66df0a04e52ab210db84b47f24a3e575dfe0c4
Yozi47/Data-Structure-and-Algorithms-Class
/Homework 5/C 5.26.py
1,070
4.1875
4
B = [1, 2, 3, 3, 3, 3, 3, 4, 5] # considering B as an array of size n >= 6 containing integer from 1 to n-5 get_num = 0 for i in range(len(B)): # looping the number of elements check = 0 for j in range(len(B)): # looping the number of elements if B[i] == B[j]: # checking for common number check += 1 if check >= 5: # if 5 common number are found then add that number to get_num get_num = B[i] print("The repeated number is: ", get_num) ''' From the above code and question, B is an array with size n >= 6 containing integer from 1 to n-5 with exactly five repeated. In above code, a loop inside a loop is used in which first loop iterate n times and same with the second loop Then each element in the array is checked if there is common number or not In 1 complete iteration there would be 1 common number except for that number which is repeated number. The repeated number iteration gives 5 common number which means the obtained number is repeated number Then, the result is the obtained number '''
true
a464d3a8d375f0356655cc11f0ffa99763725055
jeysonrgxd/python
/nociones_basicas/programacion_funciones/arg_param_indeterminados.py
586
4.25
4
# Las colecciones listas conjuntos estos datos se envian por referencia y no una copia como los demas tipos, por ende si utilizamos una colleccion dentro de una funcion y la modificamos cambiara tambien en la afuera la funcion osea la global def doblar_valores(numeros): for i,n in enumerate(numeros): numeros[i] *=2 ns = [10,50,100] doblar_valores(ns) print(ns) # para que no modifique el valor usamos pequeños trucos def doblar_numeros(numeros): for i,n in enumerate(numeros): numeros[i] *=2 print(numeros) ns2 = [2,4,6,8] doblar_numeros(ns2[:]) print(ns2)
false
82a7eed51ebb8c98f1c1a027e62479f621b5d274
jeysonrgxd/python
/nociones_basicas/controladores_flugo/sentencia_For.py
1,613
4.25
4
# METODO CON EL WHILE DE IMPRIMIR UNA LISTA numeros = [1,2,3,4,5,6,7,8,9,10] # indice = 0 # while indice < len(numeros): # print(numeros[indice]) # indice +=1 # FORMA DE FOR tradicional print("\nFORMA DEL FOR") # for numero in numeros: # print(numero) # modificar elementos del array tenemos que agregarle un contador en el mismo for y utilizar "enumarate" que mas omenos no estoy eguro investigar luego, convierte una lista en un objeto iterable la cual nesesitamos si utilizamos un contador en el for funcion de python # for i,numero in enumerate(numeros): # numeros[i] = numero*numero # print(numeros) # tambien podemos recorrer una cadena, no podemos usar enumerate ya que no nos serviria ya que una cadena es inmutable, pero podemos crear una nueva cadena y concatenar esa cadena nueva con lo valores que queramos saludo = "Hola como estas" cadena_saludo = [] # for caracter in "hola como estas": for caracter in saludo: # imprimimos los caracteres print(caracter) # creamos una lista con los caracteres cadena_saludo.append(caracter) print(cadena_saludo) # FOR tradicional de los demas lenguajes con rango de numero, recordar que el range(10) comienza de cero asta el numero que le pongamos pero no toma ese ultimo valor sino uno antes de llegar al especificado. # esta forma de for con una lista creada de 10 numero si queremos queremos iterar de esta forma, opcupa espacio en memoria por eso no es recomendable, a cabio range(10) es interpretado por python , y mas no ocupa espacio en memoria # for num in [0,1,2,3,4,5,6,7,8,9,10] for num in range(10): print(num)
false
2b2765e7e51b754bdc6f580789c525dec86766a7
Shivanisarikonda/assgn1
/newfile.py
294
4.1875
4
import string def pangram(string): alphabet="abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in string: return False return True string="five boxing wizards jump quickly" if(pangram(string)==True): print("given string is pangram") else: print("string is not a pangram")
true
9ae7ed690d2b3c60271b9ae0eb094e77bfde4797
heloise-steam/My-Python-Projects
/Turtle Time Trials
1,384
4.15625
4
#!/bin/python3 from turtle import* from random import randint print('Pick a turtle either green yellow blue red and chose a stage that the turtle you picked will get up. To make sure you bet with each other') print('Ok now let the time trials begin') speed(10) penup() goto(-140, 140) for step in range(15): write(step) right(90) forward(10) pendown() forward(150) penup() backward(160) left(90) forward(20) ada = Turtle() ada.color('red') ada.color('turtle') ada.penup() ada.goto(-160, 160) ada.pendown() for turn in range(100): ada.forward(randint(1,5)) bob = Turtle() bob.color('blue') bob.shape('turtle') bob.penup() bob.goto(-160, 70) bob.pendown for turn in range(100): ada.forward(randint(1,5)) bob.forward(randint(1,5)) bob = Turtle() bob.color('red') bob.shape('turtle') bob.penup() bob.goto(-160, 50) bob.pendown for turn in range(100): ada.forward(randint(1,5)) bob.forward(randint(1,5)) bob = Turtle() bob.color('yellow') bob.shape('turtle') bob.penup() bob.goto(-160, 90) bob.pendown for turn in range(100): ada.forward(randint(1,5)) bob.forward(randint(1,5)) bob = Turtle() bob.color('green') bob.shape('turtle') bob.penup() bob.goto(-160, 110) bob.pendown for turn in range(100): ada.forward(randint(1,5)) bob.forward(randint(1,5)) print('So which one of your turtles one the race?') print('Thanks for playing, bye!')
true
adc2e276f9795092034d9cb1942446a30c6a3755
eric-elem/prime-generator
/primegenerator.py
1,411
4.15625
4
import math import numbers import decimal def get_prime_numbers(n): # check if input is a number if isinstance(n,numbers.Number): # check if input is positive if n>0: # check if input is decimal if isinstance(n, decimal.Decimal): return 'Undefined' else: # check if n is 0 or 1 as prime numbers start from 2 if n==0 or n==1: return 'Undefined' else: prime_numbers=[2] if(n>=2): """ loop through odd numbers from 3 to n as even numbers aren't prime except 2 """ for num in range(3,n+1,2): num_is_prime=True # selecting denominator between 2 and sqrt(num) for denom in range(2,int(math.sqrt(num))+1): if(num%denom==0): num_is_prime=False break if(num_is_prime): prime_numbers.append(num) return prime_numbers else: return 'Undefined' else: return 'Undefined'
true
2e6f198de36b43c6455ee8c11e425729d37cd8db
mjcastro1984/LearnPythonTheHardWay-Exercises
/Ex3.py
714
4.34375
4
print "I will now count my chickens:" # the following lines count the number of chickens print "Hens", 25.0 + 30.0 / 6.0 print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 print "Now I will count the eggs:" # this line counts the number of eggs print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 print "Is it true that 3 + 2 < 5 - 7?" # this line checks that the statement above is true or false print 3.0 + 2.0 < 5.0 - 7.0 # these lines break down the math above print "What is 3 + 2?", 3.0 + 2.0 print "What is 5 - 7?", 5.0 - 7.0 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
252ba707cb39ef0c0f3100c1586a94d34060ddd0
hmtareque/play-with-python
/numbers.py
1,975
4.1875
4
""" Number data types store numeric values. Number objects are created when you assign a value to them. """ num = 1076 print(num) """ Python supports four different numerical types: - int (signed integers) They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore. - float (floating point real values) Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 - complex (complex numbers) are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming. """ num_int = 8 #int num_float = 90.75 #float num_complex = 3.2j #complex # to show datatype print(type(num_int)) print(type(num_float)) print(type(num_complex)) # Number conversion con_int_to_float = float(num_int) print(type(con_int_to_float)) """ Python converts numbers internally in an expression containing mixed types to a common type for evaluation. Sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter. - Type int(x) to convert x to a plain integer. - Type float(x) to convert x to a floating-point number. - Type complex(x) to convert x to a complex number with real part x and imaginary part zero. - Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions """
true
9785f3ad0bbf239885768d4a4c046ad81c6c8930
holmanapril/01_lucky_unicorn
/01_test.py
2,028
4.25
4
#name = input("Hello, what is your name?") #fruit = input("Pick a fruit") #food = input("What is your favourite food?") #animal = input("Pick an animal") #animal_name = input("Give it a name") #print("Hi {} guess what? {} the {} is eating some {} and your {}".format(name, animal_name, animal, fruit, food)) #Setting score and lives variables score = 0 lives =5 highscore = 0 #Question 1 answer_1 = input("What country is the Unicorn native to?") answer_1 = answer_1.strip().title() if answer_1 == "Scotland": print("That is correct") score += 1 else: print("That is incorrect, the Unicorn is actually native to Scotland") lives -= 1 #Question 2 while True: try: answer_2 = float(input("How many miles away from a Blue Whale can you hear its heartbeat?")) break except ValueError: print("Please enter a valid number") if answer_2 == 2: print("That is correct") score += 1 else: print("That is incorrect, the answer is actually 2 miles") lives -= 1 #Question 3 answer_3 = input("What is a baby puffin called?") answer_3 = answer_3.strip().title() if answer_3 == "Puffling": print("That is correct") score += 1 else: print("That is incorrect, the answer is Puffling") lives -= 1 #Question 4 while True: try: answer_4 = int(input ("How many grapes are needed to make 1 bottle of wine?")) break except ValueError: print("Please enter a valid number") if answer_4 == 700: print("That is correct") score += 1 else: print("That is incorrect, the answer is actually 700 grapes") lives -= 1 #Question 5 while True: try: answer_5 = int(input("How many million American Hotdogs do Americans eat on the 4th of July?")) break except ValueError: print("Please enter a valid number") if answer_5 == 150: print("That is correct") score += 1 else: print("That is incorrect,the answer was 150 million") lives -= 1 for lives in range(0): break
true
20891f3bcb76fb0be3f6de35ec847d39cae21f3f
ed18s007/DSA
/04_Trees/01_binary_tree.py
1,075
4.125
4
class Node(object): def __init__(self, value = None): self.value = value self.left = None self.right = None def get_value(self): return self.value def set_value(self, value): self.value = value def has_left_child(self): return self.left is not None def has_right_child(self): return self.right is not None def set_left_child(self, node): self.left = node def get_left_child(self): return self.left def set_right_child(self, node): self.right = node def get_right_child(self): return self.right node0 = Node("apple") node1 = Node("banana") node2 = Node("orange") print(f""" value: {node0.value} left: {node0.left} right: {node0.right} """) print(f"has left child? {node0.has_left_child()}") print(f"has right child? {node0.has_right_child()}") node0.set_left_child(node1) node0.set_right_child(node2) print(f""" node 0: {node0.value} node 0 left child: {node0.left.value} node 0 right child: {node0.right.value} """) class Tree: def __init__(self, value = None): self.root = Node(value) def get_root(self): return self.root
false
c8ad2e40362bfd97d43283cc79327facf385dd5c
yarmash/projecteuler
/python/p019.py
750
4.3125
4
#!/usr/bin/env python3 """Problem 19: Counting Sundays""" def is_leap_year(year): """Determine whether a year is a leap year""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def main(): numdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) year, month, wday = 1901, 0, 2 # Tue, 1 Jan 1901 is_leap = False sundays = 0 while year < 2001: if wday == 0: sundays += 1 days = 29 if is_leap and month == 1 else numdays[month] wday = (wday + days) % 7 if month < 11: month += 1 else: month = 0 year += 1 is_leap = is_leap_year(year) return sundays if __name__ == "__main__": print(main())
false
c82a9e44ac4a78a843bb598c1cba56f8c6ffd773
lahwahleh/python-jupyter
/Errors and Exception Handling/Unit Testing/cap.py
259
4.15625
4
""" A script to captilize texts """ def cap_text(text): """ function takes text and capitalizes it """ # words = text.split() # for word in words: # print(word.capitalize()) return text.title() cap_text("hello world today")
true
a1582e358de014f841f145a9f473e6e62d89eb8e
ErenTaskin/Celsius-to-fahrenheit-conversation
/Celcius to fahrenheit.py
479
4.15625
4
def c_to_f(): print('Celcius to fahrenheit or fahrenheit to celcius?(c to f or f to c)') x = input() if x == 'c to f': print('How much celcius?') c = float(input()) f = float(c * 9/5 + 32) print('%s celcius is %s fahrenheit.'% (c, f)) elif x == 'f to c': print('How much fahrenheit?') f1 = float(input()) c1 = float(5/9 * (f1-32)) print('%s fahrenheit is %s celcius.'% (f1, c1)) else: c_to_f() input('Press ENTER to exit') c_to_f()
false
6aa6cd6587b61ef3a44554f215d9b64fee69a2c3
Motiwala22/python-calculator
/calculator.py
653
4.1875
4
print("1: Addition") print("2: Subtraction") print("3: Multiplication") print("4: Division") choice = input("Enter your chocie here : ") num1 = int(float(input("Input Value: "))) num2 = int(float(input("Input Value "))) if choice == "1": print( num1, "+", num2, "=", (num1+num2)) elif choice == "2": print( num1, "-", num2, "=", (num1-num2)) elif choice == "3": print( num1, "*", num2, "=", (num1*num2)) elif choice == "4": if num2 == 0.0: print("Divided by 0; Error 404") else: print( num1, "/", num2, "=", (num1/num2)) else: print("Invaild choice") print("Operation has been completed successfully!")
false
83727ced73caf7c95dfbbf9cc1a2087099123377
vikasmunshi/euler
/projecteuler/041_pandigital_prime.py
1,083
4.15625
4
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- """ https://projecteuler.net/problem=41 We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? Answer: 7652413 """ from itertools import permutations def is_prime(n: int) -> bool: for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def largest_pandigital_prime() -> int: pandigital_primes = ( number for length in (7, 4) # all other length pandigital numbers are divisible by 3 {2: 3, 3: 6, 4: 10, 5: 15, 6: 21, 7: 28, 8: 36, 9: 45} for number in (int(''.join(digits)) for digits in permutations(reversed('123456789'[:length]), length)) if is_prime(number) ) return next(pandigital_primes) if __name__ == '__main__': from .evaluate import Watchdog with Watchdog() as wd: results = wd.evaluate(largest_pandigital_prime)(answer=7652413)
true
e25cf5ed10c5692653bfca95afe045a347f34219
Surbhi-Golwalkar/Python-programming
/programs.py/p4.py
348
4.25
4
# '''The int() function converts the specified value into an integer number. # We are using the same int() method to convert the given input. # int() accepts two arguments, number and base. # Base is optional and the default value is 10. # In the following program we are converting to base 17''' num = str(input("ENTER :")) print(int(num,17))
true
a3b1f0ccf64324a1a493c96b651fa127a64760da
Surbhi-Golwalkar/Python-programming
/loop/prime.py
280
4.1875
4
num = int(input("enter number:")) prime = True for i in range(2,num): if(num%i == 0): prime = False break if (num==0 or num==1): print("This is not a prime number") elif prime: print("This number is Prime") else: print("This number is not prime")
true
a318db450ffc3dc94bc00b0a413446a7e5e4723b
Surbhi-Golwalkar/Python-programming
/programs.py/washing-machine.py
1,547
4.5625
5
# A Washing Machine works on the principle of a Fuzzy system, # the weight of clothes put inside it for wash is uncertain. # But based on weight measured by sensors, it decides time and water # levels which can be changed by menus given on the machine control # area. For low Water level, time estimate is 25 minutes, where # approximate weight is 2000 grams or any non-zero positive number # below that. For Medium Water level, time estimated is 35minutes, # where approximate weight is between 2001 grams and 4000 grams. # For High Water level, time estimated is 45 Minutes, # where approximate weight is above 4000 grams. # Assume the Capacity of the Machine is maximum 7000 grams. # Where the approximate weight is zero, the time estimate is 0 minutes. # Write a function which takes numeric weight in the range [0,7000] # as input and produces estimated time as output; # if input is more than 7000, then output is: “OVERLOADED!”, # and for all other inputs, the output statement is “INVALID INPUT”. # Input should be in the form of integer value – Output must have the # following format – Time Estimated: Minutes # Example 1 # Input Value # 2000 # Output Value # Time Estimated: 25 Minutes n = int(input("Enter no.")) if n==0: print("Time Estimated : 0 Minutes") elif n in range(1,2001): print("Time Estimated : 25 Minutes") elif n in range(2001,4001): print("Time Estimated : 35 Minutes") elif n in range(4001,7001): print("Time Estimated : 45 Minutes") else: print("INVALID INPUT")
true
773ce4110c657204df88c1653f277c8790b9e2af
CalebCov/Caleb-Repository-CIS2348
/Homework1/2.19.py
1,410
4.1875
4
#Caleb Covington lemon_juice_cups = float(input('Enter amount of lemon juice (in cups):\n')) water_in_cups = float(input('Enter amount of water (in cups):\n')) agave_in_cups = float(input('Enter amount of agave nectar (in cups):\n')) servings = float(input('How many servings does this make?\n')) print('\nLemonade ingredients - yields', '{:.2f}'.format(servings), 'servings') print('{:.2f}'.format(lemon_juice_cups), 'cup(s) lemon juice') print('{:.2f}'.format(water_in_cups), 'cup(s) water') print('{:.2f}'.format(agave_in_cups), 'cup(s) agave nectar\n') num_of_servings = float(input('How many servings would you like to make?\n')) print('\nLemonade ingredients - yields', '{:.2f}'.format(num_of_servings), 'servings') convert_lemon = num_of_servings / 3 convert_water = num_of_servings * 2.66666667 convert_agave = num_of_servings / 2.4 print('{:.2f}'.format(convert_lemon), 'cup(s) lemon juice') print('{:.2f}'.format(convert_water), 'cup(s) water') print('{:.2f}'.format(convert_agave), 'cup(s) agave nectar\n') gallons_of_lemon = convert_lemon / 16 gallons_of_water = convert_water / 16 gallons_of_agave = convert_agave / 16 print('Lemonade ingredients - yields', '{:.2f}'.format(num_of_servings), 'servings') print('{:.2f}'.format(gallons_of_lemon), 'gallon(s) lemon juice') print('{:.2f}'.format(gallons_of_water), 'gallon(s) water') print('{:.2f}'.format(gallons_of_agave), 'gallon(s) agave nectar')
true
04ed8d95e2d03a0b9c1aedbcaa1dcbd4a9121a21
PEGGY-CAO/ai_python
/exam1/question3.py
526
4.1875
4
# Given the following array: # array([[ 1, 2, 3, 4, 5], # [ 6, 7, 8, 9, 10], # [11, 12, 13, 14, 15]]) # write statements to perform the following tasks: # # a. Select the second row. # # b. Select the first and third rows. # # c. Select the middle three columns. import numpy as np array = np.array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) print("question a") print(array[1]) print("\nquestion b") print(array[[0, 2]]) print("\nquestion c") print(array[:,1:4])
true
890ed31dfd858591a2850c17bf516d05eed46cf2
PEGGY-CAO/ai_python
/wk2/calCoins.py
607
4.21875
4
# This program is used to ask the user to enter a number of quarters, dimes, nickels and pennies # Then outputs the monetary value def askFor(coinUnit): coinCounts = int(input("How many " + coinUnit + " do you have?")) if coinUnit == "quarters": return 25 * coinCounts elif coinUnit == "dimes": return 10 * coinCounts elif coinUnit == "nickels": return 5 * coinCounts else: return coinCounts sum = 0 sum += askFor("quarters") sum += askFor("dimes") sum += askFor("nickels") sum += askFor("pennies") print("Total monetary value is: $" + str(sum / 100))
true
8f4d286e3c9cbdd2736972bbea43113805060cc0
manu-s-s/Challenges
/challenge2.py
412
4.15625
4
# Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # The string will only contain lowercase characters a-z import sys text=input('enter text: ') if text==text[::-1]: print('palindrome') sys.exit(0) for i in range(len(text)): k=text[0:i]+text[i+1:] if k==k[::-1]: print('palindrome') sys.exit(0) print('not palindrome')
true
d921eab7839c522018051a8ae3fb5d95d47fdbfa
Darkbladecr/ClinDev-algorithms
/06 queue/queue.py
1,206
4.15625
4
"""Queue implementation. A queue is an abstract data type that serves as a collection of elements, with two principal operations: enqueue, which adds an element to the collection, and dequeue, which removes the earliest added element. The order in which elements are dequeued is `First In First Out` aka. `FIFO`. The term `queue` takes it name from the real world queues e.g. "a queue at the ticket counter". """ class Queue: """Creates a Queue.""" def __init__(self): """Initialize data.""" self.data = list() self.nextEnqueueIndex = 0 self.lastDequeuedIndex = 0 def enqueue(self, item): """Enqueue the item in O(1).""" self.data.insert(self.nextEnqueueIndex, item) self.nextEnqueueIndex += 1 def dequeue(self): """Deqeue the item in 0(1).""" if self.lastDequeuedIndex != self.nextEnqueueIndex: dequeued = self.data[self.lastDequeuedIndex] del self.data[self.lastDequeuedIndex] self.lastDequeuedIndex += 1 return dequeued def size(self): """Return the number of elements in the queue.""" return self.nextEnqueueIndex - self.lastDequeuedIndex
true
f374e213211ff8a50aa6f9b0880ef0da146efe1f
MariaNazari/Introduction-to-Python-Class
/cs131ahw5Final.py
555
4.78125
5
""" The purpose of this program is to print out its own command line arguments in reverse order from last to first. Directions: enter file name following by inputs Example: filename.py Input1 Input2 ... Input n """ import sys # Get argument list: args = list(sys.argv) #Remove file name args.pop(0) # Reverse arguments args_reversed = args[::-1] #args_reversed = list(reversed(sys.argv)) #Print out print("Command Line Inputs Oringal:", ' '.join(args)) print("Command Line Inputs Reversed:", ' '.join(args_reversed))
true
2fe67867fe4bcd18aeda6179b6b1992873cda22a
polina-pavlova/epam_python_feb21
/homework7/tasks/hw1.py
819
4.15625
4
""" Given a dictionary (tree), that can contains multiple nested structures. Write a function, that takes element and finds the number of occurrences of this element in the tree. Tree can only contains basic structures like: str, list, tuple, dict, set, int, bool """ from typing import Any def find_occurrences(tree: dict, element: Any) -> int: counter = 0 if tree == element: counter += 1 elif isinstance(tree, (list, tuple, set)): for i in tree: counter += find_occurrences(i, element) elif isinstance(tree, dict): for k, v in tree.items(): if k == element: counter += 1 counter += find_occurrences(v, element) return counter if __name__ == "__main__": print(find_occurrences(example_tree, "RED")) # 6
true
920506e62c69aa9c45b6a658b351bf904623fd9f
jurayev/algorithms-datastructures-udacity
/project2/trees/path_from_root_to_node.py
757
4.15625
4
def path_from_root_to_node(root, data): """ :param: root - root of binary tree :param: data - value (representing a node) TODO: complete this method and return a list containing values of each node in the path from root to the data node """ def return_path(node): # 2 if not node: return None if node.data == data: return [node.data] left_path = return_path(node.left) # 521 if left_path: left_path.append(node.data) return left_path right_path = return_path(node.right) # None if right_path: right_path.append(node.data) return right_path path = return_path(root) return list(reversed(path))
true
926627cd357722cf552dadc7b0986c2420671b14
jurayev/algorithms-datastructures-udacity
/project2/recursion/palindrome.py
384
4.25
4
def is_palindrome(input): """ Return True if input is palindrome, False otherwise. Args: input(str): input to be checked if it is palindrome """ if len(input) < 2: return True first_char = input[0] last_char = input[-1] return first_char == last_char and is_palindrome(input[1:-1]) res = is_palindrome("madam") print(res) assert res
true
ab0129a56445630cccee1c997ed5994217d4ed17
jurayev/algorithms-datastructures-udacity
/project2/recursion/return_codes.py
1,400
4.3125
4
def get_alphabet(number): """ Helper function to figure out alphabet of a particular number Remember: * ASCII for lower case 'a' = 97 * chr(num) returns ASCII character for a number e.g. chr(65) ==> 'A' """ return chr(number + 96) def all_codes(number): # 23 """ :param: number - input integer Return - list() of all codes possible for this number TODO: complete this method and return a list with all possible codes for the input number """ if number == 0: return [""] # calculation for two right-most digits e.g. if number = 1123, this calculation is meant for 23 reminder = number % 100 # 23 out_100 = [] if reminder <= 26 and number > 9: # get all codes for the remaining number char = get_alphabet(reminder) out_100 = all_codes(number // 100) for i, code in enumerate(out_100): out_100[i] = code + char # calculation for right-most digit e.g. if number = 1123, this calculation is meant for 3 reminder = number % 10 # get all codes for the remaining number char = get_alphabet(reminder) out_10 = all_codes(number//10) for i, code in enumerate(out_10): out_10[i] = code + char arr = [] arr += out_100 arr += out_10 return arr # number = 145 # solution = ['abc', 'aw', 'lc'] print(1//10) print(all_codes(1145))
true
77b666b096790694700a2d2e725015d9c2b1fc2c
jurayev/algorithms-datastructures-udacity
/project2/recursion/key_combinations.py
1,827
4.15625
4
""" Keypad Combinations A keypad on a cellphone has alphabets for all numbers between 2 and 9. You can make different combinations of alphabets by pressing the numbers. For example, if you press 23, the following combinations are possible: ad, ae, af, bd, be, bf, cd, ce, cf Note that because 2 is pressed before 3, the first letter is always an alphabet on the number 2. Likewise, if the user types 32, the order would be: da, db, dc, ea, eb, ec, fa, fb, fc Given an integer num, find out all the possible strings that can be made using digits of input num. Return these strings in a list. The order of strings in the list does not matter. However, as stated earlier, the order of letters in a particular string matters. """ def get_characters(num): if num == 2: return "abc" elif num == 3: return "def" elif num == 4: return "ghi" elif num == 5: return "jkl" elif num == 6: return "mno" elif num == 7: return "pqrs" elif num == 8: return "tuv" elif num == 9: return "wxyz" else: return "" def keypad(num): if num <= 1: return [""] elif 1 < num <= 9: return list(get_characters(num)) last_digit = num % 10 small_output = keypad(num//10) keypad_string = get_characters(last_digit) output = list() for character in keypad_string: for item in small_output: new_item = item + character output.append(new_item) return output input = 354 actual = sorted(keypad(input)) print(actual) expected_output = sorted(["djg", "ejg", "fjg", "dkg", "ekg", "fkg", "dlg", "elg", "flg", "djh", "ejh", "fjh", "dkh", "ekh", "fkh", "dlh", "elh", "flh", "dji", "eji", "fji", "dki", "eki", "fki", "dli", "eli", "fli"]) assert actual == expected_output
true
bf3f684516a9a2cb16697ea3d129e6754a2d3af7
jurayev/algorithms-datastructures-udacity
/project2/recursion/staircase.py
1,310
4.28125
4
""" Problem Statement Suppose there is a staircase that you can climb in either 1 step, 2 steps, or 3 steps. In how many possible ways can you climb the staircase if the staircase has n steps? Write a recursive function to solve the problem-2. """ def staircase(n): """ :param: n - number of steps in the staircase Return number of possible ways in which you can climb the staircase TODO - write a recursive function to solve this problem """ if n <= 1: return 1 elif n == 2: return 2 return staircase(n-1) + staircase(n-2) + staircase(n-3) def staircase_with_caching(n): cache = {0: 1, 1: 1, 2: 2, 3: 4} def staircase_memoize(n): if n not in cache.keys(): cache[n] = staircase_memoize(n - 1) + staircase_memoize(n - 2) + staircase_memoize(n - 3) return cache[n] return staircase_memoize(n) def t_function(test_case): n = test_case[0] solution = test_case[1] output = staircase_with_caching(n) print(output) if output == solution: print("Pass") else: print("Fail") n = 3 solution = 4 case = [n, solution] t_function(case) n = 4 solution = 7 case = [n, solution] t_function(case) n = 7 solution = 44 case = [n, solution] t_function(case) print(staircase_with_caching(44))
true
7c6e3af24a972f2a23dc50669bc589e47e325cd5
rtduffy827/github-upload
/python_tutorial_the_basics/example_10_sets.py
1,466
4.5625
5
example = set() print(dir(example), "\n") print(help(example.add)) example.add(42) example.add(False) example.add(3.14159) example.add("Thorium") print(example) # Notice that data of different types can be added to the set # Items inside the set are called elements # Elements of a set could appear in a different order # This is because order does not matter in a set unlike tuples and lists # Sets do not contain duplicate elements example.add(42) print(example) print(len(example)) print(help(example.remove)) # Cannot remove an element that does not exist in a set without an error example.remove(42) print(len(example)) print(example) print(help(example.discard)) # Enables the user to remove an element that does not exist in a set without an error example.discard(50) example2 = set([28, True, 2.71828, "Helium"]) # An alternative and sometimes faster way to populate a set print(len(example2)) example2.clear() # A faster way to empty a set (will return the empty set print(len(example2)) # Union and intersection of sets # Integers 1 - 10 odds = set([1, 3, 5, 7, 9]) evens = set([2, 4, 6, 8, 10]) primes = set([2, 3, 5, 7]) composites = set([4, 6, 8, 9, 10]) print(odds.union(evens)) print(evens.union(odds)) print(odds) print(evens) print(odds.intersection(primes)) print(primes.intersection(evens)) print(evens.intersection(odds)) print(primes.union(composites)) print(2 in primes) print(6 in odds) print(9 not in evens) print("\n", dir(primes))
true
2bc88f03339962830e865e32bcb8927bd5be1bab
sanjay2610/InnovationPython_Sanjay
/Python Assignments/Task4/Ques4.py
421
4.21875
4
# Write a program that accepts a hyphen-separated sequence of words as input and # prints the words in a hyphen-separated sequence after sorting them alphabetically. sample = 'Run-through-the-jungle' buffer_zone = sample.split("-") buffer_zone.sort(key=str.casefold) result='' for word in buffer_zone: if word==buffer_zone[-1]: result = result+word else: result=result+word+"-" print(result)
true
5ad636481a085eac73c53d1e4552488c5d8ee518
sanjay2610/InnovationPython_Sanjay
/Python Assignments/Task3/ques3and4.py
377
4.28125
4
#Write a program to get the sum and multiply of all the items in a given list. list1= [1,4,7,2] sum_total = 0 mul = 1 for num in list1: sum_total +=num mul *=num print("Sum Total of all elements: ", sum_total) print("Product of all the elements in the list", mul) print("Largest number in the list: ", max(list1)) print("Smallest number in the list: ", min(list1))
true
48eb98880e53c60893014a48660a8b3f80939240
trriplejay/CodeEval
/python3/rollercoaster.py
1,269
4.3125
4
import sys if __name__ == '__main__': if sys.argv[1]: try: file = open(sys.argv[1]) except IOError: print('cannot open', sys.argv[1]) else: """ loop through the file, read one line at a time, turn it into a python list, then call upper or lower on alternating characters. Use a boolean toggle to do so. If the character is non-alpha, don't toggle, but still add it to the output string. """ for line in file: toggle = True finalline = "" # calling list turns the string into a list of characters for letter in list(line.strip()): if letter.isalpha(): if toggle: finalline += letter.upper() toggle = False else: finalline += letter.lower() toggle = True else: # don't toggle if its not an alphabetical character finalline += letter print(finalline) else: print("no input file provided")
true
dc787b60b21add5ec63daed3e9d36b2a08248d3c
trriplejay/CodeEval
/python3/simplesorting.py
1,149
4.125
4
import sys if __name__ == '__main__': """ given a list of float values, sort them and print them in sorted order """ if sys.argv[1]: try: file = open(sys.argv[1]) except IOError: print('cannot open', sys.argv[1]) else: """ loop through the file, read a line, strip it, split it by space, convert each item to a float so that the list can be sorted, convert each item back to a string so that then can be joined and printed as a single string """ for line in file: print( " ".join( # space between each number ['{:0.3f}'.format(x) for x in # back to formatted str sorted( # sort the floats map( # convert to floats float, line.strip().split(" ") #strip n split ) ) ] ) ) else: print("no input file provided")
true
178bb73f18ceb91470aefacac4f346f1e7a160ca
DLatreyte/dlatreyte.github.io
/premieres-nsi/chap-01/1ère Spé NSI/Chap. 7 - Dessins avec Turtle/exo9.py
2,460
4.1875
4
import turtle def rectangle(tortue: "Turtle", longueur: int, largeur: int) -> None: """ Trace un rectangle de longueur et largeur passées en argument grâce à la tortue (elle-même passée en argument). Les position et direction de la tortue ne sont pas modifiées. À l'issue du tracé la tortue se retrouve au point de départ, avec la même direction. """ for i in range(2): tortue.forward(longueur) tortue.left(90) tortue.forward(largeur) tortue.left(90) def trace_rectangle(tortue: "Turtle", x: int, y: int, longueur: int, largeur: int) -> None: """ Déplace la souris à la position (x, y) puis trace un rectangle de longueur et largeur passées en argument. (x, y) est le coin inférieur gauche du rectangle. """ tortue.penup() tortue.goto(x, y) tortue.pendown() rectangle(tortue, longueur, largeur) def main(): """ Fonction principale. Initialisation des variables et appel des autres fonctions. """ # Paramètres de l'animation largeur_aire_jeu = 800 longueur_aire_jeu = 800 largeur_carre = 100 x_rect = -(longueur_aire_jeu - largeur_carre) y_rect = -largeur_carre //2 pas = 10 # de combien augment l'abscisse entre deux animations # Création de la fenetre pour l'animation fenetre = turtle.Screen() fenetre.setup(longueur_aire_jeu + 50, largeur_aire_jeu + 50) fenetre.bgcolor("black") # Création de la tortue pour tracer les limites de l'animation tortue1 = turtle.Turtle() tortue1.speed(0) tortue1.color("white") tortue1.hideturtle() # Tracé des limites trace_rectangle(tortue1, -longueur_aire_jeu // 2, -largeur_aire_jeu // 2, longueur_aire_jeu, largeur_aire_jeu) # Création de la tortue pour l'animation tortue2 = turtle.Turtle() tortue2.speed(0) tortue2.color("white") tortue2.hideturtle() # On prend en main le rafraichissement # fenetre.tracer(0) # Animation while x_rect <= longueur_aire_jeu // 2: tortue2.clear() trace_rectangle(tortue2, x_rect, y_rect, largeur_carre, largeur_carre) # fenetre.update() # affichage() x_rect += pas # Ferme la fenêtre avec un click sur l'espace de jeu turtle.exitonclick() main()
false
d65d85f6fad4f12e8ec52f2e77a9cc77b80c7cd2
DLatreyte/dlatreyte.github.io
/premieres-nsi/chap-01/1ère Spé NSI/Chap. 7 - Dessins avec Turtle/exo1.py
905
4.1875
4
import turtle def trace_rectangle(tortue: "Turtle", longueur: int, largeur: int) -> None: """ Dessine à l'écran à l'aide de la tortue passée en argument un rectangle de longueur et largeurs passées en argument. Le dessin est effectué à partir de la position de la tortue lorsque la fonction est appelée. """ for i in range(2): tortue.forward(longueur) tortue.left(90) tortue.forward(largeur) tortue.left(90) def main(): """ Fonction principale qui initialise toutes les variables et appelle toutes les autres. """ tortue_1 = turtle.Turtle() tortue_2 = turtle.Turtle() longueur = 300 largeur = 200 trace_rectangle(tortue_1, longueur, largeur) trace_rectangle(tortue_2, longueur // 3, largeur // 3) turtle.exitonclick() # Empêche la fenêtre de se fermer automatiquement à la fin du tracé main()
false
354467448ca6536c7e875bdd4447d807cbf04258
go4Mor4/My_CodeWars_Solutions
/7_kyu_String_ends_with?.py
493
4.1875
4
''' Instructions Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). Examples: solution('abc', 'bc') # returns true solution('abc', 'd') # returns false ''' #CODE def solution(frase, final): final = final[::-1] frase = frase[::-1] for i in range(len(final)): if final[i] == frase[i] and len(final) <= len(frase): continue else: return False break return True
true
8ed5b0e9361b907f3d90601bcd216e2e795f6ee1
morbidlust/pythonCrashCourse
/ch2/math.py
880
4.6875
5
#Adding print(2+3) #Subtracting print(2/3) #Multiplication print(2*4) #Division print(2/4) #Exponent print(3**3) #3 to the power of 3, aka 27 #Don't forget the order of operations matter! print(2+3*4) # 3*4 =12 + 2 = 14 #Use parenthesis if needed to set the order as intended) print((2+3)*4) # 2+3=5*4=20 #In Python any number with a decimal is a float, it will convert on it's own but it's best to include a decimal if that's what you want #Python3 handles this automatically but Python2 will not return the decimal values unless you've set the right types print(5/2) # This works and gives the right answer as it converted the result to a float of 2.5, Python2 would return 2 as the answer print(5.0/2) # Making sure my result will be in float due to the 5.0, Python2 would correctly return 2.5 as the answer here.
true
05afbea5731b30a155bd2b2ce6e1c2c98d1c4855
archambers/Data_Structures_And_Algorithms
/Misc/fibonacci.py
1,534
4.125
4
def naive_fibonacci(n: int) -> int: # Natural approach to recursive fibonacci function. if n <= 1: return n return naive_fibonacci(n - 1) + naive_fibonacci(n - 2) def iterative_fibonacci(n: int) -> int: # Bottom-up iterative approach first = 0 second = 1 for _ in range(n): first, second = second, first + second return first def better_fibonacci(n: int) -> int: # Does fibonacci with a single recursive call. # Makes time-complexity O(n) def _internal(n): if n <= 1: return (n, 0) (a, b) = _internal(n - 1) return (a + b, a) return _internal(n)[0] def memoized_fibonacci(n: int) -> int: # simple memoization of naive fibonacci implementation memo = {0: 0, 1: 1} def _internal(n): if n not in memo: memo[n] = memoized_fibonacci(n - 1) + memoized_fibonacci(n - 2) _internal(n) return memo[n] def better_fibonacci_memoized(n: int) -> int: # simple memoization of improved recursive fibonacci memo = {0: 0, 1: 1} def _internal(n: int): if n in memo: return memo[n], memo[n - 1] else: memo[n], memo[n - 1] = _internal(n - 1) return (memo[n] + memo[n - 1], memo[n]) return _internal(n)[0] def Memoize(function): memo = {} def _wrapper(param): if param not in memo: memo[param] = function(param) return memo[param] return _wrapper decorated_fib = Memoize(naive_fibonacci)
false
4d30cb1c0922cc09aa18f76f70393bdb624e4f65
kkeefe/py_Basic
/hello_py_stuff/self_test.py
1,085
4.34375
4
<<<<<<< HEAD # stuff to write as a silly test bench of py code to place in other note sections.. # use of a map function as applied to a lambda function # make some function you want my_func = lambda x: x ** x # lets make a map for this function sequence = [1, 2, 3] my_map = list(map(my_func, sequence)) print(my_map) # filter function, removes items from a list for which func returns false. sequence_2 = [1,2,3] is_odd = lambda x : ( x % 2 ) my_filter = list(filter(is_odd, sequence_2)) print(my_filter) ======= # stuff to write as a silly test bench of py code to place in other note sections.. # use of a map function as applied to a lambda function # make some function you want my_func = lambda x: x ** x # lets make a map for this function sequence = [1, 2, 3] my_map = list(map(my_func, sequence)) print(my_map) # filter function, removes items from a list for which func returns false. sequence_2 = [1,2,3] is_odd = lambda x : ( x % 2 ) my_filter = list(filter(is_odd, sequence_2)) print(my_filter) >>>>>>> ef1fa5f03d0dc522c35426b67da3caeb06e5339c
true
1819a769a857c24fa11e9af79f503f160ed0e61d
isheebo/ShoppingLister
/shoppinglister/models/user.py
2,089
4.125
4
from datetime import datetime class User: """ A user represents a person using the Application""" def __init__(self, name, email, password): self.name = name self.email = email self.password = password # a mapping of ShoppingList IDs to ShoppingList names self.shoppinglist_names = dict() self.shoppinglists = dict() # a mapping of shopping list items def create_shoppinglist(self, shop_list): """ Adds a ShoppingList to a specified user profile. """ if shop_list.list_id in self.shoppinglists or shop_list.name in self.shoppinglist_names.values(): return False self.shoppinglists[shop_list.list_id] = shop_list self.shoppinglist_names[shop_list.list_id] = shop_list.name return True def delete_shoppinglist(self, list_id): """ Deletes a shopping list from a specified user profile. :param list_id is the id of the ShoppingList to be deleted """ is_deleted = False if list_id in self.shoppinglists: del self.shoppinglists[list_id] del self.shoppinglist_names[list_id] is_deleted = True return is_deleted def edit_shoppinglist(self, list_id, new_name, notify_date): """ Edits the name and the notify_date of an already existing shopping list :returns True if the edit is successful. False otherwise """ if list_id in self.shoppinglists: old_list = self.shoppinglists[list_id] old_list.name = new_name old_list.notify_date = notify_date old_list.date_modified = datetime.now().strftime("%Y-%m-%d %H:%M") return True return False def get_shoppinglist(self, list_id): """ Searches a specified user profile for the specified ShoppingList ID. :returns ShoppingList if list_id exists else None """ if list_id in self.shoppinglists: # returns a list of Item objects return self.shoppinglists[list_id] return None
true
3b2b3340575fde0709fe7b8632c0f48d202ff814
MokahalA/ITI1120
/Lab 8 Work/magic.py
2,219
4.25
4
def is_square(m): '''2d-list => bool Return True if m is a square matrix, otherwise return False (Matrix is square if it has the same number of rows and columns''' for i in range(len(m)): if len(m[i]) != len(m): return False return True def magic(m): '''2D list->bool Returns True if m forms a magic square Precondition: m is a matrix with at least 2 rows and 2 columns ''' if(not(is_square(m))): # if matrix is not square return False # return False #Condition 1 merged_list=[] for o in m: merged_list += o for l in range(len(merged_list)): for k in range(l+1,len(merged_list)): if merged_list[l] == merged_list[k]: return False #Condition 2 diagonal1=0 diagonal2=0 col_sum=0 row_sum=0 c=len(m[0])-1 for i in range(len(m)): for j in range(len(m[i])): if i == j: diagonal1 = diagonal1 + m[i][j] for r in range(len(m)): diagonal2 = diagonal2 + m[r][c] c=c-1 for a in range(0,1): for b in range(0,len(m)): row_sum=row_sum + m[a][b] for e in range(0,1): for f in range(0,len(m[0])): col_sum=col_sum + m[f][e] if col_sum == row_sum and diagonal1 == diagonal2: return True else: return False # main # TESTING OF magic functions # this should print True m0=[[2,7, 6],[9,5,1],[4,3,8]] print(magic(m0)) # this should print True m1 = [[16,3,2,13], [5,10,11,8],[9,6,7,12], [4,15,14,1]] print(magic(m1)) # this should print False. Why? Which condition imposed on magic squares is not true for m3 m2 = [[1,2,3,4], [5,6,7,8],[9,10,11,12], [13,14,15,16]] print(magic(m2)) #this should print False. Why? Which condition imposed on magic squares is not true for m3 m3 = [[1,1],[1,1]] print(magic(m3)) # #this should print False. Why? Which condition imposed on magic squares is not m3 = [[1,1],[1,1],[1,2]] print(magic(m3))
true
bfd26facfdcd3a54f02140cca999585e22eff7da
MokahalA/ITI1120
/Lab 11 Work/Lab11Ex4.py
1,044
4.3125
4
def is_palindrome_v2(s): """(str) -> bool Return whether or not a string is a palindrome. While ignoring letters not of the english alphabet """ #Just 1 letter so its a palindrome if len(s) <= 1: return True #First letter is not in the alphabet if not s[0].isalpha(): return is_palindrome_v2(s[1:]) #Last letter is not in the alphabet if not s[-1].isalpha(): return is_palindrome_v2(s[:-1]) # Comparing first and last letter to see if they are the same. if s[0].casefold() != s[-1].casefold(): return False return is_palindrome_v2(s[1:-1]) #test print(is_palindrome_v2("A man, a plan, a canal -- Panama!")) # True print(is_palindrome_v2("Go hang a salami, I'm a lasagna hog")) # True print(is_palindrome_v2("Madam, I'm Adam")) # True print(is_palindrome_v2("Madam, I'm")) # False print(is_palindrome_v2('blurb')) # False print(is_palindrome_v2('a')) # True print(is_palindrome_v2('Anna')) # True
true
d851be7bee0b67d5d7a9f5dc04ab37a46155390d
MokahalA/ITI1120
/Lab 11 Work/Lab11Ex3.py
521
4.21875
4
def is_palindrome(s): """(str) -> bool Return whether or not a string is a palindrome. """ if len(s) <= 1: return True if s[0].lower() != s[-1].lower(): return False return is_palindrome(s[1:-1]) #test print(is_palindrome('blurb')) #False print(is_palindrome('a')) #True print(is_palindrome('anna')) #True print(is_palindrome('Anna')) #True print(is_palindrome("A man, a plan, a canal -- Panama!")) #False print(is_palindrome("Madam, I'm Adam")) #False
false
5fc4e6f7732929cb1442da206a315a974555f5cf
Mamuntheprogrammer/Notes
/Pyhton_snippet/HackerRankString.py
2,110
4.3125
4
# Python_365 # Day-26 # Python3_Basics # Python Data Types : String # Solving String related problems: (src : hackerrank) # Problem title : sWAP cASE """ Problem description : You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. Input and Output example : input : Www.HackerRank.com Output : wWW.hACKERrANK.COM """ # Solution 1 : def swap_case(s): d = '' for x in s: if (x.isupper()==True): d+=x.lower() else: d+=x.upper() return d print(swap_case("Hello moZur")) # Solution 2: print(''.join(list(map(lambda x: x.upper() if x.islower() else x.lower(),"Hello moZur")))) PyGems.com https://www.facebook.com/pygems # Python_365 # Day-27 # Python3_Basics # Python Data Types : String # Solving String related problems: (src : hackerrank) # Problem title :String Split and Join """ Problem description : You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. Sample Input: this is a string Sample Output: this-is-a-string """ def split_and_join(line): return "-".join(line.split(" ")) split_and_join("this is a string") PyGems.com https://www.facebook.com/pygems # Python_365 # Day-28 # Python3_Basics # Python Data Types : String # Solving String related problems: (src : hackerrank) # Problem title : Find a string #hackerrank #python """ Problem description : In this challenge, the user enters a string and a substring. You have to print the number of times that the substring occurs in the given string. String traversal will take place from left to right, not from right to left. Sample Input: ABCDCDC CDC Sample Output : 2 """ def count_substring(a, b): count=0 for x in range(len(a)-len(b)+1): if a[x:x+len(b)]==b: count+=1 return count count_substring("ABCDCDC","CDC") Output : 2 PyGems.com https://www.facebook.com/pygems
true
972eea4d5a9c74cd3a9aae9e35c3037ce8d68a46
Sukhrobjon/Hackerrank-Challanges
/interview_kit/Sorting/bubble_sort.py
660
4.28125
4
def count_swaps(arr): """ Sorts the array with bubble sort algorithm and returns number of swaps made to sort the array """ count = 0 swapped = False while swapped is not True: swapped = True for j in range(len(arr)-1): if arr[j] > arr[j + 1]: arr[j], arr[j+1] = arr[j+1], arr[j] count += 1 swapped = False print(arr) # return count print("Array is sorted in {} swaps.".format(count)) print("First Element: {}".format(arr[0])) print("Last Element: {}".format(arr[len(arr) - 1])) arr = [5, 2, 4, 1, 3] (count_swaps(arr))
true
c77f6ee57e3500c56f4c64d920b343b600b9d1ea
Sukhrobjon/Hackerrank-Challanges
/ProblemSolving/plus_minus.py
718
4.15625
4
def plus_minus(arr): ''' print out the ratio of positive, negative and zero items in the array, each on a separate line rounded to six decimals. ''' # number of all positive numbers in arr positive = len([x for x in arr if x > 0]) # number of all negative numbers in arr negative = len([x for x in arr if x < 0]) # number of zeros in arr zero = len([x for x in arr if x == 0]) total = len(arr) precision = [positive, negative, zero] for i in precision: # prints out the float 6 decimal points even it ends with 0s print("{:.6f}".format(round(i/total, 6))) arr = [-4, 3, -9, 0, 4, 1] plus_minus(arr) ''' Output : 0.500000 0.333333 0.166667 '''
true
cf5900bc9115c2054ca19965281cd0ef2f1c4b93
Sukhrobjon/Hackerrank-Challanges
/interview_kit/reverse_list.py
1,076
4.4375
4
# Create a function that takes a list # Create an empty list # Iterate through the old list # Get the last index of the old list # Append to the new list # Return the new list # Shiv Toolsidass ''' 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 a b c d e f g -9 -9 -9 1 1 1 0 -9 0 4 3 2 -9 -9 -9 1 2 3 0 0 8 6 6 0 0 0 0 -2 0 0 0 0 1 2 4 0 -63, -34, -9, 12, -10, 0, 28, 23, -27, -11, -2, 10, 9, 17, 25, 18 0 4 3 1 8 6 6 ''' example_list = [0, 1, 2, 3] def reverse_list(old_list): new_list = [] for index in range(len(old_list)): new_index = len(old_list) - 1 - index new_list.append(old_list[new_index]) return new_list print(reverse_list(example_list)) # # Your previous Python 2 content is preserved below: # # def say_hello(): # print 'Hello, World' # # for i in xrange(5): # say_hello() # # # # # # Your previous Plain Text content is preserved below: # # # # ''' # # Given a list, return a reversed version of the list. # # # # [1,2,3,4,5] # # [5,4,3,2,1] # # # # # # ''' # # #
false
28a48c5b770cefdfb0dbc15828a9810d18cf27e5
RicardoAugusto-RCD/exercicios_python
/exercicios/ex058.py
672
4.28125
4
# Melhore o jogo do desafio 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai # tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. import random numeroUsuario = int(input('Digite um número entre 0 e 10: ')) numeroPc = random.randint(0,10) tentativaUsuario = 1 while numeroUsuario != numeroPc: print('Tente novamente!') numeroUsuario = int(input('Digite um número entre 0 e 10: ')) tentativaUsuario += 1 print('O computador "pensou" no número {} e você acertou!!!'.format(numeroPc)) print('Você conseguiu acertar com {} tentativas'.format(tentativaUsuario))
false
de583ba447a373cebea3725955037e02b13d7e04
RicardoAugusto-RCD/exercicios_python
/exercicios/ex041.py
708
4.1875
4
# A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua # categoria, de acordo com a idade: # Até 9 anos: MIRIM. # Até 14 anos: INFANTIL. # Até 19 anos: JUNIOR. # Até 25 anos: SÊNIOR. # Acima: MASTER. from datetime import date anoAtual = date.today().year anoNascimento = int(input('Digite o ano do nascimento: ')) idade = anoAtual - anoNascimento print('Atleta com {} anos.'.format(idade)) if idade <= 9: print('Categoria: Mirim.') elif idade <= 14: print('Categoria: Infantil.') elif idade <= 19: print('Categoria: Junior.') elif idade <= 25: print('Categoria: Sênior.') else: print('Categoria: Master.')
false
848bb33a7961ed442c6e1622bec6cd9cabb21221
RicardoAugusto-RCD/exercicios_python
/exercicios/ex059a.py
1,638
4.1875
4
# Crie um programa que leia dois valores e mostre um menu na tela: # [1] Somar # [2] Multiplicar # [3] Maior # [4] Novos números # [5] Sair do programa # Seu programa deverá realizar a operação solicitada em cada caso. print('►◄' * 20) n1 = int(input('Primeiro valor: ')) print('►◄' * 20) n2 = int(input('Segundo Valor: ')) print('►◄' * 20) opcao = 0 while opcao != 5: print('►◄' * 20) print(''' ► 1 ◄ Somar ► 2 ◄ Multiplicar ► 3 ◄ Maior ► 4 ◄ Novos Números ► 5 ◄ Sair do Programa''') print('►◄' * 20) opcao = int(input('Digite sua opção ►►►►► ')) print('►◄' * 20) if opcao == 1: soma = n1 + n2 print('A soma entre {} + {} é {}'.format(n1, n2, soma)) elif opcao == 2: multiplica = n1 * n2 print('A multiplicação de {} x {} é {}'.format(n1, n2, multiplica)) elif opcao == 3: if n1 > n2: maior = n1 print('Entre {} e {} o maior é {}'.format(n1, n2, maior)) elif n2 > n1: maior = n2 print('Entre {} e {} o maior é {}'.format(n1, n2, maior)) else: print('Os valores {} e {} são iguais'.format(n1, n2)) elif opcao == 4: print('►◄' * 20) n1 = int(input('Primeiro valor: ')) print('►◄' * 20) n2 = int(input('Segundo Valor: ')) print('►◄' * 20) elif opcao == 5: print('Saindo...') else: print('Opção Inválida...Tente Novamente...') print('►◄' * 20) print('Fim do programa! Volte Sempre!') print('►◄' * 20)
false
1b0a92c3b053416b530452f5509c978220d29e10
RicardoAugusto-RCD/exercicios_python
/exercicios/ex095.py
1,708
4.15625
4
# Aprimore o Desafio 093 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do # aproveitamento de cada jogador. jogador = dict() jogadorLista = list() while True: jogador['nome'] = '' jogador['gols'] = list() jogador['total'] = 0 jogador['nome'] = str(input('Nome do jogador? ')) partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for contador in range(0, partidas): golPartida = int(input(f'Quantos gols na {contador + 1}ª partida? ')) jogador['gols'].append(golPartida) jogador['total'] += golPartida jogadorLista.append(jogador.copy()) resposta = str(input('Quer continuar? [S/N] ')).strip().upper()[0] while resposta not in 'SN': print(' ► ERRO ◄ |Responda apenas S ou N|') resposta = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resposta == 'N': break print('—' * 50) print(f'{"cod":<3}|{"nome":<15}|{"gols":<15}|{"total":<5}') print('—' * 50) for i, v in enumerate(jogadorLista): print('{:<3}|{:15}|{:15}|{:<5}'.format(i, v['nome'], '{}'.format(v['gols']), v['total'])) print('—' * 50) while True: print('—' * 50) dadosJogador = int(input('Mostrar dados de qual jogador? [999 interrompe] ')) print('—' * 50) if dadosJogador == 999: break else: if dadosJogador < len(jogadorLista): print(f'LEVANTAMENTO DO JOGADOR {jogadorLista[dadosJogador]["nome"]}') for c, v in enumerate(jogadorLista[dadosJogador]['gols']): print(f'No {c + 1}º jogo, fez {v} gols') else: print('Posição Inválida') continue
false
a5a8f8de8bc33c63123e9af60ef88222df0add72
RicardoAugusto-RCD/exercicios_python
/exercicios/ex093.py
1,066
4.15625
4
# Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e # quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será # guardado em um dicionário, incluindo o total de gols feitos durante o campeonato. jogador = dict() jogador['nome'] = str(input('Nome do jogador? ')) jogador['gols'] = list() jogador['total'] = 0 partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for contador in range(0, partidas): golPartida = int(input(f'Quantos gols na {contador + 1}ª partida? ')) jogador['gols'].append(golPartida) jogador['total'] += golPartida print('—' * 50) print(f'{jogador}') print('—' * 50) for k, v in jogador.items(): print(f'O campo {k} tem o valor {v}') print('—' * 50) print(f'O jogador {jogador["nome"]} jogou {partidas} partidas') for contador in range(0, partidas): print(f'→ Na partida {contador + 1} fez {jogador["gols"][contador]} gols') print(f'Foi um total de {jogador["total"]} gols')
false
7b905d6a127cd3076cba642a7b40eb5fd3503288
blu3h0rn/AI4I_DataCamp
/07_Cleaning_Data/reg_ex.py
626
4.125
4
import re # Write the first pattern # A telephone number of the format xxx-xxx-xxxx. You already did this in a previous exercise. pattern1 = bool(re.match(pattern='\d{3}-\d{3}-\d{4}', string='123-456-7890')) print(pattern1) # Write the second pattern # A string of the format: A dollar sign, an arbitrary number of digits, a decimal point, 2 digits. pattern2 = bool(re.match(pattern='\$\d*\.\d{2}', string='$123.45')) print(pattern2) # Write the third pattern # A capital letter, followed by an arbitrary number of alphanumeric characters. pattern3 = bool(re.match(pattern='\[A-Z]\w*', string='Australia')) print(pattern3)
true
c9267081ab2a317066a7d5881eaac862579d2bbe
justin-tt/euler
/19.py
2,298
4.25
4
# approach is to run a loop for every day starting from 1 Jan 1901 until 31 Dec 2000 # have a dictionary that holds every day of the week with a list that appends every single date as the loop runs # have a way to read the list of sundays and parse how many "firsts" of the month. # create a number of days generator for each month def is_leap_year(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False assert is_leap_year(1700) is False assert is_leap_year(1800) is False assert is_leap_year(1900) is False assert is_leap_year(2000) is True assert is_leap_year(2012) is True def days_in_month(year, month): leap_year = is_leap_year(year) no_of_days_in_month = { 1: 31, 2: 29 if leap_year else 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31, } return no_of_days_in_month[month] assert days_in_month(2024, 2) is 29 assert days_in_month(2000, 2) is 29 assert days_in_month(1900, 2) is 28 class Date: def __init__(self, date, month, year): self.date = date self.month = month self.year = year def __str__(self): return f'{self.date} {self.month} {self.year}' a = Date(1, 12, 1988) # print(a) b = Date(1, 12, 1988) f = Date(1, 4, 2000) c = [a, b, f] # filtering how many firsts of the month there are in this list d = list(filter(lambda x: x.date == 1, c)) print(len(d)) # create a loop to generate dictionary of days with dates # 1 = monday, 7 = sunday days = {} for i in range(1,8): days[i] = [] print(days) start_day = 1 # 1 Jan 1900 is a monday start_day = 2 # 1 Jan 1901 is a tuesday total_days = 0 for year in range(1901, 2001): for month in range(1, 13): for day in range(1, days_in_month(year, month) + 1): days[start_day].append(Date(day, month, year)) start_day += 1 total_days += 1 if start_day == 8: start_day = 1 print(days) print(start_day) print(total_days) print(days[7]) print(len(list(filter(lambda x: x.date == 1, days[7]))))
false
58c508b8b8a9f6a4935555649c91148fb0f7511c
ricardomachorro/PracticasPropias
/PythonEnsayo/Python6.py
791
4.5
4
#Otro tipo de dato que existe en python y que sirve mucho para bucles #es el tipo de dato range, ya que esta es una coleccion ordenada de numeros que los puede #controlar estricturas como el for #se declara con la palabra reservada range: #si se le pone solo un parametro este se toma como valor maximo rang1 = range(6) for i in rang1: print(i) print("//////////////////////") #si se le ponen dos parametros se toma el primero com valor minimo, y el ultimo como el maximo rang2 = range(2,5) for i in rang2: print(i) print("//////////////////////") #si se le ponen tres parametros se toma el primero com valor minimo,el segundo como valor maximo # y el ultimo como el salto que se da entre numeros rang3 = range(3,19,3) for i in rang3: print(i) print("///////////////////////")
false
19cbe0a02f0a73643b7a2ee1545536af3600fc95
ricardomachorro/PracticasPropias
/PythonEnsayo/Python14.py
2,605
4.40625
4
import math, cmath, operator #Algunas operaciones aritmeticas de python se pueden lograr o es necesario los modulos math,cmath u operator print("\nOperaciones aritmeticas de python con modulos math, cmath y operator\n") #Un ejemplo de estas formas son: print("\nLa division\n") #La division print("\nOperator para divisiones flotantes\n") print(operator.truediv(3,4))#Para divisiones flotantes print("\nOperator para divisiones enteras\n") print(operator.floordiv(4,3))#Para divisiones enteras print("\nLa Suma\n") #Suma a,b = 1,2 print("\nOperator para suma \n") print(operator.add(a,b))#Suma usando el modulo operator #Sumando de manera rapida a un variable print("\nSuma rapida \n") print(a) a += 2 print(a) #Una forma de hacer la suma parecida a " += " con el modulo operator print("\nSuma rapida con modulo Operator \n") print(operator.iadd(a,b)) #Exponenciacion print("\nExponenciacion\n") #Para elevar una base a un exponente en Python normalmente se hace simplemente asi: print("Exponenciacion rapida") print(2**3) print("Exponenciacion rapida 2") print(pow(2,3)) #tambien se puede hacer raices o exponentes fraccionarios print(8**(1/3)) print(pow(8,(1/3))) #Raiz cuadrada print("Raiz cuadrada") print("Raiz cuadrada normal con math") print(math.sqrt(4)) print("Raiz cuadrada con numeros complejos con cmath") print(cmath.sqrt(4+5j)) #Tambien se puede poner exponenciacion en base e con exp print("Exponenciacion base e") print(math.exp(0)) print(math.exp(1)) #Tambien se puede usar fucniones trigonometricas print("Funciones trigonometricas") print(math.sin(1))#Esta recibe y devuelve parametros en radianes print(math.cos(1)) print(math.tan(1)) print(math.atan(math.pi)) print(math.acos(.67)) print(math.asin(.67)) #Tambien se puede usar el teorema de pitagoras print("Teorema de pitagoras con 3 y 4 como catetos") print(math.hypot(3,4)) #Se puede transformar grados a redianes y en reversa print("Radianes:1 a Grados") print(math.degrees(1)) print("Grados: 57.29577951308232 a radianes") print(math.radians(57.29577951308232)) #Tambien se pueden acortar elementos o funciones print("\nAcortar elementos \n") #Adicion a,b,c = 1,2,3 c += b print(c) #Resta a -= c print (a) #Multiplicacion b *= c print(b) #Division a /= c print(a) #Division entera b //= a print(b) #Modulo c %= b print(c) #Exponenciacion a **= c print(b) #Tambien se puede usar logaritmos print("Tambien se puede usar logaritmos\n") print(math.log(100,10)) #Por default es base e print(math.log(3)) #Tmabien hay variantes base 2 y 10 print(math.log2(6)) print(math.log10(40))
false
6f8e0716bad3366dfa3e8ed5157500ac48c4f838
gustavo-detarso/engenharia_de_software
/concluidas/logica_de_programacao_e_algoritmos/Aula_2/c2_e4.py
423
4.25
4
# Desenvolva um algoritmo que converta uma temperatura em Celsius (C) para Fahrenheit (F). # Passo 1: criando as strings # Definição do que o algoritmo se propõe: print('Conversor de Celsius para Fahrenheit') celsius = float(input('Digite a temperatura em graus Celsius (ºC): ')) conversao = (9*celsius)/5+32 # Passo 2: Montando o algoritmo print('A temperatura de {}ºC corresponde a {}ºF' .format(celsius,conversao))
false
ca9e85d8c6d8304ad3d041cd663ada46603f1aa8
enriquerojasv/ejercicios_python
/Práctica 7/p07e11.py
479
4.21875
4
# Enrique Rojas - p07e11 # Escribe un programa que te pida una frase, y pase la frase como parámetro a una función. Ésta debe devolver si es palíndroma o no , y el programa principal escribirá el resultado por pantalla. def palindromo(a): alreves = "" for i in range(len(a)-1,-1,-1): alreves += (a[i]) if alreves == a: return f"{a} es palíndromo" else: return f"{a} no es palíndromo" a = input("Escribe una frase: ") print (palindromo(a))
false
aff8db65519cf6c95930facf7e4a9f5794c261cc
0neMiss/cs-sprint-challenge-hash-tables
/hashtables/ex4/ex4.py
598
4.21875
4
def has_negatives(list): """ YOUR CODE HERE """ dict = {} result = [] #for each number for num in list: # if the number is positive if num > 0: #set the value of the dictionary at the key of the number equal to the number dict[num] = num #iterate through the list again and run the abs function if the positive version of each nevgative number exists in the list result = [abs(num) for num in list if num * -1 in dict] return result if __name__ == "__main__": print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
true
5ecf9ec9ff9ec7eafcda9f8c61fdb6493c338743
Andytrento/zipf
/bin/my_ls.py
606
4.1875
4
""" List the files in a given directory with a given suffix""" import argparse import glob def main(args): """Run the program""" dir = args.dir if args.dir[-1] == "/" else args.dir + "/" glob_input = dir + "*." + args.suffix glob_output = sorted(glob.glob(glob_input)) for item in glob_output: print(item) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("dir", type=str, help="Directory") parser.add_argument("suffix", type=str, help="File suffix (e.g py, sh)") args = parser.parse_args() main(args)
true
52ae75e0bce95f04fe589a792ad38d11d08d2487
St1904/GB_python_1
/lesson3/easy.py
1,474
4.5
4
# Постарайтесь использовать то, что мы прошли на уроке при решении этого ДЗ, # вспомните про zip(), map(), lambda, посмотрите где лучше с ними, а где они излишни! # Задание - 1 # Создайте функцию, принимающую на вход Имя, возраст и город проживания человека # Функция должна возвращать строку вида "Василий, 21 год(а), проживает в городе Москва" def str_about(name, age, city): return f'{name}, {age} год(а), проживает в городе {city}' print(str_about('Vasya', 21, 'Moscow')) # Задание - 2 # Создайте функцию, принимающую на вход 3 числа, и возвращающую наибольшее из них def max_num(x, y, z): return max(x, y, z) print(max_num(1, 2, 3)) print(max_num(1, 3, 3)) print(max_num(1, 8, 3)) print(max_num(8, 2, 3)) # Задание - 3 # Создайте функцию, принимающую неограниченное количество строковых аргументов, # верните самую длинную строку из полученных аргументов def max_len_str(*args): return max(args, key=len) print(max_len_str('khfej', 'jfi', '', 'ojfiejfk', '12', 'oijofpmlffe'))
false
2ab455fa9d6bbba20a4c15c1e178ae6193255d43
Pavithjanum/PythonModule1
/Module1-Q2.py
490
4.40625
4
# 2 # Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. # Hint: In case of input data being supplied to the question, it should be assumed to be a console input. import sys inputs = sys.argv print('Raw inputs from user',inputs[1:]) String_inputs = inputs[1:] String_outputs = sorted(String_inputs) print(String_outputs) print('Your Strings in Sorted order:') for string in String_outputs: print(string)
true
1ea69e0bbaac2100ec90d25e707a3072a51e1b4d
faiderfl/algorithms
/recursion/Palindrome.py
708
4.15625
4
def reverse(string)->str: """[summary] Args: string ([type]): [description] Returns: str: [description] """ len_string= len(string) if len_string==1: return string[0] else: return string[len_string-1]+ reverse(string[:len_string-1]) def is_palindrome(string)->bool: return True if string == reverse(string) else False def is_palindrome2(string): if len(string) == 0: return True if string[0] != string[len(string)-1]: return False return is_palindrome2(string[1:-1]) print(is_palindrome('awesome')) print(is_palindrome('tacocat')) print(is_palindrome2('awesome')) print(is_palindrome2('tacocat'))
false
d21cef2ba8aa4d53ebff4a8e94996731b3b3ae91
A01377744/Mision-03
/calculoDelPagoDeUnTrabajador.py
1,098
4.15625
4
#Autor: Alejandro Torices Oliva #Es un programa que lee las horas normales y horas extra trabajadas en una semana #e imprime el pago por cada una y el pago total. #Calcula el pago para las horas normales. def calcularPagoNormal(horasNormales, pagoPorHora): pagoNormal = horasNormales * pagoPorHora return pagoNormal #Calcula el pago para las horas extras. def calcularPagoExtra(horasExtras, pagoPorHora): pagoExtra = horasExtras * (pagoPorHora * 1.85) return pagoExtra #Es la función principal, obtiene los datos e imprime las soluciones. def main(): horasNormales = int(input("Teclea las horas normales trabajadas: ")) horasExtras = int(input("Teclea las horas extras trabajadas: ")) pagoPorHora = int(input("Teclea el pago por hora: ")) pagoNormal = calcularPagoNormal(horasNormales, pagoPorHora) pagoExtra = calcularPagoExtra(horasExtras, pagoPorHora) pagoTotal = pagoNormal + pagoExtra print(""" Pago normal: $%.2f""" % pagoNormal) print("Pago extra: $%.2f" % pagoExtra) print("-----------------------") print("Pago total: $%.2f" % pagoTotal) main()
false