blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
fe703b6364b1835b433410da896166adaf129654
elijahsk/cpy5python
/practical04/q05_count_letter.py
509
4.1875
4
# Name: q05_count_letter.py # Author: Song Kai # Description: Find the number of occurences of a specified letter # Created: 20130215 # Last Modified: 20130215 # value of True as 1 and value of False as 0 def count_letter(string,char): if len(string)==1: return int(string[0]==char) return int(string[0]==char)+count_letter(string[1:],char) # input the string and char string=input("Enter a string: ") char=input("Enter a specific char you want to serach: ") # print print(count_letter(string,char))
true
66488b56ef595a4ce86f4936262ce9c47c2030d0
elijahsk/cpy5python
/practical03/q08_convert_milliseconds.py
813
4.1875
4
# Name: q08_convert_milliseconds.py # Author: Song Kai # Description: Convert milliseconds to hours,minutes and seconds # Created: 20130215 # Last Modified: 20130215 # check whether the string can be converted into a number def check(str): if str.isdigit(): return True else: print("Please enter a proper number!") return False # the convert process def convert_ms(n): string="" # calculate the number of hours string+=str(n//3600000) n%=3600000 # calculate the number of minutes string+=":"+str(n//60000) n%=60000 # calculate the number of seconds string+=":"+str(n//1000) return string # input the time n=input("Enter the time in milliseconds: ") while not check(n): n=input("Enter the time in milliseconds: ") # print print(convert_ms(int(n)))
true
6dce3c4965f32564385623ffb9ef1528a180a016
siddk/hacker-rank
/miscellaneous/python_tutorials/mobile_number.py
469
4.125
4
""" mobile_number.py Given an integer N, and N phone numbers, print YES or NO to tell if it is a valid number or not. A valid number starts with either 7, 8, or 9, and is 10 digits long. """ n = input() for i in range(n): number = raw_input() if number.isdigit(): number = int(number) if (len(str(number)) == 10) and (int(str(number)[0]) in [7,8,9]): print "YES" else: print "NO" else: print "NO"
true
b90e89de330807f02410bee5f6faa321376c0a26
siddk/hacker-rank
/miscellaneous/python_tutorials/sets.py
684
4.3125
4
""" sets.py You are given two sets of integers M and N and you have to print their symmetric difference in ascending order. The first line of input contains the value of M followed by M integers, and then N and N integers. Symmetric difference is the values that exist in M or N but not in both. """ m = input() m_lis = raw_input() n = input() n_lis = raw_input() m_list = m_lis.split() m_list = list(map(int, m_list)) n_list = n_lis.split() n_list = list(map(int, n_list)) m_set = set(m_list) n_set = set(n_list) intersect = m_set.intersection(n_set) for i in intersect: m_set.remove(i) n_set.remove(i) union = m_set.union(n_set) for i in sorted(union): print i
true
cbb33de2960bed126ad694a163a15aca703bc40a
askwierzynska/python_exercises
/exercise_2/main.py
702
4.125
4
import random print('-----------------------------') print('guess that number game') print('-----------------------------') print('') that_number = random.randint(0, 50) guess = -1 name = input("What's your name darling? ") while guess != that_number: guess_text = input('Guess number between 0 an 50: ') guess = int(guess_text) if guess < that_number: print('{0}Your guess of {1} was too low. Keep trying!'.format(name, guess)) elif guess > that_number: print('{0}Your guess of {1} was too big. Keep trying!'.format(name, guess)) else: print('Huge congrats {0}! {1} was that number!'.format(name, guess)) print('') print('done. thanks ;)')
true
1607baf5554044a4870c9402e79c1ae0867faa0e
obayomi96/Algorithms
/Python/simulteneous_equation.py
786
4.15625
4
# solving simultaneous equation using python print('For equation 1') a = int(input("Type the coefficient of x = \n")) b = int(input("Type the coefficient of y = \n")) c = int(input("Type the coefficient of the constant, k = \n")) print("For equation 2") d = int(input("Type the coefficient of x = \n")) e = int(input("Type the coefficient of y = \n")) f = int(input("Type the coefficient of the constant, k = \n")) def determinant(): return((a*e) - (b*d)) x = determinant() # print(x) to output: a*e - b*d def cofactors(): return((e*c) + (-1 * d * f)) / determinant(), ((-1 * b * c) + (a * 5)) / determinant() z = cofactors() #print(z) output: (e*c) + (-1 * d * f) / determinant(), ((-1 * b * c) + (a * 5)) / determinant() print("Answer = (x,y)") print(cofactors())
true
9b6acd981eb913452c020d5bd66aac70f329fd6c
heyhenry/PracticalLearning-Python
/randomPlays.py
1,096
4.15625
4
import random randomNumber = random.randint(1, 10) randomNumber = str(randomNumber) print('✯ Welcome to the guessing game ✯') username = input('✯ Enter username: ') guessesTaken = 0 print(username, 'is it? \nGreat name! \nOkay, the rules are simple.\n') print('⚘ You have 6 attempts. \n⚘ Enter a number ranging between 1 - 10. \n⚘ Heed the warnings after each attempt.\n') while guessesTaken < 6: guess = input('Guess the number:') guess = str(guess) guessesTaken += 1 if guess < randomNumber: print("A little higher...") elif guess > randomNumber: print("A little lower...") elif guess == randomNumber: print("\nCongratulations! You guessed it right!") break if guess != randomNumber: print('\nOh no! You ran out of attempts. The correct number was', randomNumber + '.\n') print('Taking you to the stats screen now...\n') print('\nStats: ') print('The actual number: ', randomNumber, '\nLast guess: ', guess, '\nAttempts taken: ', guessesTaken) print('\nThank you. Come again ( ͡👁️ ͜ʖ ͡👁️)✊!')
true
de5a9fdc707edaee79994df174ca98968d07228c
ivy-liu/re-Automation
/0311_01.py
980
4.34375
4
#算术运算符 a=21 b=10 c=0 c=a+b print("a+b=",c) c=a//b print("a//b=",c)#取整除 - 返回商的整数部分(向下取整) c=a/b print("a/b=",c) c=a**b print("a**b=",c) c=a*b print("a*b=",c) #条件语句,判断 jin=90 qu=75 ts=(jin-qu)/qu*100 print('小明成绩提升百分点:%.1f' % ts+'%') flag=False name="xiaoming" if name=='小明'or'xiaoming': flag=True print('是的,对,我是小明') else: print('不是') num=5 if num==3: print('我是3') elif num==4: print('我是4') else: print('我好困,我是5') num=9 if num >=0 and num <=10: print('我大于等于0小于等于10\n') height=1.68 weight=53 bmi=weight/(height**2) #体重除以身高的平方 print('bmi=',bmi) if bmi<18.5: print('过轻') elif bmi>=18.5 and bmi <=25: print('正常') elif bmi>25 and bmi<=28: print('过重') elif bmi>28 and bmi <=32: print('肥胖') elif bmi>32: print('严重肥胖') else: print('异常')
false
39f360ae4828952b4da6249bacfadda4671911d2
aryashah0907/Arya_GITSpace
/Test_Question_2.py
454
4.40625
4
# 3 : Write a Python program to display the first and last colors from the following list. # Example : color_list = ["Red","Green","White" ,"Black"]. # Your list should be flexible such that it displays any color that is part of the list. from typing import List color_list = ["Red", "Green", "White", "Black", "Pink", "Azure", "Brown"] newColorlist = color_list[0] finalColorlist = color_list[len(color_list) - 1] print(newColorlist + finalColorlist)
true
ac9de1f5797579203874fef062220415cc7a3c13
cvhs-cs-2017/sem2-exam1-LeoCWang
/Function.py
490
4.375
4
"""Define a function that will take a parameter, n, and triple it and return the result""" def triple(n): n = n * 3 return (n) print(triple(5)) """Write a program that will prompt the user for an input value (n) and print the result of 3n by calling the function defined above. Make sure you include the necessary print statements and address any issues with whitespace. """ def usertriple(n): n = 3 *n return n print (usertriple(float(input('Please enter a number'))))
true
1ce5245bebfd0e12605f9a1fac47a3fd985c080c
luffysk/coderesources
/python/1.base/11.str_format.py
255
4.28125
4
# 格式化输出字符串有三种方式 # 第一种 a = 'str' b = 'str2' print('a is ' + a + ', b is ' + b) # 第二种 a = 's1' b = 's2' print('a is %s, b is %s' % (a, b)) # 第三种, 推荐此种 a = 'fstr' b = 'fstr2' print(f'a is {a}, b is {b}')
false
9040c3eeb0c6b4bf7cdff293644912e879a07eee
dexterpengji/practice_python
/fishC/038_class_inherit.py
919
4.15625
4
# -*- coding: utf-8 -* import random as r class Fish: def __init__(self): self.x = 100 self.y = 100 def move(self): self.x += r.randint(-5,5) self.y += r.randint(-5,5) print("position",self.x,self.y) class Gold_Fish(Fish): def __init__(self): #Fish.__init__(self) # way 1 super().__init__() # way 2 - the better one self.size = 20 def inflate(self): self.size += 10 def shrink(self): self.size -= 10 class Carp_Fish(Fish): pass class Salmon_Fish(Fish): pass class Shark_Fish(Fish): def __init__(self): #Fish.__init__(self) # way 1 super().__init__() # way 2 - the better one self.hungry = True def eat(self): if self.hungry: print("Hungry...") self.hungry = False else: print("Full...") class Gold_Shark_Fish(Gold_Fish, Shark_Fish): # 多重继承可能会出现不可预料的bug,尽量不要使用 pass
false
1712892d8d87ea7ffc0532bedeb31afd088c47bc
damianserrato/Python
/TypeList.py
693
4.46875
4
# Write a program that takes a list and prints a message for each element in the list, based on that element's data type. myList = ['magical unicorns',19,'hello',98.98,'world'] mySum = 0 myString = "" for count in range(0, len(myList)): if type(myList[count]) == int: mySum += myList[count] elif type(myList[count]) == str: myString += myList[count] myString = "String: " + myString print myString mySum = "Sum: " + myString if mySum > 0 and len(myString) > 1: print "The list you entered is of a mixed type" elif mySum > 0 and len(myString) == 0: print "The list you entered is of an integer type" else: print "The list you entered is of a string type"
true
2d5273b86616f827bed2a4496b4fe6854acf5ac3
damianserrato/Python
/FindCharacters.py
388
4.15625
4
# Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character. word_list = ['hello','world','my','name','is','Anna'] char = 'o' newList = [] for count in range(0, len(word_list)): for c in word_list[count]: if c == "o": newList.append(word_list[count]) print newList
true
8a833841f94024fa0c6e5185a78d4b404716ba8c
Hikareee/Phyton-exercise
/Programming exercise 1/Area of hexagon.py
266
4.3125
4
import math #Algorithm #input the side #calculate the area of the hexagon #print out the area #input side of hexagon S = eval(input("input the side of the hexagon: ")) #area of the hexagon area=(3*math.sqrt(3)*math.pow(S,2))/2.0 #print out the area print (area)
true
51150a87bda43b7f1a9c1787005001a034b73232
rvrn2hdp/informatorio2020
/FuncionesComp/func9.py
1,182
4.21875
4
'''Ejercicio 9: ¿Un string representan un entero? En este ejercicio escribirá una función llamada es_entero que determina si los caracteres en una cadena representan un número entero válido. Al determinar si un string representa un número entero, debe ignorar cualquier espacio en blanco inicial o final. Una vez que se ignora este espacio en blanco, una cadena representa un número entero si su longitud es al menos 1 y solo contiene dígitos, o si su primer carácter es + o - y el primer carácter va seguido de uno o más caracteres, todos los cuales son dígitos Escriba un programa principal que lea una cadena del usuario e informe si representa o no un número entero. Sugerencia: Puede encontrar los métodos lstrip, rstrip y / o strip para cadenas útiles cuando complete este ejercicio. ''' def es_entero(cadena): cadena = cadena.strip(' ') print(cadena) if len(cadena) > 0 or (cadena[0] == '+' or cadena[0] == '-') and cadena[0:].isdigit(): return "Es un número entero." else: return "No es un número entero." def principal(): micadena = input("Ingrese un numero: ") print(es_entero(micadena)) principal()
false
9d0d3dd9396aa1135f9d3f84d5d6ba7c76c3cffa
rvrn2hdp/informatorio2020
/FuncionesComp/func6.py
731
4.125
4
'''Ejercicio 6: Centrar una cadena en la terminal Escriba una función que tome una cadena de caracteres como primer parámetro y el ancho de la terminal en caracteres como segundo parámetro. Su función debe devolver una nueva cadena que consta de la cadena original y el número correcto de espacios iniciales para que la cadena original aparezca centrada dentro del ancho proporcionado cuando se imprima. No agregue ningún carácter al final de la cadena. Incluya un programa principal que use su función.''' def centrar_cadena(cadena, ancho): return cadena.center(ancho, ' ') def funcion_principal(): miCadena = input("Ingrese una cadena: ") print(centrar_cadena(miCadena, 79)) funcion_principal()
false
2580e93a9665e26326c9478950be89a27e1709e0
rvrn2hdp/informatorio2020
/Desafios1/desafiorepetitiva5.py
1,350
4.125
4
"""Se está desarrollando un sistema de control de vehículos desde donde se han tirado restos de basura a la vía pública. Para ello la ciudad cuenta con sistemas de monitoreo de patentes que devuelve 3 letras y un valor numérico de 5 dígitos a la Central con el siguiente significado: 3 letras: Correspondientes a la patente. Del valor numérico: Los 3 primeros números corresponden a la patente El 4 número indica 1 - Tiró basura a la vía pública 0 - No tiró basura a la vía pública El 5 número indica 1 - Ya había sido multado el vehículo 0 - Vehículo sin multas. Deberás informar cantidad de vehículos observados, cantidad de vehículos que han tirado basura y porcentaje de éstos que ya habían sido multados. """ print("\nBienvenido\n") tiro_basura = 0 ya_multado = 0 analizadas = 0 while True: patente = input("\nIngrese la patente: ") analizadas += 1 if patente [6] == '1': tiro_basura += 1 if patente [7] == '1': ya_multado += 1 seguir = int(input("\n1 - Siguiente patente\n2 - Terminar de analizar patentes\n")) if seguir == 2: break print("\nSe analizaron", analizadas, "patentes") print(tiro_basura, "tiraron basura") print("y", ya_multado, "ya habían sido multados.\n")
false
7633108013a04f6e5ef0c4287c65002bd12e70c6
rvrn2hdp/informatorio2020
/FuncionesComp/func10.py
1,074
4.21875
4
'''Ejercicio 10: Precedencia del operador Escriba una función llamada precedencia que devuelve un número entero que representa la precedencia de un operador matemático. Una cadena que contiene el operador se pasará a la función como su único parámetro. Su función debe devolver 1 para + y -, 2 para * y /, y 3 para ˆ. Si la cadena que se pasa a la función no es uno de estos operadores, la función debería devolver -1. Incluya un programa principal que lea un operador del usuario y muestre la precedencia del operador o un mensaje de error que indique que la entrada no era un operador. En este ejercicio, se usa ˆ para representar la exponenciación, en lugar de la elección de Python de **, para facilitar el desarrollo de la solución. ''' def precedencia(s): if s == '+' or s == '-': return 1 elif s == '*' or s == '/': return 2 elif s == '^': return 3 else: return -1 def principal(): print("precedencia del operador ingresado:") s = input() print (precedencia(s)) principal()
false
e74ddfcc4b04789ce051adee50598c592547d7fb
congyingTech/Basic-Algorithm
/medium/hot100/2-add-two-numbers.py
2,341
4.25
4
""" 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。 请你将两个数相加,并以相同形式返回一个表示和的链表。 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。 输入:l1 = [2,4,3], l2 = [5,6,4] 输出:[7,0,8] 解释:342 + 465 = 807. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-two-numbers 解题思路: 每个数位都是逆序的,所以可以从头遍历两个链表,把两个链表的值相加 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p1 = l1 p2 = l2 res_Node = ListNode() head_res = res_Node temp = 0 while p1 or p2 or temp: if p1 and not p2: res_val = p1.val + temp elif not p1 and p2: res_val = p2.val + temp elif p1 and p2: res_val = p1.val + p2.val + temp elif not p1 and not p2 and temp: res_val = temp else: break temp = 0 if res_val < 10: res = ListNode(res_val) else: res = ListNode(res_val % 10) temp = res_val // 10 head_res.next = res head_res = head_res.next if p1 and p1.next: p1 = p1.next else: p1 = None if p2 and p2.next: p2 = p2.next else: p2 = None res = res_Node.next return res if __name__ == "__main__": s = Solution() l1 = [9, 9, 9, 9, 9, 9, 9] l2 = [9, 9, 9, 9] l1_node = ListNode(l1[0]) p1 = l1_node l2_node = ListNode(l2[0]) p2 = l2_node for i in range(1, len(l1)): p1.next = ListNode(l1[i]) p1 = p1.next for i in range(1, len(l2)): p2.next = ListNode(l2[i]) p2 = p2.next s.addTwoNumbers(l1_node, l2_node)
false
070b897a2f9365ae21c150490d0949a4b3d47960
congyingTech/Basic-Algorithm
/data_structure/3.directed-graph.py
1,586
4.21875
4
# encoding:utf-8 """ 问题描述:有向(可能有环图)图 """ class DirectedGraph(object): def __init__(self,vertices): self.vertices = vertices self.graph = [[0]*self.vertices for i in range(self.vertices)] def add_edges(self, src, dest): self.graph[src][dest] = 1 def print_graph(self): for i in range(self.vertices): connect_vertices = [] for j in range(self.vertices): if self.graph[i][j] == 1: connect_vertices.append(j) print('head:{}, connect with {}'.format(i, connect_vertices)) # 深度搜索(backtrack)find path def print_path(self, i, temp, res): """ i是第i个点 """ if len(set(temp))<len(temp): print('闭环:{}'.format(temp)) inner_res = temp[:] res.append(inner_res) return if 1 not in self.graph[i] and temp not in res : print(temp) inner_res = temp[:] res.append(inner_res) return for j in range(self.vertices): if self.graph[i][j] == 1: temp.append(j) self.print_path(j, temp, res) temp.pop() if __name__ == "__main__": v_num = 4 graph = DirectedGraph(v_num) graph.add_edges(0,1) graph.add_edges(0,2) graph.add_edges(1,3) graph.add_edges(2,3) graph.add_edges(2,0) graph.print_graph() temp = [0] res = [] graph.print_path(0, temp, res) print(res)
false
30698c43e3ce59495f42fb6d0bff2c5cce4a525b
congyingTech/Basic-Algorithm
/getOffer/17.merge-two-sorted-lists.py
2,753
4.125
4
# encoding:utf-8 """ 问题描述:合并两个上升排序的链表,使之合并后有序 解决方案:递归的方案, 非递归的方案:先比较第一个节点,节点小的那一个作为主链表,把循环遍历另一条链表,把其中的元素插入到主链表中 在主链表设置两个指针:mainHead/mainNext,次链表只有secondHead一个指针,做次链表单节点插入主链表的动作。 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution1(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 if l1.val < l2.val: mainHead = l1 secondHead = l2 else: mainHead = l2 secondHead = l1 mainNext = mainHead.next mergeHead = mainHead while secondHead: if not mainNext: mainHead.next = secondHead break # 当第二个linkedlist的node的值小于主list的时候,把其插入主list if secondHead.val<mainNext.val: mainHead.next = secondHead secondHead = secondHead.next mainHead.next.next = mainNext mainHead = mainHead.next else: mainHead = mainHead.next mainNext = mainNext.next return mergeHead def printLinkList(self, head): while head: print(head.val) head = head.next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 if l1.val<l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 def printLinkList(self, head): while head: print(head.val) head = head.next if __name__ == "__main__": s = Solution() l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) # l1.next.next.next = ListNode(7) # l1.next.next.next.next = ListNode(9) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) # l2.next.next.next = ListNode(8) # # 递归的方法 # l = s.mergeTwoLists(l1, l2) # s.printLinkList(l) s1 = Solution1() l1 = s1.mergeTwoLists(l1,l2) s1.printLinkList(l1)
false
0fd112e01e2545fb78af3211f1f1d12dd0159d24
Lukhanyo17/Intro_to_python
/Week7/acronym.py
538
4.15625
4
def acronym(): acro = '' ignore = input("Enter words to be ignored separated by commas:\n") title = input("Enter a title to generate its acronym:\n") ignore = ignore.lower() ignore = ignore.split(', ') title = title.lower() titleList = title.split() titleList.append("end") for k in range(len(titleList)-1): if(not titleList[k] in ignore): word = titleList[k] acro += word[0] print("The acronym is: "+acro.upper()) acronym()
true
a51357020c8422857735e9092ed7b35fa3992060
samvelarakelyan/ACA-Intro-to-python
/Practicals/Practical5/Modules/pretty_print.py
667
4.25
4
def simple_print(x:int): """ The function gets an integer and just prints it. If type of function argument isn't 'int' the function print 'Error'. """ if isinstance(x,int): print("Result: %d" %x) else: print("Error: Invalid parametr! Function parametr should be integer") def pro_print(x:int): """ The function gets an integer and just prints it. If type of function parametr isn't 'int' the function print 'Error'. """ if isinstance(x,int): print("The result of the operation is %d" %x) else: print("Error: Invalid parametr! Function parametr should be integer")
true
76e9d759bbee0884ff88b287e491ae097580f41b
imsk003/Python
/reverse_words.py
224
4.25
4
def reverseWords(input): inputWords = input.split(" ") inputWords=inputWords[-1::-1] output = ' '.join(inputWords) return output if __name__ == "__main__": input = 'hello python' print(reverseWords(input))
false
6ca26100985fc23524b13578e97cde54a42f2f70
twhay/Python-Scripts
/Dice Simulator.py
509
4.21875
4
# Python Exercise - Random Number Generation - Dice Generator # Import numpy as np import numpy as np # Set the seed np.random.seed(123) # Generate and print random float r = np.random.rand() print(r) # Use randint() to simulate a dice dice = np.random.randint(1,7) print(dice) # Starting step step = 50 # Finish the control construct if dice <= 2 : step = step - 1 elif dice <=5 : step = step + 1 else : step = step + np.random.randint(1,7) # Print out dice and step print(dice) print(step)
true
6065b6d6ecb45e18d532a5a3bcf765851e97d1eb
iMeyerKimera/play-db
/joins.py
929
4.34375
4
# -*- coding: utf-8 -*- # joining data from multiple tables import sqlite3 with sqlite3.connect("new.db") as connection: c = connection.cursor() # retrieve data c.execute(""" SELECT population.city, population.population, regions.region FROM population, regions WHERE population.city = regions.city ORDER BY population.city ASC """) rows = c.fetchall() for r in rows: print "City: " + r[0] print "Population: " + str(r[1]) print "Region: " + r[2] print # Take a look at the SELECT statement. # Since we are using two tables, fields in the SELECT statement must adhere # to the following format: table_name.column_name (i.e., population.city ). # In addition, to eliminate duplicates, as both tables include the city name, # we used the WHERE clause as seen above. # finally organize the outputted results and clean up the code so it’s more compact
true
2909e9da710ee8da8f33f9c67687f697c8db7385
lorenanicole/abbreviated-intro-to-python
/exercises/guessing_game_two.py
1,143
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import random """ ITERATION THREE: Now that you have written a simple guessing game, add some logic in that determines if the game is over when either: * user has correctly guesses the number * user has reached 5 guesses Let's use two functions: * is_guess_correct * display_user_output STRETCH: In the case user loses, show correct number. In the case user wins tell them how many guesses it took for them to win. Both situations show user all guesses they made. """ def display_user_output(num_to_guess, guessed_num): """ :param: guessed_num - number user guessed :param: num_to_guess - number the user has to guess :returns string saying if the guess is too high, too low, or match """ def is_guess_correct(num_to_guess, guessed_num): """ :param: guessed_num - number user guessed :param: num_to_guess - number the user has to guess :returns boolean True if correct else False """ game_not_over = False turns = 0 while game_not_over: # TODO: ask for user input # determine what message to show user # determine if guess is correct
true
b9a599544b5dbf2e0cf855cfe9b848f3fec098eb
juliakyrychuk/python-for-beginners-resources
/final-code/oop/car.py
777
4.25
4
class Car: """Represents a car object.""" def __init__(self, colour, make, model, miles=0): """Set initial details of car.""" self.colour = colour self.make = make self.model = model self.miles = miles def add_miles(self, miles): """Increase miles by given number.""" self.miles += miles def display_miles(self): """print the current miles value.""" print( f'{self.make} {self.model} ({self.colour}) ' f'has driven {self.miles} miles.' ) astra = Car('Red', 'Vauxhall', 'Astra') astra.display_miles() astra.add_miles(100) astra.display_miles() prius = Car('Blue', 'Toyota', 'Prius', 1000) prius.display_miles() prius.add_miles(50) prius.display_miles()
true
70504fde426af3e446033709871f1d5219844539
Farmerjoe12/PythonLoanLadder
/pythonLoanLadder/model/Loan.py
1,234
4.1875
4
import numpy import math class Loan: """ A representation of a Loan from a financial institution. Loans are comprised of three main parts, a principal or the amount for which the loan is disbursed, an interest rate because lending companies are crooked organizations which charge you money for borrowing their money, and a term for which the repayment period is defined. Fields: name: A descriptive name for a loan interest_rate: The interest rate given by a lender (%5.34) principal: The amount of money that is lent term: the repayment period (in years) """ def __init__(self, name, interest_rate, principal): self._name = name self._interest_rate = interest_rate self._principal = principal def get_interest_rate(self): return self._interest_rate def get_principal(self): return self._principal def get_name(self): return self._name def to_string(self): result = "Loan Name: {}\n".format(self._name) result += "Principal: {}\n".format(self._principal) result += "Interest Rate: %{}".format(self._interest_rate) return result
true
0a0558e50b0bd8f9f41348596aae5c06ac66c7e7
LIZETHVERA/python_crash
/chapter_7_input_while/parrot.py
788
4.3125
4
message = input ("Tell me something, and i will repetar it back to you: ") print (message) name = input ("please enter your name: ") print ("hello, "+ name + "!") prompt = "If you tell us who you are, we can personalize the messages you see" prompt += "\nWhat is your first name?" name = input (prompt) print ("\nHello," + name + "!") prompt = "Tell me something, and i will repeat the message to you: " prompt += "\nEnter 'quit' to end the program. ?" message = "" while message != "quit": message = input (prompt) print (message) prompt = "Tell me something, and i will repeat the message to you: " prompt += "\nEnter 'quit' to end the program. ?" message = "" while message != "quit": message = input (prompt) if message != "quit": print (message)
true
f25f1e4333a6c8a4ef1f22eb18a430ad3be862ab
olsgaard/adventofcode2019
/day01_solve_puzzle1.py
801
4.5
4
""" Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2. For a mass of 1969, the fuel required is 654. For a mass of 100756, the fuel required is 33583. """ def calculate_fuel(mass): return int(mass / 3) - 2 assert calculate_fuel(12) == 2 assert calculate_fuel(14) == 2 assert calculate_fuel(1969) == 654 assert calculate_fuel(100756) == 33583 with open("input.txt01") as f: lines = f.readlines() result = sum([calculate_fuel(int(mass)) for mass in lines]) print(result)
true
a00d0f8ef6e6f6ba51524c3c0309ebe863ab9581
osmandi/programarcadegames
/Capítulo 4: Adivianzas con números aleatorios y bucles/ejemplos_de_while.py
1,633
4.21875
4
""" # Sample Python/Pygame Programs # Simpson College Computer Science # http://programarcadegames.com/ # http://simpson.edu/computer-science/ """ # Podemos emplear un bucle while allí donde, también, podríamos usar un bucle for: i = 0 while i < 10: print(i) i = i + 1 # Es lo mismo que: for i in range(10): print(i) # Es posible simplificar el código: # i=i+1 # Con lo siguiente: # i += 1 # Esto lo podemos hacer también con la resta y la multiplicación. i = 0 while i < 10: print(i) i += 1 # ¿Qué imprimiremos aquí? i = 1 while i <= 2 ** 32: print(i) i *= 2 # Una tarea muy habitual, es iterar hasta que el usuario realiza una petición de salida. salir = "n" while salir == "n": salir = input ("¿Quieres salir? ") # Existen diversas formas para salir de un bucle. Un operador booleano que dispare el evento es una # forma de conseguirlo. hecho = False while not hecho: salir = input ("¿Quieres salir? ") if salir == "s": hecho = True; ataca = input ("¿El elfo atacó al dragón? ") if ataca == "s": print("Mala elección, estás muerto.") hecho = True; valor = 0 incremento = 0.5 while valor < 0.999: valor += incremento incremento *= 0.5 print(valor) # -- Problemas habituales con los bucles while -- # El programador quiere hacer una cuenta atrás empezando en 10. # ¿Qué es lo que está mal, y cómo lo podemos arreglar? i = 10 while i == 0: print (i) i -= 1 # ¿Qué es lo que está mal en este bucle que intenta contar hasta 10? # ¿Qué sucederá cuando lo ejecutemos? i = 1 while i < 10: print (i)
false
77da7fdefd5a5ddc68ce5652094f4ad1b627d3a3
stefantoncu01/Pizza-project
/pizza_project.py
2,981
4.125
4
class Pizza: """ Creates a pizza with the attributes: name, size, ingredients """ def __init__(self, name, size): self.name = name self.size = size self.ingredients = None @property def price(self): """ Calculates the price based on size and ingredients """ price_per_ingredient = 3 size_price = { "small": 1, "medium": 1.2, "large": 1.5 } return size_price[self.size] * len(self.ingredients) * price_per_ingredient class VeganPizza(Pizza): """ Creates a vegan pizza by inheriting attributes from Pizza class """ def __init__(self, name, size): super().__init__(name, size) self.ingredients = ['tomato_sauce', 'pepper', 'olives'] class CarnivoraPizza(Pizza): """ Creates a carnivora pizza by inheriting attributes from Pizza class """ def __init__(self, name, size): super().__init__(name, size) self.ingredients = ['tomato_sauce', 'cheese', 'chicken', 'parmesan', 'spinach'] class PepperoniPizza(Pizza): """ Creates a pepperoni pizza by inheriting attributes from Pizza class """ def __init__(self, name, size): super().__init__(name, size) self.ingredients = ['tomato_sauce', 'cheese', 'salami', 'habanero_pepper'] class HawaiianPizza(Pizza): """ Creates a hawaiian pizza by inheriting attributes from Pizza class """ def __init__(self, name, size): super().__init__(name, size) self.ingredients = ['tomato_sauce', 'cheese', 'pineapple', 'coocked_ham', 'onion'] class Client: """ Creates a client with the attributes name, address, has_card(bool) """ def __init__(self, name, address, has_card=True): self.name = name self.address = address self.has_card = has_card class Order: """ Creates an order based on the Client class and products (a list of Pizza objects) """ def __init__(self, client, products): self.client = client self.products = products @property def total_price(self): """ Calculates the total price of the order based on products attributes. If the client has_card a 10% discount should be applied. """ price = sum([product.price for product in self.products]) if self.client.has_card: return price * 0.9 return price @property def invoice(self): """ Table formatted string containing all products associated with this order, their prices, the total price, and client information """ result ='\n'.join([f'{product.name} - {product.price}' for product in self.products]) result += f'\nThe total price is {self.total_price}! \nThe delivery will be in {self.client.address}!' return result
true
e378f29d1bd2dbf43f88f0a0d2333f811150be2f
scvetojevic1402/CodeFights
/CommonCharCount.py
660
4.15625
4
#Given two strings, find the number of common characters between them. #Example #For s1 = "aabcc" and s2 = "adcaa", the output should be #commonCharacterCount(s1, s2) = 3. #Strings have 3 common characters - 2 "a"s and 1 "c". def commonCharacterCount(s1, s2): num=0 s1_matches=[] s2_matches=[] for i in range(0,len(s1)): if i not in s1_matches: for j in range(0,len(s2)): if j not in s2_matches: if s1[i]==s2[j]: num+=1 s1_matches.append(i) s2_matches.append(j) break return num
true
c2d0e8489e7783edf1fc6a5548825a77da605e57
dayanandtekale/Python_Basic_Programs
/basics.py
1,303
4.125
4
#if-else statements: #score=int(input("Enter your score")) #if score >=50: # print("You have passed your exams") # print("Congratulations") #if score <50: # print("Sorry,You have failed Exam") #elif statements: #score=109 #if score >155 or score<0: # print("Your score is invalid") #elif score>=50: # print("You have passed your exam") # print("Congratulations!") #else: # print("Sorry,You have failed Exam") #while loop: #count= 5 #while count <=10: # print(count) # count= count + 1 #number = int(input("Enter a number: ")) #count = 1 #while count >= 10: # product = number * count # print(number, "x" ,count, "=", product) # count = count + 1 #for loop in python: #text = "Python" #for character in text: # print(character) #languages = ["English","French","German"] #for language in languages: # print(language) #count=1 #while count <= 5: # print(count) # count = count + 1 #using for loop in 1 sentence we get same op: #for count in range(1,6): # print(count) #for table of any number in (1-11) #number = int(input("Enter an integer: ")) #for count in range(1,11): # product = number * count # print(number, "X", count, "=", product)
true
49063cf5cbae4fc79e96e59d6dfd07178f16b211
cxdy/CSCI111-Group4
/project2/final.py
597
4.40625
4
# Find the distance between two points # Class: CSCI 111 - Intro to Computer Science # Group: Project Group 4 import math # Ask for the 2 xy coordinates x1 = float(input("Point #1 x-coord: ")) y1 = float(input("Point #1 y-coord: ")) x2 = float(input("Point #2 x-coord: ")) y2 = float(input("Point #2 y-coord: ")) # Square the difference between the (x2 - x1) vars and (y2 - y1) vars xMath = (x2 - x1) ** 2 yMath = (y2 - y1) ** 2 # Find the square root of the sum of the xMath and yMath vars squareRoot = math.sqrt(xMath + yMath) print(f"The distance between the two points is: {squareRoot}")
false
613a833ae062123c4f5a81af2e957fb28fea74cd
cxdy/CSCI111-Group4
/project1/GroupProect1 BH.py
1,054
4.40625
4
firstname1 = input("Enter a first name: ") college = input("Enter the name of a college: ") business = input("Enter the name of a business: ") job = input("Enter a job: ") city = input("Enter the name of a city: ") restaurant = input("Enter the name of a restaurant: ") activity1 = input("Enter an activity: ") activity2 = input("Enter another activity: ") animal = input("Enter a type of animal: ") firstname2 = input("Enter a different first name: ") store = input("Enter the name of a store: ") # Display the paragraph with all the inputs in the console print(f"There once lived a person named {firstname1} who recently graduated from {college}. After accepting a job with {business} as a(n) {job}, {firstname1} decided to first take a vacation to {city}. Upon arriving in {city}, {firstname1} planned to visit {restaurant} before enjoying an evening of {activity1} and {activity2}. The next day, {firstname1} adopted a(n) {animal} named {firstname2} found in front of an abandoned {store}. {firstname1} and {firstname2} lived happily ever after .")
true
10e396f5019fd198a588d543c6746a642867496c
DSR1505/Python-Programming-Basic
/04. If statements/4.05.py
309
4.15625
4
""" Generate a random number between 1 and 10. Ask the user to guess the number and print a message based on whether they get it right or not """ from random import randint x = randint(1,10) y = eval(input('Enter a number between 1 and 10: ')) if(x == y): print('You get it right') else: print('Try again')
true
4c590e8a0ff2058228a40e521d4dc31b1978ee9e
DSR1505/Python-Programming-Basic
/02. For loops/2.14.py
276
4.34375
4
""" Use for loops to print a diamond. Allow the user to specify how high the diamond should be. """ num = eval(input('Enter the height: ')) j = (num//2) for i in range(1,num+1,2): print(' '*j,'*'*i) j = j - 1 j = 1 for i in range(num-2,0,-2): print(' '*j,'*'*i) j = j + 1
true
1ddc261cf174c109583fd0ead1f537673d29090a
athirarajan23/luminarpython
/regular expression/validation rules/rules with eg.py
2,250
4.15625
4
#rules used for pattern matching # #1. x='[abc]' either a,b or c #eg: # import re # x="[abc]" # matcher=re.finditer(x,"abt cq5kz") # for match in matcher: # print(match.start()) # print(match.group()) #2. x='[^abc]' except abc #eg: # import re # x="[^abc]" # matcher=re.finditer(x,"abt cq5kz") # for match in matcher: # print(match.start()) # print(match.group()) #3. x='[a-z]' a to z ^ cap means that is not included #eg # import re # x="[a-z]" # matcher=re.finditer(x,"abt cq5kz") # for match in matcher: # print(match.start()) # print(match.group()) #eg with ^ # import re # x="[^a-z]" # matcher=re.finditer(x,"abt cq5kz") # for match in matcher: # print(match.start()) # print(match.group()) #4. x='[A-Z]' A TO Z # import re # x="[A-Z]" # matcher=re.finditer(x,"abt SC5kZ") # for match in matcher: # print(match.start()) # print(match.group()) #5.X="[a-zA-Z]" BOTH LOWER AND UPPERCASE ARE CHECKED import re x="[a-zA-Z]" matcher=re.finditer(x,"abtABIkz") for match in matcher: print(match.start()) print(match.group()) #6. X="[0-9]" # import re # x="[0-9]" # matcher=re.finditer(x,"ab1z7") # for match in matcher: # print(match.start()) # print(match.group()) #7.x="[a-zA-Z0-9]" # import re # x="[a-zA-Z0-9]" # matcher=re.finditer(x,"ab72ABIkz") # for match in matcher: # print(match.start()) # print(match.group()) #8.x='\s' check space # import re # x="\s" # matcher=re.finditer(x,"ab tAB Ikz") # for match in matcher: # print(match.start()) # print(match.group()) #9.x='\d' check the digits # import re # x="\d" # matcher=re.finditer(x,"ab7tAB12kz") # for match in matcher: # print(match.start()) # print(match.group()) #9. x='\D' except digits # import re # x="\D" # matcher=re.finditer(x,"ab001tAB5236Ikz") # for match in matcher: # print(match.start()) # print(match.group()) #10. x='\w' all words except special characters # import re # x="\w" # matcher=re.finditer(x,"ab %tAB @Ikz") # for match in matcher: # print(match.start()) # print(match.group()) #11.x='\W' for special characters # import re # x="\W" # matcher=re.finditer(x,"ab!!tAB@Ikz") # for match in matcher: # print(match.start()) # print(match.group())
false
af8f6a301de6b7bcf12dce96898944ec99928b6d
vickylee745/Learn-Python-3-the-hard-way
/ex30.py
925
4.46875
4
people = 30 cars = 40 trucks = 15 if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks.") else: print("We still can't decide.") if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's stay home then.") ''' or above decision process can be written:''' def what_to_take(people, cars, trucks): if trucks >= people and trucks < cars: print ("Alright take trucks") elif trucks < people and cars >= people: print ("not enough trucks, take cars") else: print ("Can't fit everyone") people = input("number of people: ") cars = input("number of cars: ") trucks = input("number of trucks: ") what_to_take(people, cars, trucks)
true
8684285a1e580d4249b60a838d4eec6bc85222db
kkashii/Python-NRS568
/Class 2/Challenge2.2.py
391
4.125
4
# List Overlap list_a = ['dog', 'cat', 'rabbit', 'hamster', 'gerbil'] list_b = ['dog', 'hamster', 'snake'] def overlap(list_a, list_b): list_c=[value for value in list_a if value in list_b] return list_c print(overlap(list_a, list_b)) for x in list_a: if x not in list_b: print(x) for y in list_b: if y not in list_a: print (y)
false
33dffd72dbc71e9bf6d0669e3570557c5102418d
Chyi341152/pyConPaper
/Concurrency/codeSample/Part4_Thread_Synchronuzation_Primitives/sema_signal.py
1,236
4.65625
5
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # sema_signal.py # # An example of using a semaphore for signaling between threads import threading import time done = threading.Semaphore(0) # Resource control. item = None def producer(): global item print("I'm the producer and I produce data.") print("Producer is going to sleep.") time.sleep(5) item = "Hello" print("Producer is alive. Signaling the consumer.") done.release() # Increments the count and signals waiting threads def consumer(): print("I'm a consumer and I want for date.") print("Consumer is waiting.") done.acquire() # Waits for the count is 0, otherwise decrements the count and continues print("Consumer got", item) t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start() t2.start() """ Semaphore Uses: 1. Resource control You can limit the number of threads performing certain operations.For example, performing database queries making network connections 2. Signaling Semaphores can be used to send "signals" between threads. For example, having one thread wake up another thread """
true
3df062d10ddff464e32ed814ddd2012dc97d326d
DataKind-DUB/PII_Scanner
/namelist.py
1,231
4.25
4
#!/usr/bin/python3 -i """This file contain functions to transform a list of names text file to a set """ def txt_to_set(filename): """(str) -> set() Convert a text file containing a list of names into a set""" res = set() with open(filename,'r') as f: for line in f: l = line.strip().split() for item in l: try: int(item[0]) except ValueError: res.add(item) return res def cleaned_txt_to_set(filename): """(str) -> set() Convert a cleaned text file containing a list of names into a set a clean text is formatted as a name each line Same effect as txt_to_set but quicker""" res = set() with open(filename,'r') as f: for line in f: res.add(line.strip()) return res def clean_txt(filename): """(str) -> None Rewrite a file with a list of name under the format name, pass line, name""" tmp = [] with open(filename,'r') as f: for line in f: l = line.split() for item in l: try: int(item[0]) except ValueError: tmp.append(item) with open(filename,'w') as f: for item in tmp: f.write(item+"\n") if __name__=="__main__": print(txt_to_set("Irish Name Dict with Number.txt")) print(cleaned_txt_to_set("Irish Name Dict with Number.txt"))
true
061f34d0ae2055ecaa8c26aaa5ef2d43dcb473cf
tzpBingo/github-trending
/codespace/python/tmp/strings.py
661
4.15625
4
""" 字符串常用操作 Version: 0.1 Author: 骆昊 Date: 2018-02-27 """ str1 = 'hello, world!' print('字符串的长度是:', len(str1)) print('单词首字母大写: ', str1.title()) print('字符串变大写: ', str1.upper()) # str1 = str1.upper() print('字符串是不是大写: ', str1.isupper()) print('字符串是不是以hello开头: ', str1.startswith('hello')) print('字符串是不是以hello结尾: ', str1.endswith('hello')) print('字符串是不是以感叹号开头: ', str1.startswith('!')) print('字符串是不是一感叹号结尾: ', str1.endswith('!')) str2 = '- \u9a86\u660a' str3 = str1.title() + ' ' + str2.lower() print(str3)
false
307b9a3b8ac5d9d65ad3c9a834cabab1b51c6c62
tzpBingo/github-trending
/codespace/python/tmp/example16.py
1,731
4.25
4
""" 魔术方法 如果要把自定义对象放到set或者用作dict的键 那么必须要重写__hash__和__eq__两个魔术方法 前者用来计算对象的哈希码,后者用来判断两个对象是否相同 哈希码不同的对象一定是不同的对象,但哈希码相同未必是相同的对象(哈希码冲撞) 所以在哈希码相同的时候还要通过__eq__来判定对象是否相同 """ class Student(): __slots__ = ('stuid', 'name', 'gender') def __init__(self, stuid, name): self.stuid = stuid self.name = name def __hash__(self): return hash(self.stuid) + hash(self.name) def __eq__(self, other): return self.stuid == other.stuid and \ self.name == other.name def __str__(self): return f'{self.stuid}: {self.name}' def __repr__(self): return self.__str__() class School(): def __init__(self, name): self.name = name self.students = {} def __setitem__(self, key, student): self.students[key] = student def __getitem__(self, key): return self.students[key] def main(): # students = set() # students.add(Student(1001, '王大锤')) # students.add(Student(1001, '王大锤')) # students.add(Student(1001, '白元芳')) # print(len(students)) # print(students) stu = Student(1234, '骆昊') stu.gender = 'Male' # stu.birth = '1980-11-28' print(stu.name, stu.birth) school = School('千锋教育') school[1001] = Student(1001, '王大锤') school[1002] = Student(1002, '白元芳') school[1003] = Student(1003, '白洁') print(school[1002]) print(school[1003]) if __name__ == '__main__': main()
false
9a049b0cd58d5c48f564591f9edb5ff6b19e1ae9
Ishita46/PRO-C97-NUMBER-GUESSING-GAME
/gg.py
551
4.25
4
import random print("Number Guessing Game") Number = random.randint(1,9) chances = 0 print("Guess a number between 1-9") while chances < 5: guess = int(input("Enter your guess")) if guess == Number: print("Congratulations you won!") break elif guess < Number: print("You loose, try to choose a higher number.",guess) else: print("Your guess was too high, guess a low number than that.",guess) chances += 1 if not chances < 5: print("You loose! The actual number is: ",Number)
true
36a5612ef360eeb868da742bc9f29f535cb3fb84
saparia-data/data_structure
/geeksforgeeks/maths/2_celcius_to_fahrenheit.py
852
4.5
4
""" Given a temperature in celsius C. You need to convert the given temperature to Fahrenheit. Input Format: The first line of input contains T, denoting number of testcases. Each testcase contains single integer C denoting the temperature in celsius. Output Format: For each testcase, in a new line, output the temperature in fahrenheit. Your Task: This is a function problem. You only need to complete the function CtoF that takes C as parameter and returns temperature in fahrenheit( in double). The flooring and printing is automatically done by the driver code. Constraints: 1 <= T <= 100 1 <= C <= 104 Example: Input: 2 32 50 Output: 89 122 Explanation: Testcase 1: For 32 degree C, the temperature in Fahrenheit = 89. def cToF(C): hints: 1) �F = �C x 9/5 + 32 """ coding="utf8" def cToF(C): return (C * 9/5) + 32 print(cToF(32))
true
795bc9954ddcd5e52ad3477bf197c5bedd9a9650
saparia-data/data_structure
/geeksforgeeks/linked_list/segregate_even_and_odd_nodes_in_linked_list_difficullt.py
2,808
4.15625
4
''' Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same. https://www.geeksforgeeks.org/segregate-even-and-odd-elements-in-a-linked-list/ ''' class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next def segregateEvenOdd(self): # Starting node of list having # even values. evenStart = None # Ending node of even values list. evenEnd = None # Starting node of odd values list. oddStart = None # Ending node of odd values list. oddEnd = None # Node to traverse the list. currNode = self.head while(currNode != None): val = currNode.data # If current value is even, add # it to even values list. if(val % 2 == 0): if(evenStart == None): evenStart = currNode evenEnd = evenStart else: evenEnd.next = currNode evenEnd = evenEnd.next # If current value is odd, add # it to odd values list. else: if(oddStart == None): oddStart = currNode oddEnd = oddStart else: oddEnd.next = currNode oddEnd = oddEnd.next # Move head pointer one step in # forward direction currNode = currNode.next # If either odd list or even list is empty, # no change is required as all elements # are either even or odd. if(oddStart == None or evenStart == None): return # Add odd list after even list. evenEnd.next = oddStart oddEnd.next = None # Modify head pointer to # starting of even list. self.head = evenStart llist = LinkedList() llist.push(11) llist.push(10) llist.push(9) llist.push(6) llist.push(4) llist.push(1) llist.push(0) llist.printList() llist.segregateEvenOdd() print("Linked list after re-arranging") llist.printList()
true
17d7ca663bf8697b79bd7824a49e561839818cf3
saparia-data/data_structure
/pepcoding/dynamic_programming/4_climb_stairs_with_minimum_moves.py
1,375
4.15625
4
''' 1. You are given a number n, representing the number of stairs in a staircase. 2. You are on the 0th step and are required to climb to the top. 3. You are given n numbers, where ith element's value represents - till how far from the step you could jump to in a single move. You can of-course fewer number of steps in the move. 4. You are required to print the number of minimum moves in which you can reach the top of staircase. Note -> If there is no path through the staircase print null. Sample Input: 10 3 3 0 2 1 2 4 2 0 0 Sample Output: 4 https://www.youtube.com/watch?v=d42uDPBOXSw&list=PL-Jc9J83PIiG8fE6rj9F5a6uyQ5WPdqKy&index=4 https://www.youtube.com/watch?v=Zobz9BXpwYE&list=PL-Jc9J83PIiG8fE6rj9F5a6uyQ5WPdqKy&index=5 ''' import sys def climbStairsWithMinMoves(arr): dp = [None] * (len(arr) + 1) dp[n] = 0 for i in range(n-1, -1, -1): minn = sys.maxsize j = 1 while(j <= arr[i] and i+j <= len(dp)): if(dp[i + j] != None): minn = min(minn, dp[i + j]) j += 1 if(minn != sys.maxsize): dp[i] = minn + 1 return dp[0] if __name__ == "__main__": arr = [3,3,0,2,1,2,4,2,0,0] n = 10 print(climbStairsWithMinMoves(arr))
true
fea46e295115747dfcc38e182eb865603b501e74
saparia-data/data_structure
/pepcoding/recursion/1_tower_of_hanoi.py
961
4.15625
4
''' 1. There are 3 towers. Tower 1 has n disks, where n is a positive number. Tower 2 and 3 are empty. 2. The disks are increasingly placed in terms of size such that the smallest disk is on top and largest disk is at bottom. 3. You are required to 3.1. Print the instructions to move the disks. 3.2. from tower 1 to tower 2 using tower 3 3.3. following the rules 3.3.1 move 1 disk at a time. 3.3.2 never place a smaller disk under a larger disk. 3.3.3 you can only move a disk at the top. sample input: 3 10 11 12 sample output: 1[10 -> 11] 2[10 -> 12] 1[11 -> 12] 3[10 -> 11] 1[12 -> 10] 2[12 -> 11] 1[10 -> 11] https://www.youtube.com/watch?v=QDBrZFROuA0&list=PL-Jc9J83PIiFxaBahjslhBD1LiJAV7nKs&index=12 ''' def toh(n, t1, t2, t3): if(n == 0): return toh(n-1, t1, t3, t2) print(str(n) + "[" + str(t1) + " -> " + str(t2) + "]") toh(n-1, t3, t2, t1) toh(3, 10, 11, 12)
true
60937f08311c74e6773fa09eaec056097efb9496
saparia-data/data_structure
/pepcoding/generic_tree/17_is_generic_tree_symmetric.py
1,776
4.1875
4
''' The function is expected to check if the tree is symmetric, if so return true otherwise return false. For knowing symmetricity think of face and hand. Face is symmetric while palm is not. Note: Symmetric trees are mirror image of itself. Sample Input: 20 10 20 50 -1 60 -1 -1 30 70 -1 80 -1 90 -1 -1 40 100 -1 110 -1 -1 -1 Sample Output: true https://www.youtube.com/watch?v=ewEAjK83ZVM&list=PL-Jc9J83PIiEmjuIVDrwR9h5i9TT2CEU_&index=39 https://www.youtube.com/watch?v=gn2ApElF2i0&list=PL-Jc9J83PIiEmjuIVDrwR9h5i9TT2CEU_&index=40 ''' class Node: def __init__(self): self.data = None self.children = [] def create_generic_tree(arr): root = Node() st = [] # create empty stack for i in range(len(arr)): if(arr[i] == -1): st.pop() else: t = Node() t.data = arr[i] if(len(st) > 0): st[-1].children.append(t) else: root = t st.append(t) return root def areMirror(root1, root2): if(len(root1.children) != len(root2.children)): return False for i in range(len(root1.children)): j = len(root1.children) - 1 - i c1 = root1.children[i] c2 = root2.children[j] if(areMirror(c1, c2) == False): return False return True def isSymmetric(root): return areMirror(root, root) # symmetric trees are mirror image of itself if __name__ == "__main__": arr = [10, 20, 50, -1, 60, -1, -1, 30, 70, -1, 80, -1, 90, -1, -1, 40, 100, -1, 110, -1, -1, -1] root = create_generic_tree(arr) print(root.data) print(isSymmetric(root))
true
008b19ff7efc7fc9be540903c086a792aed6c0d2
saparia-data/data_structure
/geeksforgeeks/maths/7_prime_or_not.py
1,297
4.34375
4
''' For a given number N check if it is prime or not. A prime number is a number which is only divisible by 1 and itself. Input: First line contains an integer, the number of test cases 'T'. T testcases follow. Each test case should contain a positive integer N. Output: For each testcase, in a new line, print "Yes" if it is a prime number else print "No". Your Task: This is a function problem. You just need to complete the function isPrime that takes N as parameter and returns True if N is prime else returns false. The printing is done automatically by the driver code. Constraints: 1 <= T <= 100 1 <= N <= 103 Example: Input: 2 5 4 Output: Yes No Explanation: Testcase 1: 5 is the prime number as it is divisible only by 1 and 5. Hints: Count the number of factors. If the factors of a number is 1 and itself, then the number is prime. You can check this optimally by iterating from 2 to sqrt(n) as the factors from 2 to sqrt(n) have multiples from sqrt(n)+1 to n. So, by iterating till sqrt(n) only, you can check if a number is prime. def isPrime(N): ''' import math def isPrime(N): if(N == 1): return True else: for i in range(2, int(math.sqrt(N)) + 1): if (N % i == 0): return False return True print(isPrime(9))
true
3fb0fefa594130bd865c342d60d0f7ff34127f7f
saparia-data/data_structure
/geeksforgeeks/linked_list/4_Insert_in_Middle_of_Linked_List.py
1,343
4.15625
4
''' Given a linked list of size N and a key. The task is to insert the key in the middle of the linked list. Input: The first line of input contains the number of test cases T. For each test case, the first line contains the length of linked list N and the next line contains N elements to be inserted into the linked list and the last line contains the element to be inserted to the middle. Output: For each test case, there will be a single line of output containing the element of the modified linked list. User Task: The task is to complete the function insertInMiddle() which takes head reference and element to be inserted as the arguments. The printing is done automatically by the driver code. Expected Time Complexity : O(N) Expected Auxilliary Space : O(1) Constraints: 1 <= T <= 100 1 <= N <= 104 Example: Input: 2 3 1 2 4 3 4 10 20 40 50 30 Output: 1 2 3 4 10 20 30 40 50 Explanation: Testcase 1: The new element is inserted after the current middle element in the linked list. Testcase 2: The new element is inserted after the current middle element in the linked list and Hence, the output is 10 20 30 40 50. ''' def insertInMid(head,new_node): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next new_node.next = slow.next slow.next = new_node
true
296acd0cb1655e3fd6d57e80b9bd72529ffb4ecc
saparia-data/data_structure
/geeksforgeeks/matrix/8_Boundary_traversal_matrix.py
2,384
4.34375
4
''' You are given a matrix A of dimensions n1 x m1. The task is to perform boundary traversal on the matrix in clockwise manner. Input: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1. The second line contains n1*m1 elements separated by spaces. Output: For each testcase, in a new line, print the boundary traversal of the matrix A. Your Task: This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code. Constraints: 1 <= T <= 100 1 <= n1, m1<= 30 0 <= arri <= 100 Examples: Input: 4 4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 3 4 12 11 10 9 8 7 6 5 4 3 2 1 1 4 1 2 3 4 4 1 1 2 3 4 Output: 1 2 3 4 8 12 16 15 14 13 9 5 12 11 10 9 5 1 2 3 4 8 1 2 3 4 1 2 3 4 Explanation: Testcase1: The matrix is: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5 Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8. Testcase 3: Boundary Traversal will be 1 2 3 4. Testcase 4: Boundary Traversal will be 1 2 3 4. hints: Traverse the top boundary first then the right boundary then the bottom boundary then the left boundary and print the elements simultaneously. ''' def BoundaryTraversal(a, n, m): """ a: matrix n: no. of rows m: no. of columns """ if(min(n,m) == 1): for row in a: print(*row, end = " ") return row_idx, col_idx = 0, 0 #print first row while(col_idx < m): print(a[row_idx][col_idx], end = " ") col_idx += 1 #print last column col_idx = m - 1 row_idx += 1 while(row_idx < n): print(a[row_idx][col_idx], end = " ") row_idx += 1 #print last row row_idx = n - 1 col_idx -= 1 while(col_idx > -1): print(a[row_idx][col_idx], end = " ") col_idx -= 1 #print first column row_idx -= 1 col_idx = 0 while(row_idx > 0): print(a[row_idx][col_idx], end = " ") row_idx -= 1 a = [ [1,2,3], [4,5,6], [7,8,9] ] n, m = 3, 3 BoundaryTraversal(a, n, m)
true
789288e7c8987df76436b463f7e8fa6f2d9b1a8a
saparia-data/data_structure
/geeksforgeeks/tree/6_height_of_binary_tree.py
698
4.125
4
''' Hint: 1. If tree is empty then return 0 2. Else (a) Get the max depth of left subtree recursively i.e., call maxDepth( tree->left-subtree) (a) Get the max depth of right subtree recursively i.e., call maxDepth( tree->right-subtree) (c) Get the max of max depths of left and right subtrees and add 1 to it for the current node. max_depth = max(max dept of left subtree, max depth of right subtree) + 1 (d) Return max_depth ''' def height(root): if(root is None): return 0 return (1 + max(height(root.left), height(root.right)))
true
770ac8812cac09b77d0990edacc7fed78c612480
saparia-data/data_structure
/geeksforgeeks/maths/1_absolute_value_solved.py
1,062
4.375
4
''' You are given an interger I. You need to print the absolute value of the interger I. Input Format: The first line of input contains T, denoting number of testcases. Each testcase contains single integer I which may be positive or negative. Output Format: For each testcase, in a new line, output the absolute value. Your Task: This is function problem. You only need to complete the function absolute that takes integer I as parameter and returns the absolute value of I. All other things are taken care of by the driver code. Constraints: 1 <= T <= 100 -106 <= I <= 106 Example: Input: 2 -32 45 Output: 32 45 Explanation: Testcase 1: Since -32 is negative, we prints its positive equavalent, i.e., 32 Testcase 1: Since 45 is positive, we prints its value as it is, i.e., 45 Hints: 1. Absolute value of an integer means value >=0. So if a number is negative you can find its absolute value by multiplying it by -1. For positive numbers no need to multiply as it's already positive. ''' def printAbs(n): return abs(n) print(printAbs(-32))
true
35030f181df15a7fb1ad550279aadc98a6baf954
saparia-data/data_structure
/geeksforgeeks/sorting/11_Counting_Sort.py
1,265
4.25
4
''' Given a string S consisting of lowercase latin letters, arrange all its letters in lexographical order using Counting Sort. Input: The first line of the input contains T denoting number of testcases.Then T test cases follow. Each testcase contains positive integer N denoting the length of string.The last line of input contains the string S. Output: For each testcase, in a new line, output the sorted string. Your Task: This is a function problem. You only need to complete the function countSort() that takes char array as parameter. The printing is done by driver code. Constraints: 1 <= T <= 105 1 <= N <= 105 Example: Input: 2 5 edsab 13 geeksforgeeks Output: abdes eeeefggkkorss Explanation: Testcase 1: In lexicographical order , string will be abdes. Testcase 2: In lexicographical order , string will be eeeefggkkorss. hints: 1) Store the count of elements. And use this count to sort the elements accordingly. ''' def countingSort(s,n): freq=[0 for i in range(256)] print(freq) for char in s: freq[ord(char)] += 1 print(freq) for i in range(256): for j in range(freq[i]): print(chr(i),end="") s = "geeksforgeeks" n = len(s) countingSort(s, n)
true
d476ee8753b489e9a160984ca1a71e49eed86f2d
saparia-data/data_structure
/geeksforgeeks/array/3_majority_in_array_solved.py
2,439
4.40625
4
''' We hope you are familiar with using counter variables. Counting allows us to find how may times a certain element appears in an array or list. You are given an array arr[] of size N. You are also given two elements x and y. Now, you need to tell which element (x or y) appears most in the array. In other words, print the element, x or y, that has highest frequency in the array. If both elements have the same frequency, then just print the smaller element. Input Format: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains 3 lines of input. The first line contains size of array denoted by n. The second line contains the elements of the array separated by spaces. The third line contains two integers x and y separated by a space. Output Format: For each testcase, in a newline, print the element with highest occurrence in the array. If occurrences are same, then print the smaller element. Your Task: Since, this is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function majorityWins() that takes array, n, x, y as parameters and return the element with highest Constraints: 1 <= T <= 100 1 <= n <= 103 0 <= arri , x , y <= 108 Examples: Input: 2 11 1 1 2 2 3 3 4 4 4 4 5 4 5 8 1 2 3 4 5 6 7 8 1 7 Output: 4 1 Explanation: Testcase 1: n=11; elements = {1,1,2,2,3,3,4,4,4,4,5}; x=4; y=5 x frequency in arr is = 4 times y frequency in arr is = 1 times x has higher frequency, so we print 4. Testcase 2: n=8; elements = {1,2,3,4,5,6,7,8}; x=1; y=7 x frequency in arr is 1 times y frequency in arr is 1 times both have same frequency, so we look for the smaller element. x=1 is smaller than y=7, so print 1. ''' def majorityWins(arr, n, x, y): c_x = 0 c_y = 0 for i in range(n): if(arr[i] == x): c_x = c_x + 1 elif(arr[i] == y): c_y = c_y + 1 else: continue #print(c_x) #print(c_y) if(c_x > c_y): return x elif(c_x < c_y): return y elif(c_x == c_y): return min(x,y) arr = [854,190,562,906,2,625,678,667,779,755,699,842,970,81,253,155,456,830,575,640,962,44,124,209,841,571,211,213,904,993,130,996,866,938,553,114,3,79,18,823,176,75,740,83,391,223,289,561,927,351,744] n = len(arr) x = 10 y = 40 print(majorityWins(arr,n,x,y))
true
8f2e60355dfe700cfde7b30b569d431ce959b7e5
saparia-data/data_structure
/geeksforgeeks/strings/6_check_if_string_is_rotated_by_two_places.py
1,986
4.21875
4
''' Given two strings a and b. The task is to find if the string 'b' can be obtained by rotating another string 'a' by exactly 2 places. Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. In the next two lines are two string a and b respectively. Output: For each test case in a new line print 1 if the string 'a' can be obtained by rotating string 'b' by two places else print 0. User Task: The task is to complete the function isRotated() which checks if given strings can be formed by rotations. The function returns true if string 1 can be obtained by rotating string 2 by two places, else it returns false. Expected Time Complexity: O(N). Expected Space Complexity: O(N). Challenge: Try doing it in O(1) space complexity. Constraints: 1 <= T <= 50 1 <= length of a, b < 100 Example: Input: 2 amazon azonam geeksforgeeks geeksgeeksfor Output: 1 0 Explanation: Testcase 1: amazon can be rotated anti-clockwise by two places, which will make it as azonam. Testcase 2: If we rotate geeksforgeeks by two place in any direction , we won't get geeksgeeksfor. hints: Step1: There can be only two cases: a) Clockwise rotated b) Anti-clockwise rotated Step 2: If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true. Step 3: Else, check if it is rotated anti-clockwise that means elements are shifted to left. So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true. Step 4: Else, return false. ''' def isRotated(s,p): n=len(p) if(n<3): return p==s anticlock_str=p[2:]+p[0:2] clockwise_str=p[-2]+p[-1]+p[:n-2] if(s==anticlock_str or s==clockwise_str): return True return False s = "amazon" p = "onamaz" print(isRotated(s, p))
true
b6bf8024d4250adafec321751f4317591391a1c9
saparia-data/data_structure
/geeksforgeeks/tree/26_Foldable_Binary_Tree.py
1,007
4.4375
4
''' Given a binary tree, find out if the tree can be folded or not. -A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. -An empty tree is considered as foldable. Consider the below tree: It is foldable 10 / \ 7 15 \ / 9 11 ''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None def foldableUtil(root1, root2): if(root1 is None and root2 is None): return True if(root1 is None or root2 is None): return False return foldableUtil(root1.left, root2.right) and foldableUtil(root1.right, root2.left) def foldable(root): if(root is None): return True result = foldableUtil(root.left, root.right) return result root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(5) root.right.left = Node(4) print(foldable(root))
true
b05134767f55b443af849edfa92df6ae5937491b
saparia-data/data_structure
/geeksforgeeks/matrix/11_Reversing_the _columns_Matrix.py
1,919
4.40625
4
''' You are given a matrix A of dimensions n1 x m1. The task is to reverse the columns(first column exchanged with last column and so on). Input: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1. The second line contains n1*m1 elements separated by spaces. Output: For each testcase, in a new line, print the resultant matrix. Your Task: This is a function problem. You only need to complete the function reverseCol() that takes n1, m1, and matrix as parameter and modifies the matrix. The driver code automatically appends a new line. Constraints: 1 <= T <= 100 1 <= n1, m1 <= 30 0 <= arri <= 100 Examples: Input: 2 4 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 3 4 3 2 1 5 6 Output: 3 2 1 7 6 5 11 10 9 15 14 13 2 3 4 6 5 1 Explanation: Testcase 1: Original array is as follows: 1 2 3 5 6 7 9 10 11 13 14 15 Array after exchanging columns: 3 2 1 7 6 5 11 10 9 15 14 13 Testcase 2: Original matrix is as follows: 4 3 2 1 5 6 After reversing the column of matrix 2 3 4 6 5 1 hints: Take two pointers low and high, low at 0 and high at n-1. Start swapping elements at two pointers and increasing the low and decreasing the high one. Do the above for all the rows. Keep in mind, when number of rows is odd, no need to take care of middle column. ''' #arr1 is matrix #n1 is rows #m1 is cols def reverseCol(n1, m1, arr1): for i in range(n1): for j in range(m1//2): t = arr1[i][j] arr1[i][j] = arr1[i][m1 - 1 - j] arr1[i][m1 - 1 - j] = t for i in range(n1): for j in range(m1): print(arr1[i][j], end = " ") print("\n") arr1 = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n1, m1 = 4, 4 reverseCol(n1, m1, arr1)
true
e76d09cc97d9d6d8677ae32ba52425ec5fa34a0f
cginiel/si507
/lecture/week3/2020.01.21.py
2,638
4.46875
4
# # import datetime # # date_now = datetime.datetime.now() # # print(date_now.year) # # print(date_now.month) # # print(date_now.day) # # print(type(date_now)) # # class is a type of thing, object is a particular instance of that class!!!!! # # BEGIN CLASS DEFINITION # """ # class Dog: # def __init__(self, nm, br): # self.name = nm # self.breed = br # """ # # END CLASS DEFINITION # # every time we call "Dog" the program is going to # # set up the function written above (which is how # # we "index" or call out the specific names below) # d1 = Dog('Fido', 'German Shepherd') # d2 = Dog('Rufus', 'Lhasa Apso') # print (d1.name, 'is a', d1.breed) # print (d2.name, 'is a', d2.breed) # # "self" essentially equals d1 because self corresponds # # to the object in question # # in that sense, "self," in the case of d2 # # equals d2 # # "all class methods will have to have self as the first # # parameter" # class Dog: # large_dogs = ['German Shepherd', 'Golden Retriever', # 'Rottweiler', 'Collie', # 'Mastiff', 'Great Dane'] # small_dogs = ['Lhasa Apso', 'Yorkshire Terrier', # 'Beagle', 'Dachshund', 'Shih Tzu'] # def __init__(self, nm, br): # self.name = nm # self.breed = br # def speak(self): # if self.breed in Dog.large_dogs: # print('woof') # elif self.breed in Dog.small_dogs: # print('yip') # else: # print('rrrrr') # d1 = Dog('Fido', 'German Shepherd') # d2 = Dog('Rufus', 'Lhasa Apso') # d3 = Dog('Fred', 'Mutt') # d1.speak() # d2.speak() # d3.speak() class Dog: large_dogs = ['German Shepherd', 'Golden Retriever', 'Rottweiler', 'Collie', 'Mastiff', 'Great Dane'] small_dogs = ['Lhasa Apso', 'Yorkshire Terrier', 'Beagle', 'Dachshund', 'Shih Tzu'] def __init__(self, nm, br, a): self.name = nm self.breed = br self.age = a def speak(self): if self.breed in Dog.large_dogs: print('woof') elif self.breed in Dog.small_dogs: print('yip') else: print('rrrrr') def print_dog_years(d): '''prints a dog's name and age in dog years dog years = actual years * 7 Parameters ---------- dog : Dog The dog to print Returns ------- none ''' dog_years = d.age * 7 print(f"{d.name} is a {d.breed} who is {dog_years} years old in dog years") pass #TODO: implement kennel = [ Dog('Fido', 'German Shepherd', 4), Dog('Rufus', 'Lhasa Apso', 7), Dog('Fred', 'Mutt', 11) ] for dog in kennel: print_dog_years(dog)
true
8288e5fd26c497ab9b285289e0218d5ab2cba302
jpchato/pdx_code
/programming_101/unit_3/exercise_1.py
1,026
4.15625
4
import math # 1.1 tri_side_1 = 1 tri_side_2 = 2 hypotenuse = (tri_side_1*tri_side_1 + tri_side_2*tri_side_2) def triangle_perimeter(tri_side_1, tri_side_2, hypotenuse): print(tri_side_1 + tri_side_2 + hypotenuse) return tri_side_1 + tri_side_2 + hypotenuse # 1.2 def triangle_area(tri_side_2, tri_side_1): print((tri_side_1*tri_side_2)/2) return (tri_side_1*tri_side_2)/2 #1.3 radius = 5 pi = math.pi print(pi) def circle_circumference(radius): print(int(radius*math.pi*2)) return int(radius*math.pi*2) # 1.4 def sphere_volume(radius): volume = (math.pi*radius*radius*radius*4)/3 print (volume) return volume # 1.5 radius_2 = 3 def annulus_area(radius, radius_2): area = int(math.pi*(radius*radius-radius_2*radius_2)) print (area) return area if __name__ == "__main__": triangle_perimeter(tri_side_1, tri_side_2, hypotenuse) triangle_area(tri_side_2, tri_side_1) circle_circumference(radius) sphere_volume(radius) annulus_area(radius, radius_2)
false
1d07ee37723cc22548908a0a75b02facb6664100
alexbenko/pythonPractice
/classes/magic.py
787
4.125
4
#how to use built in python methods like print on custom objects class Car(): speed = 0 def __init__(this,color,make,model): this.color = color this.make = make this.model = model def __str__(this): return f'Your {this.make},{this.model} is {this.color} and is currently going {this.speed} mph' def accelerate(this,toGoTo): print(f'Accelerating car to {toGoTo},currently going {this.speed} mph...') while this.speed < toGoTo: this.speed += 1 print(f'{this.speed} mph...') print(f'Accelerated to {toGoTo} !') volt = Car(color='White',make='Chevorlet',model='Volt') print(volt) #=>Your Chevorlet,Volt is White and is currently going 0 mph volt.accelerate(100) print(volt) #=>Your Chevorlet,Volt is White and is currently going 100 mph
true
b1ec77cac2953516ced165066ea926e67f236c14
xenron/sandbox-github-clone
/qiwsir/algorithm/delete_space.py
508
4.375
4
#! /usr/bin/env python #coding:utf-8 #删除一个字符串中连续超过一次的空格。 def del_space(string): split_string = string.split(" ") #以空格为分割,生成list,list中如果含有空格,则该空格是连续空格中的后一个 string_list = [i for i in string if i!=""] result_string = " ".join(string_list) return result_string if __name__=="__main__": one_str = "Hello, I am Qiwsir." string = del_space(one_str) print one_str print string
false
b821bd68661a42ae46870bd01178d181656149e6
xenron/sandbox-github-clone
/qiwsir/algorithm/divide.py
2,005
4.125
4
#! /usr/bin/env python #coding:utf-8 def divide(numerator, denominator, detect_repetition=True, digit_limit=None): # 如果是无限小数,必须输入限制的返回小数位数:digit_limit # digit_limit = 5,表示小数位数5位,注意这里的小数位数是截取,不是四舍五入. if not detect_repetition and digit_limit == None: return None decimal_found = False v = numerator // denominator numerator = 10 * (numerator - v * denominator) answer = str(v) if numerator == 0: return answer answer += '.' # Maintain a list of all the intermediate numerators # and the length of the output at the point where that # numerator was encountered. If you encounter the same # numerator again, then the decimal repeats itself from # the last index that numerator was encountered at. states = {} while numerator > 0 and (digit_limit == None or digit_limit > 0): if detect_repetition: prev_state = states.get(numerator, None) if prev_state != None: start_repeat_index = prev_state non_repeating = answer[:start_repeat_index] repeating = answer[start_repeat_index:] return non_repeating + '[' + repeating + ']' states[numerator] = len(answer) v = numerator // denominator answer += str(v) numerator -= v * denominator numerator *= 10 if digit_limit != None: digit_limit -= 1 if numerator > 0: return answer + '...' return answer if __name__=="__main__": print "5divide2", print divide(5,2) print "10divide3", print divide(10,3) print divide(10,3,5) print "15divide7" print divide(15,7) print divide(15,7,True,3)
true
465074ef23a66b649ac36eb6a259c9ace2732cb3
YYYYMao/LeetCode
/374. Guess Number Higher or Lower/374.py
1,424
4.15625
4
374. Guess Number Higher or Lower We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I ll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example: n = 10, I pick 6. Return 6. # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): #65ms class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ L , R = 1 , n M = (L+R)>>1 m = guess(M) while m != 0 : # print L , R ,M ,m if m == -1: R = M-1 elif m == 1 : L = M+1 M = (R+L)>>1 m = guess(M) return M #46ms class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ L , R = 1 , n while 1 : M = (R+L)>>1 m = guess(M) if m == -1: R = M-1 elif m == 1 : L = M+1 elif m == 0: return M
true
b7cfe79cf0003bdb6d174d1471fbb672b0700b7f
codeAligned/interview_challenges
/sort_and_search/binary_search.py
442
4.25
4
def binary_search(iterable, target): """Determine if target value is in sorted iterable containing numbers""" sorted_iterable = sorted(iterable) low = 0 high = len(sorted_iterable) - 1 while low <= high: midpoint = (high + low) // 2 if sorted_iterable[midpoint] == target: return True elif sorted_iterable[midpoint] > target: high = midpoint - 1 elif sorted_iterable[midpoint] < target: low = midpoint + 1 return False
true
c92ba78a30f78a134befad3de91f7572a201b1ef
szk0139/python_tutorial_FALL21
/mysciW4/readdata.py
1,018
4.1875
4
def read_data(columns, types = {}, filename= "data/wxobs20170821.txt"): """ Read data from CU Boulder Weather Stattion data file Parameters: colums: A dictonary of column names mapping to column indices types: A dictonary of column names mapping to the types to which to convert each column of data filename: A string path pointing to the CU Boulder Wather Station data file """ #Initialize my data variable data = {} for column in columns: data[column] = [] with open(filename, "r") as datafile: # read first three line (header) for _ in range(3): #print(_) datafile.readline() # Read and parse the rest of the file for line in datafile: split_line = line.split() for column in columns: i = columns[column] t = types.get(column, str) value = t(split_line[i]) data[column].append(value) return data
true
9b34c6cc778d0a45f819a5667308a2e4f5f7f1f8
Stepancherro/Algorithm
/stack.py
1,879
4.1875
4
# -*- encoding: utf-8 -*- # Stack() creates a new stack that is empty. # It needs no parameters and returns an empty stack. # push(item) adds a new item to the top of the stack. # It needs the item and returns nothing. # pop() removes the top item from the stack. # It needs no parameters and returns the item. The stack is modified. # peek() returns the top item from the stack but does not remove it. # It needs no parameters. The stack is not modified. # isEmpty() tests to see whether the stack is empty. # It needs no parameters and returns a boolean value. class Stack(): def __init__(self, size=10): """ Initialize python List with size of 10 or user given input. Python List type is a dynamic array, so we have to restrict its dynamic nature to make it work like a static array. """ self.size = size self.stack = [] self.top = 0 def push(self, value): if self.isFull(): raise IndexError("stack is full") else: self.stack.append(value) self.top += 1 def pop(self): if self.isEmpty(): raise IndexError("stack is empty") else: value = self.stack[self.top - 1] self.top -= 1 self.stack.pop() return value def peek(self): if self.isEmpty(): raise IndexError("stack is empty") return self.stack[self.top - 1] def isFull(self): return self.top == self.size def isEmpty(self): return self.top == 0 def showStack(self): print(self.stack) if __name__ == '__main__': stack = Stack(7) stack.push(15) stack.push(6) stack.push(2) stack.push(9) stack.showStack() last_element = stack.pop() print(last_element) stack.showStack() print(stack.peek())
true
5b7ad9bbd58b59d7e7319bad5d970b5dbba1a529
moha0825/Personal-Projects
/Resistance.py
1,018
4.375
4
# This code is designed to have multiple items inputted, such as the length, radius, and # viscosity, and then while using an equation, returns the resistance. import math def poiseuille(length, radius, viscosity): Resistance = (int(8)*viscosity*length)/(math.pi*radius**(4)) return Resistance def main(): length = float(input("Please enter the length: ")) radius = float(input("Please enter the radius: ")) viscosity = float(input("Please enter the viscosity: ")) if length <= 0: print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.") elif radius <= 0: print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.") elif viscosity <= 0: print("Failed due to input error. Please make sure your inputs are all positive. Exiting program.") else: print("The resistance is: ", poiseuille(length, radius, viscosity)) if __name__ == "__main__": main()
true
bad4bb04bb518a8b45e3c0e75dabde665ef5d942
jojadev/simpsons-test
/main.py
383
4.15625
4
name = input("Who is your favourite Simpson household member? ").capitalize() if name == 'Homer': print("You the man Homer!") elif name == 'Marge': print("Way to go mom!") elif name == 'Lisa': print("Eww, Lisa!") elif name == 'Maggie': print("What's up you cool baby?") else: print("I'm Bart Simpson, who the hell are you?") #https://repl.it/@jojadev/simpsons-test
false
d0a53a4ca42e65bb86f1e4453bdfe747ea8227ee
AmineNeifer/holbertonschool-interview
/0x19-making_change/0-making_change.py
578
4.25
4
#!/usr/bin/python3 """ Contains makeChange function""" def makeChange(coins, total): """ Returns: fewest number of coins needed to meet total If total is 0 or less, return 0 If total cannot be met by any number of coins you have, return -1 """ if not coins or coins is None: return -1 if total <= 0: return 0 change = 0 coins = sorted(coins)[::-1] for coin in coins: while coin <= total: total -= coin change += 1 if (total == 0): return change return -1
true
3b2c0d8d806dcc4b73a80bf0564a77f77b906b67
laurenhesterman/novTryPy
/TryPy/trypy.py
1,832
4.5625
5
#STRINGS # to capitalize each first letter in the word use .capitalize() method, with the string before .capitalize characters = "rick" print characters.capitalize() #returns Rick #returns a copy of the whole string in uppercase print characters.upper() #returns RICK #.lower() returns a copy of the string converted completely to lowercase print characters.lower() #returns rick #count returns the number of occurances of the substr in original string. Uses (str[start:end]) as paramaters. #defaults start and end to 0 string ="today is my birthday" strg= "day" print string.count("day") #returns 2 #.find() returns lowest index at which substring is found. (str[start:end]) start and end default to entire string #-1 on failure print string.find(strg) #returns 2, as "day" begins on 2nd index of the string #.index() is similar to .find(), but returns ValueError when not found print string.index("day") #returns 2 """.split() reutrns a list of words of the string. (str[, sep[, maxsplit]]) are parameters. By default they separate with whitespace, but 'sep' can replace a string as the separateor. maxsplit defaults to 0, but that number specifies how many splits will occur at most""" string ="today is my birthday" print string.split("y") #.join() concentrates a list or words to string at intervening occurances of sep (default whitespace) string2 ="today is my birthday" print string2.join("now") # returns: ntoday is my birthdayotoday is my birthdayw (wraps each character of "now around" occurances of string2) #replaces occurances of first argument within string with second argument print string.replace("day", "month") #returns tomonth is my birthmonth #.format() formats string with replacement holders string3 = "The sum of 1 + 2 = {}" print string3.format(1+2) #returns The sum of 1 + 2 = 3 #NUMBERS
true
017ccb38921399323ccb3c169a50063b3057a118
Alex-Reitz/Python_SB
/02_weekday_name/weekday_name.py
566
4.25
4
def weekday_name(day_of_week): """Return name of weekday. >>> weekday_name(1) 'Sunday' >>> weekday_name(7) 'Saturday' For days not between 1 and 7, return None >>> weekday_name(9) >>> weekday_name(0) """ i = 0 weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] while i < len(weekdays): if i + 1 == day_of_week: print(weekdays[i]) i = i + 1 weekday_name(1) weekday_name(2) weekday_name(3) weekday_name(4)
true
5c39c42c7787b07e51728b67855c4f58fa98fd0f
leios/OIST.CSC
/hello_world/python/hello_world.py
788
4.15625
4
#-------------hello_world.py---------------------------------------------------# # # In most traditional coding courses, they start with a simple program that # outputs "Hello World!" to the terminal. Luckily, in python... this is pretty # simple. In fact, it's only one line (the line that follows this long comment).# # You should be able to type in: # # python hello_world.py # # and receive the following output in your terminal: # # Hello World! # # So let's get to it! #------------------------------------------------------------------------------# print("Hello World!") # In python, the "print" command sends whatever is in the parentheses to your # terminal. That's precisely what we are doing. Sending "Hello World!" to the # terminal. Let me know if you have any trouble!
true
53c935628a3bcee64d664a7304417cc509031e12
LittltZhao/code_git
/342_Power_of_Four.py
202
4.125
4
# -*- coding:utf-8 -*- #判断一个数是否为4的幂数 def isPowerOfFour(num): return num>0 and (num&(num-1))==0 and (num-1)%3==0#(num&(num-1))==0判断是否为2的幂 print isPowerOfFour(16)
false
ec4030fa14128f11e3354b789203588dddf333ff
flashlightli/math_question
/leetcode_question/mid_question/29_Divide_Two_Integers.py
2,103
4.125
4
""" 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符(取余)。 返回被除数 dividend 除以除数 divisor 得到的商。 整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2   示例 1: 输入: dividend = 10, divisor = 3 输出: 3 解释: 10/3 = truncate(3.33333..) = truncate(3) = 3 示例 2: 输入: dividend = 7, divisor = -3 输出: -2 解释: 7/-3 = truncate(-2.33333..) = -2   提示: 被除数和除数均为 32 位有符号整数。 除数不为 0。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/divide-two-integers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def divide(self, dividend: int, divisor: int) -> int: # 位运算 positive = False if dividend == 0: return 0 if (dividend > 0 and dividend > 0) or (dividend < 0 and dividend < 0): positive = True scaling = 1 << 31 result = self.divide_1(dividend, divisor) if positive == 1: if result > scaling: result = scaling return -result if result >= scaling: result = (scaling) - 1 return result def divide_1(self, dividend, divisor): # 除数向左平移 count = 0 while dividend >= divisor: divisor_i = divisor new_count = 1 while (divisor_i << 1) < dividend: divisor_i = divisor_i << 1 new_count = new_count << 1 # count 记录了倍数, 即divisor*count < dividend < divisor*count*2 dividend = dividend - divisor_i count = count + new_count return count test = Solution() print(test.divide( 10, 3 ))
false
cbabb745d29b004c700fa4edfa9c16c1d4424d5a
flashlightli/math_question
/leetcode_question/mid_question/114_Flatten_Binary_Tree_to_Linked_List.py
1,404
4.25
4
""" 给定一个二叉树,原地将它展开为一个单链表。 例如,给定二叉树 1 / \ 2 5 / \ \ 3 4 6 将其展开为: 1 \ 2 \ 3 \ 4 \ 5 \ 6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ # 把左子树插入到根节点和右子树之间 return self.to_right(node=root) def to_right(self, node): if not node: return self.to_right(node.left) self.to_right(node.right) if node.left: pre = node.left while pre.right: pre = pre.right pre.right = node.right node.right = node.left node.left = None root = TreeNode(1) # root.left = TreeNode(2) # root.left.left = TreeNode(3) root.right = TreeNode(2) # root.right = TreeNode(5) root.right.right = TreeNode(3) test = Solution() print(test.flatten( root ))
false
457ac15fcea68d766279c72296236295daa866d1
Hanlen520/Leetcode-4
/src/114. 二叉树展开为链表.py
1,746
4.1875
4
""" 给定一个二叉树,原地将它展开为链表。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 其实就是先序遍历,下面采用迭代的方法 class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ head = TreeNode(0) stack = [root] while stack: curr = stack.pop() if curr: stack.append(curr.right) stack.append(curr.left) curr.left = None curr.right = None head.right = curr head = curr # 这个是用后序遍历使用的递归方法 # 后序遍历由于可以先处理左子树和右子树,根节点在最后处理。所以先找到左子树的最右节点,然后再把右子树插到左子树的最右节点后,最后将 # 根节点的右子树变为当前的左子树,依次递归。 class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ def helper(root1): if not root1: return else: helper(root1.left) helper(root1.right) # 找到左子树的最右节点 curr = root1.left if curr: while curr: pre = curr curr = curr.right pre.right = root1.right root1.right = root1.left root1.left = None helper(root)
false
4508866832b2578a43788e47e00c3e9781bb6b44
cesarmarroquin/blackjack
/blackjack_outline.py
2,089
4.1875
4
""" I need to create a blackjack Game. In blackjack, the player plays against the dealer. A player can win in three different ways. The three ways are, the player gets 21 on his first two cards, the dealer gets a score higher than 21, and if the player's score is higher than the dealer without going over 21. The dealer wins if the player goes over 21, or if the dealer's hand is greater than the player's without going over 21. In the beginning, the player is dealt two cards. There is also one rule which states that if the dealer's hand is greater than or equal to 17, then he can not hit anymore. There is a point system that must be followed in the game of blackjack, all cards have a point value based off the numeric indication on the front. The card's that don't follow this rule are ace's which could be 1 or 11, and face cards which all equal to 10. It is also important to know what a deck of cards has; a deck of cards ha s 52 cards, 13 unique cards, and 4 suits of those 13 unique cards. Game(player1, player2=) The Game Responsibilities: * ask players if they want to hit or stand. * Collaborators: * Collected into a Deck. * Collected into a Hand for each player and a Hand for the dealer. def play_game def deal_two_cards_to_player def switch_players Player The player Responsibilities: * Has to hit or stand Collaborators: * game takes the hit or stand response def hit def stand money Dealer The dealer Responsibilities: * Has to hit, has to stand at 17 or greater Collaborators: * game takes the hit or stand response def hit def stand money shoe Hand cards_in_hand Card A playing card. Responsibilities: * Has a rank and a suit. * Has a point value. Aces point values depend on the Hand. Collaborators: * Collected into a Deck. * Collected into a Hand for each player and a Hand for the dealer. suit kind Deck card_amount suits kinds if __name__ == '__main__': """
true
3883f41652fa43d96be453f5d5434aead2cf3ead
mohit131/python
/project_euler/14__Longest_Collatz_sequence.py
1,095
4.21875
4
'''The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million.''' def even(x): return(x/2) def odd(x): return(3*x + 1) def Collatz(a): b=[a] while (a != 1): if(a%2==0): b.append(even(a)) a=even(a) else: b.append(odd(a)) a=odd(a) return b c=[] lsize=[] ''' for i in range(1,10000): c.append((Collatz(i))) lsize.append((len(c[i-1]))) #lsize.append() #print(c) print(max(lsize)) ''' irange=range(1,1000000) c=list(map(Collatz,irange)) lsize1=list(map(len,c)) print(max(lsize1))
true
c7404efed6d6384bcf49df15f0dc508c01a7fef5
mohit131/python
/project_euler/9__Special_Pythagorean_triplet.py
490
4.125
4
'''A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.''' for m in range(1,5000): for n in range(1,500): if m>n: a=m*m - n*n b= 2 * m * n c=m*m + n*n sum_ab=a*a + b*b sum_c=c*c if sum_ab == sum_c: if a+b+c==1000: print(a,b,c,a+b+c,a*b*c) else: break
false
5a97036b637ec09c393d8fae0178db26b3db1603
adidrmwan/basic-python
/leapYear.py
503
4.1875
4
def is_leap(year): leap = False leap_year = year % 4 leap_year_divided_100 = year % 100 leap_year_divided_400 = year % 400 if leap_year == 0: leap = True if leap_year_divided_100 == 0: leap = False if leap_year_divided_400 == 0: leap = True else: leap = False else: leap = True else: leap = False return leap year = int(input()) print(is_leap(year))
false
df01dc415a7750095dcd99b64690469a7c41b983
Chittadeepan/P342
/lab5_q2.py
1,328
4.1875
4
#importing everything from math module from math import * #importing all functions from library from library import * #poly_f(x) function def poly_f(x,coeff,n): sum=0 for i in range(1,n+1): sum=sum+coeff[i-1]*x**(n-i) return sum #main program def main(): #initialising final absolute error(epsilon), initial guess of root(root) and number of terms in polynomial(n) epsilon=10**(-6) root=0.9 n=5 #initialising coeff list and appending coeff elements corresponding to their variables with decreasing power coeff=[1,-3,-7,27,-18] #solving P(x)=x^4-3x^3-7x^2+27x-18 print('Solving x^(4)-3x^(3)-7x^(2)+27x-18 by Laguerre method and Synthetic Division method:') #calling Laguerre function and Synthetic Division function and displaying the roots obtained in a loop for index in range(n,1,-1): root=Laguerre(root,epsilon,coeff,index,poly_f) if index>0: coeff=Synthetic_Division(root,coeff) print('One of the roots obtained:',round(root,6)) main() ''' #Output Solving x^(4)-3x^(3)-7x^(2)+27x-18 by Laguerre method and Synthetic Division method: One of the roots obtained: 1.0 One of the roots obtained: 2.0 One of the roots obtained: 3.0 One of the roots obtained: -3.0 '''
true
e537efac5d4877eb9b8516a4b02cee19f7985323
PratheekH/Python_sample
/comp.py
201
4.28125
4
name=input("Enter your name ") size=len(name) if size<3: print("Name should be more than 3") elif size>50: print("Name should not be more than 50") else: print("Name looks fine")
true
134a72d4bd4ca94b8e3a0d2d7c5a4f6b83bf9480
cjrzs/MyLeetCode
/重要的算法模板/排序算法模板/冒泡排序.py
667
4.28125
4
""" coding: utf8 @time: 2020/12/8 17:18 @author: cjr @file: 冒泡排序.py """ # 冒泡排序使用当前元素与下一个元素做比较,把符合条件的后移一位或者不动, # 这样每次都会把最大或者最小的数放在最后一个位置。 # 重复这种排序思路。就可以从后到前的排序好数组。 def bubble_sort(nums): n = len(nums) for i in range(n - 1): for j in range(n - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums if __name__ == '__main__': nums_ = [1, 3, 8, 4, 2, 1, 5, 10] print(bubble_sort(nums_))
false
3f9f28e504e80d7a04fb13f7750d12c873a063a0
xdyxiang/pythonlearn
/python_base/digui.py
574
4.15625
4
# 遍历一个盘符下的所有文件(包括子文件夹、文件) import os def getFile(path): try: filelist = os.listdir(path) # 得到该文件夹下的所有文件 for file in filelist: file = os.path.join(path, file) # 将文件名和路径结合起来 if os.path.isdir(file): getFile(file) # 在这里如果判断一个文件是文件夹,那么就会再次调用自己 else: print(file) except: print('出错,跳过') getFile(r'E:/')
false
2a8ea1f95001015fba07fc2130024b5c6a8375c7
aashishah/LocalHackDay-Challenges
/EncryptPassword.py
702
4.28125
4
#Using Vignere Cipher to encrpt password of a user using a key that is private to the user. def encrypt(password, key): n = len(password) #Generate key if len(key) > n: key = key[0:n] else: key = list(key) for i in range(n - len(key)): key.append(key[i % len(key)]) key = "" . join(key) #Generate encrypted password: cipher = [] for i in range(n): letter = (ord(password[i]) + ord(key[i])) % 26 letter += ord('A') cipher.append(chr(letter)) print("Encrypted password: " + "".join(cipher)) password = input("Enter password: ") key = input("Enter your private key: ") encrypt(password, key)
true
15c76b453894e5eb09fcaa195a0a8a66351b1048
Karlo5o/rosalind_problems
/RNA.py
700
4.1875
4
""" An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'. Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u. Given: A DNA string t having length at most 1000 nt. Return: The transcribed RNA string of t. """ def dna_transcriber(input_file): with open('output.txt','w') as output, open(input_file) as input: dna_string = input.readline() rna_string = dna_string.replace("T", "U") #Convert int to string output.write(rna_string) #Write transcribed string in to file dna_transcriber('input.txt') #input file name is 'input.txt'
true
d6c9481fd67e920623b9c3ac06f98d0051db1c95
SaulAlekss/clienteservidor
/listas.py
1,328
4.5625
5
def main(): # Una lista es una estructura de datos en python # # La ventaja aceptan datos de tipos distintos # # Creamos una lista lista = [1,23.01, False, "hola lista", "A",[-1,-5, "hola", 0.0], -12,"A"] # Lista Vacia listaVacia = [] # Accesando a elementos de la lista for elemento in lista: print("El elemento de la lista es: ", elemento) for i in listaVacia: print("El elemento de la lista es: ", elemento) #Imprimir un elemento de la lista print("Elemento en la posicion 3: ", lista[3]) print("Elemento en la posicion 3: ", lista[-1]) print(lista[-2]) print(lista[5]) # Leer elemento en la posicion 2 de la lista interna print(lista[5][2]) # Metodos de las listas """lista.append("Agregar una cadena......") for elemento in lista: print("El elemento de la lista es: ", elemento) """ # count regresa el numero de veces que se repite un elememto en la lista print("Elemento se repite : " , lista.count("A")) # index() imprime el indice de un elemento en la lista print("La posicion de False es: ", lista.index(False)) # Eliminar elementos de la lista : remove() lista.remove("hola lista") for x in lista: print("El elemento de la lista es: ", x) if __name__=="__main__": main()
false
d516d08d9c1af9bce8e845f69552a45377b6696b
marcusiq/w_python
/greeting.py
1,570
4.4375
4
""" Generally. There is no method overloading in python. Overloading in other languages occurs when two methods have the same name, but different numbers of arguments. In python, if you give more than one definition using the same name, the last one entered rules, and any previous definitions are ignored. """ # Here an unsuspecting student attempts to overload a method named "greeting" with several definitions. def greeting(): print "Hi! Are you new here?\n" # The second takes one argument, and can be used to greet a person whose name you know. def greeting(name): print "Yes! It's my first day! My name is %s.\n" % name # The third takes two arguments, and can be used to name both yourself and the addressee. def greeting(name1, name2): print "Nice to meet you %s! My name is %s.\n" % (name1, name2) # The fourth takes one argument, conceived to be an integer. def greeting(n): print "Can I borrow $%d for coffee?\n" % n # The fifth takes one argument, conceived to be a boolean. def greeting(b): # A boolean. if b: print "Sure! Let's have coffee together.\n" else: print "Sorry! I'm flat broke!\n" # Hmmm, that did not work! There is no overloading in Python! try: greeting() except Exception as e: print e.message try: greeting("Mork") except Exception as e: print e.message try: greeting("Mork", "Mindy") except Exception as e: print e.message try: greeting(10) except Exception as e: print e.message try: greeting(True) except Exception as e: print e.message
true
0db7eaa487bf54eb30f885b7baf11d93dfd6eabd
adamelliott1982/1359_Python_Benavides
/lab_04/1359-lab_04/drop_grade.py
1,549
4.34375
4
# Program: drop_grade.py # Programmer: Adam Elliott # Date: 02/26/2021 # Description: lab 4 - lists and for statements ######################################################## # create list of 5 grades and initialize grades = [100, 80, 70, 60, 90] # print report name – DROP LOWEST GRADE PROGRAM print('DROP LOWEST GRADE PROGRAM:\n') # show original grades using for in Loop print('Grades:') for grade in grades: print(grade) # use sum function on grades to calculate the total total = sum(grades) # calculate the average by dividing total by len(grades) average = total/len(grades) # print number of grades using len function print(f'Number of grades: {len(grades)}') # print average formatted to 2 decimal places print(f'Average: {average:.2f}') # find the lowest grade using min function and print lowest grade lowest_grade = min(grades) print(f'Lowest grade: {lowest_grade}') #remove lowest grade grades.remove(lowest_grade) # print LOWEST GRADE DROPPED print('\nLOWEST GRADE DROPPED:\n') # show grades after dropping lowest grade using for in Loop print('Grades:') for grade in grades: print(grade) # use sum function to calculate the total after dropping lowest grade total = sum(grades) # compute new average average = total/len(grades) # print new number of grades print(f'Number of grades: {len(grades)}') # print new average print(f'Average: {average:.2f}') # find new lowest grade and print lowest_grade = min(grades) print(f'Lowest grade: {lowest_grade}')
true
8c2a6954dbcdb20dba141975559470e8b04ad921
BenjaminLivingstone/fundamentos-python
/Otros/ejerciciopython1.py
1,116
4.1875
4
# GRUPO 2: # Crea una funcion que dado una palabra diga si es palindroma o no. def palindroma(palabra): if ("hola"[::-1]==palabra): print("La palabra",palabra,"es palindroma") else: print("La palabra",palabra,"NO es palindroma") palabra="hola"; palindroma(palabra) palabra="python" print(palabra[2:]) # palabra[inicio:final:paso] print("hola"[::-1]) # - Crea una función que tome una lista y devuelva el primer y el último valor de la lista. Si la longitud de la lista es menor que 2, haga que devuelva False. def devuelvevalor(lista): if (len(lista)<2): return False print(lista[0]) print(lista[len(lista)-1]) lista=[1,2,3,4,5,7] devuelvevalor(lista) # # # - Crea una función que tome una lista y devuelva un diccionario con su mínimo, máximo, promedio y suma. # def devuelvedic(listadic): # minimo=min(listadic) # maximo=max(listadic) # promedio=sum(listadic)/len(listadic) # suma=sum(listadic) # dic={"Mínimo":minimo,"Máximo":maximo,"Promedio":promedio,"Suma":suma} # print(dic) # listadic=[1,21,3,44,-15,6] # devuelvedic(listadic)
false
f371184ca3169f6fffe54319969f8ed2cf8ef2d6
DishT/Python100-
/ex2.py
297
4.1875
4
def factorial(num): number = 1 for i in range(int(num)): number = (i+1)*number print (number) # 8! = 8 * 7!....... , 0! = 1 def factorial_2(num): if num == 0 : return 1 else: return num * factorial_2(num-1) def factorial_3(num): num = input() factorial(num) print (factorial_2(num))
false
37ac60fa04dbaed484d77e43317c6069a26ad777
marc-p-greenfield/tutor_sessions
/payment_system.py
602
4.21875
4
number_of_employees = int(input("How many employees do you want to enter:")) total_payment = 0 for i in range(number_of_employees): name = input('Please enter name: ') hours = float(input('How many hours did you work this week? ')) rate = float(input('What is your hourly rate?')) payment = 0 overtime = 0 if hours > 40: overtime = hours - 40 hours = 40 payment = (hours * rate) + (overtime * rate * 1.5) total_payment += payment print(name) print("${:,.2f}".format(payment)) print (total_payment) print (total_payment/number_of_employees)
true
a9f5a386203fe02efc9f289408744aef6e326c57
jinseoo/DataSciPy
/src/파이썬코드(py)/Ch08/code_8_6.py
392
4.125
4
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # 8.6 집합의 항목에 접근하는 연산, 207쪽 # numbers = {2, 1, 3} if 1 in numbers: # 1이라는 항목이 numbers 집합에 있는가 검사 print("집합 안에 1이 있습니다.") numbers = {2, 1, 3} for x in numbers: print(x, end=" ") for x in sorted(numbers): print(x, end=" ")
false
f26e9e6bc1103c6c72fbe0fc72ed2435b62281ad
KishoreMayank/CodingChallenges
/Cracking the Coding Interview/Arrays and Strings/StringRotation.py
349
4.1875
4
''' String Rotation: Check if s2 is a rotation of s1 using only one call to isSubstring ''' def is_substring(string, sub): return string.find(sub) != -1 def string_rotation(s1, s2): if len(s1) == len(s2) and len(s1) != 0: return is_substring(s1 + s1, s2) # adds the two strings together and calls is substring return False
true