blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1f78c540f60b806c42790f8ad770486c289a92e3
croguerrero/pythonexercises
/ejerciciospracticafunciones.py
1,642
4.1875
4
def area_rectangulo(base,altura): """ Calcula el area del rectangulo Arg: base y altura (int or float) Return: area(Float) """ if base > 0 and altura > 0: area = base * altura else: print("Los parametos ingresados de base y altura no son los correctos") area = 0 return print("Esta es el area del rectangulo {}".format(area)) ##area_rectangulo(1.5,6.5) def area_circulo(r): """ Calcula el area del circulo Arg: radio (int or float) Return: area(Float) """ import math A = (r**2)*(math.pi) return print("El area del circulo es: {}".format(A)) ##area_circulo(5) def relacion(a,b): """ Calcula la relacio de dos numeros Arg: Dos numeros enteros a y b (int) Return: 1 A>B -1 B>A 0 A=B """ if a > b: r = 1 elif b > a: r = -1 else: r = 0 return print("La relacion de los numero a y b es igual: {}".format(r)) ##relacion (5,10) def separar(*lista): """ Dada un lista separa en numeros pares e impares Arg: Indeterminado lista de numeros Return: Lista pares[] en formaa ordenada Lista impares[] en forma ordenada """ pares = [] impares = [] for i in lista: rest = i % 2 if rest==0: pares.append(i) else: impares.append(i) return print("Lista pares: {}".format(sorted(pares))) , print("Lista impares: {}".format(sorted(impares))) separar(6,5,2,1,7,8,9,88,66,55,66,105,100,1,3,9,7,26,44,65665,55)
false
c98bb5bb0e732c435b577a70b9e9b7cc4d3b38e9
croguerrero/pythonexercises
/filterfuncion.py
723
4.125
4
###La funcion filter ## aplica la funcion a todos los elementos de un objeto iterable ##Devuelve un objeto generado de ahiq eu usemos las funcion list() para convertirlo a lista ### Duvuelve los elementos para los cuales aplicar la funcion devuelve un true nums = [49, 57, 62, 147, 2101, 22] print(list(filter(lambda x: (x % 7 == 0), nums))) ## Ejemplo con funcion --- combinar la funcion filter con una funcion def third_letter_is_s(word): return word[2] == "s" words = ["castaña", "astronomía", "masa", "bolígrafo", "mando", "tostada"] print(list(filter(third_letter_is_s, words))) ###Ejercicio con funciones lambda nums = [-5,-3,5,2,6,9,8,9,-6,8,7,6,9,-6,-2,-1] print(list(filter(lambda x: x > 0,nums)))
false
9ab9a300bdda856d7d05757c6c2916887719c524
croguerrero/pythonexercises
/funcioncompleja.py
2,666
4.125
4
from typing import Container def euclidean_division(x, y): ints = (x == int(x)) and (y == int(y)) if not ints: x = int(x) y = int(y) print("Se tomarán como parámetros la parte entera de los valores introducidos.") if abs(x) >= abs(y): q = x // y r = x % y print("Se ha realizado la división {} entre {} y se ha obtenido como cociente q = {} y como resto, r = {}".format(x, y, q, r)) else: q = y // x r = y % x print("Se ha realizado la división {} entre {} y se ha obtenido como cociente q = {} y como resto, r = {}".format(y, x, q, r)) return q, r ### Ejemplos ## def sing(num): """ Funcion dado un numero comprueba su signo Args: num(int): numero del cual podemos hallar su signo Return: String() que indica el signo """ if num > 0: print(" Este es un numero postivo {}".format(num)) elif num < 0: print(" Este es un numero negativo: {}".format(num)) else : print(" Este es un numero es: {}".format(num)) def tabla(num): """ Dado un número entero, imprimimos su tabla de multiplicar con los 10 primeros múltiplos y devolvemos una lista de los múltiplos. Args: num (int): valor del cual vamos a calcular sus tabla de multiplicar Returns: multiples (list): lista con los 10 primeros múltiplos de num """ if type(num) != type(1): print("El numero introducido no es entero") return multiples = [] print("La tabla de multiplicar del {}:".format(num)) for i in range (1,11,1): prod = i * num print("{} x {} = {}".format(i,num, prod)) multiples.append(prod) return multiples #### Ejemplo 7 def cointain_a(sentence): """ Dado un frase comprueba si existe la letra a Arg: sentence(string) frase para verificar Return: Indica True o False si contiene o no la letra 'a' """ i = 0 while sentence[i] != ".": if sentence[i] == "a": return print(True) i +=1 return print(False) cointain_a("Hol que ms.") def cointain_letter(sentence): """ Dado un frase comprueba si existe la letra a Arg: sentence(string) frase para verificar Return: Indica True o False si contiene o no la letra 'a' """ print("Dada la oracion: ", sentence ) sentence = sentence.lower() letter = input("Indicar que letra quiere encontrar: ") i = 0 while sentence[i] != ".": if sentence[i] == letter: return print(True) i +=1 return print(False) cointain_letter("Hol que ms.")
false
707330c6a067b20d68b1864052f8114237154a52
croguerrero/pythonexercises
/funcionsorted.py
635
4.46875
4
#### la funcion sorted() ### Ordena los elementos del objeto iterable que indiquemos de acuerdo a la función que pasemos por parámetro #### Como output, devuelve una permutación del objeto iterable ordenado según la función indicada ##Ejercicio: Con la ayuda de las funciones lambda, apliquemos sorted() para ordenar la lista words en función # de las longitudes de las palabras en orden descendente. words = ["zapato", "amigo", "yoyo", "barco", "xilófono", "césped"] print(sorted(words, key = lambda x: len(x), reverse = True)) print(sorted(words, key = len, reverse = True)) print(sorted(words, key = len)) print(words)
false
c77a6dd6090ddd15e50741841a66cb05e8db771a
shashbhat/Internship_Data_Analytics
/Assignment/Day 1/6.py
387
4.375
4
''' 6. Write a program to accept a number from the user; then display the reverse of the entered number. ''' def reverse_num(num): ''' Reverses a number and returns it. ''' rev = 0 while num != 0: rev = rev * 10 + num % 10 num = num // 10 return rev num = int(input("Enter a number: ")) rev = reverse_num(num) print(f"Reverse of {num} is {rev}")
true
4ac7158db07e3d5ce9de5125b646eee70fec24b3
milind1992/CheckIO-python
/Boolean Algebra.py
1,713
4.5
4
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence") ​ def boolean(x, y, operation): ​ if operation=="conjunction": #"conjunction" denoted x ∧ y, satisfies x ∧ y = 1 if x = y = 1 and x ∧ y = 0 otherwise. return x*y ​ elif operation=="disjunction": #"disjunction" denoted x ∨ y, satisfies x ∨ y = 0 if x = y = 0 and x ∨ y = 1 otherwise. return x or y ​ elif operation=="implication": #"implication" (material implication) denoted x→y and can be described as ¬ x ∨ y. If x is true then the value of x → y is taken to be that of y. But if x is false then the value of y can be ignored; however the operation must return some truth value and there are only two choices, so the return value is the one that entails less, namely true. return not_(x)or y ​ elif operation=="exclusive": #"exclusive" (exclusive or) denoted x ⊕ y and can be described as (x ∨ y)∧ ¬ (x ∧ y). It excludes the possibility of both x and y. return (x+y)%2 elif operation=="equivalence": #"equivalence" denoted x ≡ y and can be described as ¬ (x ⊕ y). It's true just when x and y have the same value. return not_(boolean(x,y,"exclusive")) ​ ​ def not_(x): if x is 0 : return 1 else: return 0 ​ if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert boolean(1, 0, "conjunction") == 0, "and" assert boolean(1, 0, "disjunction") == 1, "or" assert boolean(1, 1, "implication") == 1, "material" assert boolean(0, 1, "exclusive") == 1, "xor" assert boolean(0, 1, "equivalence") == 0, "same?"
true
47ad2084d09c9be3ffae5d20f34cac14b96f85e3
CodeAltus/Python-tutorials-for-beginners
/Lesson 3 - Comments, input and operations/lesson3.py
269
4.21875
4
# Taking user input dividend = int(input("Enter dividend: ")) divisor = int(input("Enter divisor: ")) # Calculation quotient = dividend // divisor remainder = dividend % divisor # Output results print("The quotient is", quotient) print("The remainder is", remainder)
true
c86b788a0d4bab42f59fde14c1d3a35b034171a1
GedasLuko/Python
/Chapter 5 2/program52.py
673
4.15625
4
#Gediminas Lukosevicius #October 8th, 2016 © #import random function #build numbers function first #create accumulator #create a count in range of five numbers #specify five numbers greater than ten but less than thirty #create a total for five numbers assignment #display five random numbers and total as specified #build main function and call numbers function #call main function import random def main(): numbers() def numbers(): total = 0.0 for count in range(5): number = random.randint(11,29) total = total + number print(number, end = ' ') print() print('The total is', format(total, '.0f')) main()
true
1527cdb327c0d59506154813384d32718ceb1864
GedasLuko/Python
/chapter 2/program24.py
587
4.5
4
#Gediminas Lukosevicius #September 1st, 2016 © #This program will convert an improper fraction to a mixed number #Get Numerator #Get Denominator #Convert improper fraction to mixed number #Dislpay the equivalent mixed number with no space either side of the / symbol numerator = int(input('Please enter the numerator: ')) denominator = int(input('Please enter the denominator: ')) whole_number = int(numerator // denominator) remainder_fraction = int(numerator % denominator) print('The mixed number is: ', format(whole_number), ' and ', format(remainder_fraction), '/', format(denominator),sep='')
true
53c1bd002b7c652df805e6ea2cd1991746508aef
GedasLuko/Python
/write_numbers.py
510
4.375
4
#Gediminas Lukosevicius #October 24th, 2016 © #This program demonstrates how numbers must be converted to strings before they are written to a text file. def main(): outfile = open('numbers.txt', 'w') num1 = int(input('Enter a number: ')) num2 = int(input('Enter another number: ')) num3 = int(input('Enter another number: ')) outfile.write(str(num1) + '\n') outfile.write(str(num2) + '\n') outfile.write(str(num3) + '\n') outfile.close() print('Data written to numbers.txt') main()
true
7ab57f62d55657bcba373ca0ab2cfea240039b64
GedasLuko/Python
/Chapter 5/program53/tempconvert.py
490
4.40625
4
#Gediminas Lukosevicius #October 8th, 2016 © #This program will convert temperature from celsius to fahrenheit #and fahrenheit to celsius #write formula for celsius to fahrenheit #display converted celsius temperature in fahrenheit #create function with formula for fahrenheit to celsius conversion #return fahrenheit to celsius conversion temperature def c_to_f(tmp): fahr = 9.0 / 5.0 * tmp + 32 print('In Fahrenheit that is',format(fahr,'.2f')) def f_to_c(tmp): return (tmp - 32) * 5 / 9
false
25e2f64d1c80edac30dfb37bf57035cc2b3d1e1d
zsoltkebel/university-code
/python/CS1028/practicals/p2/seasons.py
868
4.25
4
# Author: Zsolt Kébel # Date: 14/10/2020 # The first day of seasons of the year are as follow: # Spring: March 20 # Summer: June 21 # Fall: September 22 # Winter: December 21 # Display the season associated with the date. month = "Mar" date = 23 if month == "Jan" or month == "Feb": print("Winter") elif month == "Mar": if date < 20: print("Winter") else: print("Spring") elif month == "Apr" or month == "May": print("Spring") elif month == "Jun": if date < 21: print("Spring") else: print("Summer") elif month == "July" or month == "Aug": print("Summer") elif month == "Sep": if date < 22: print("Summer") else: print("Fall") elif month == "Oct" or month == "Nov": print("Fall") elif month == "Dec": if date < 21: print("Fall") else: print("Winter")
true
c437e2b2397e99a209a6b2273117a443d198e277
gschen/where2go-python-test
/1906101041刘仕豪/第九周练习题/3.py
802
4.125
4
''' 3、 输入三个整数x,y,z,请把这三个数由小到大输出。 ''' # x = int(input("请输入正整数x:")) # y = int(input("请输入正整数y:")) # z = int(input("请输入正整数z:")) # if y>x and y>z and z>x: # x1 = y # y1 = z # z1 = x # elif y>x and y>z and x>z: # x1 = y # y1 = x # z1 = z # elif x>z and z>y: # y1 = z # z1 = y # x1 = x # elif z>x and x>y: # x1 = z # y1 = x # z1 = y # elif z>y and y>x: # x1 = z # z1 = x # y1 = y # print("正整数x,y,z从小到大排序为{}<{}<{}".format(z1,y1,x1)) #第二次改的 x = int(input("请输入正整数x:")) y = int(input("请输入正整数y:")) z = int(input("请输入正整数z:")) if x>y: x,y=y,x if x>z: x,z=z,x if y>z: y,z=z,y print(x,y,z)
false
60b40f345a12dac59f986ec76fbf76bc787a9ff3
gschen/where2go-python-test
/1906101001周茂林/第16周20191215/力扣-1.py
503
4.25
4
''' 给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。 请你返回该链表所表示数字的 十进制值 。 示例 1: 输入:head = [1,0,1] 输出:5 解释:二进制数 (101) 转化为十进制数 (5) 示例 2: 输入:head = [0] 输出:0 ''' def getDecimalValue(head): s = int(''.join(str(x) for x in head), 2) print(s) getDecimalValue([1, 0, 1]) getDecimalValue([0, 0])
false
cacbf029b45a960fa30b175e3f0bafe66ebfaab6
gschen/where2go-python-test
/1200-常用算法/其他/111_二叉树的最小深度.py
1,288
4.15625
4
# https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/ from typing import * import unittest # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: result = [] if root == None: return result queue = [] queue.append(root) while len(queue) != 0: level_len = len(queue) level_all = [] for i in range(level_len): node = queue.pop(0) level_all.append(node.val) if node.left != None: queue.append(node.left) if node.right != None: queue.append(node.right) result.insert(0, level_all) return result class Test(unittest.TestCase): def test_01(self): n3, n9, n20, n15, n7 = [TreeNode(i) for i in [3, 9, 20, 15, 7]] n3.left, n3.right = n9, n20 n20.left, n20.right = n15, n7 self.assertEqual(Solution().levelOrderBottom(n3), [ [15, 7], [9, 20], [3] ]) if __name__ == '__main__': unittest.main()
true
4e441ab239c7d9bec2ed15b889002935808f9adc
pcebollada/Python
/Ejercicios de clase/Buenos días, tardes, noches.py
493
4.15625
4
# -*- coding: cp1252 -*- #hacer un programa que segun la hora que sea, nos diga buenos dias, buenas tardes o buenas noches# #De seis a catorce, son buenos das;de catorce a veinte son buenas tardes; y de 20 a 6 son buenas noches# def saludador(): h=input("Dime que hora es?:") if (h>=6 and h<14): print "Buenos dias" elif (h>=14 and h<20): print "Buenas tardes" elif ((h>=20 and h<=24) or (h>=0 and h<6)): print "Buenas noches" saludador()
false
5253599aa98ef4900197ef5616ceb94936048fe2
K23Nikhil/PythonBasicToAdvance
/Program13.py
507
4.125
4
#Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. startIndex = 0 endIndex = 10 FabSer = [] i = 1 if startIndex ==1: FabSer.append(startIndex) FabSer.append(startIndex) else: FabSer.append(startIndex) FabSer.append(startIndex + 1) while i < endIndex: sum = FabSer[i] + FabSer[i -1] FabSer.append(sum) i = i+1 print(FabSer)
true
8929a0b3e7d0dcbf04f6bc907de9f9aece86c9d1
spoorthyandhe/project-98
/game.py
885
4.34375
4
import random print(" Number guessing game :") number = random.randint(1,9) chances = 0 print ("Guess a number (between 1 and 9): ") # while loop to count the umbers of changes while chances <5: guess = int(input("Enter your guess: ")) #compare the user enteres number with the number if guess == number: #if number entered by user is same as the generated #number by randint function then break from loop using loop #control statement "break" print(" Congatulation YOU WON!!!") break elif guess < number: print("your guess was too low: guess a number higher than ",guess) else: print("your guess was too high: guess a number lower than ",guess) chances = chances+1 #check whether the user gussed the correct number if not chances <5 : print("YOU LOSE!!! The number is",number)
true
ef05347532b0eab4ddede67797e8a39725fefc07
Mfrakso/Week3
/FiberOptic If_Statements.py
1,895
4.4375
4
''' File: FiberOptic If_Statments.py Name: Mohammed A. Frakso Date: 14/12/2019 Course: DSC_510 - Introduction to Programming Desc: Programe calculates the need of fiber optic cable and evaluate a bulk discount for a user Usage : This program is built to take the 'Company Name' and 'required length(in feet)' of optic cable for installation as input. Then Calculate the total cost that will vary upon the length of optic cable requested for installation and printing receipt for the total cost for installation to user. ''' # Display Welcome Message message = "Welcome to the store" print(message) # Retrieve the company name companyName = input('What is your company name? \n') print('Your company name is', companyName) # Retrieve the number of fiber optic prompt = 'What is the number of feet of fiber optic cable to be installed? \n' numberFeet = float(input(prompt)) int(numberFeet) # Calculate the installation cost of fiber optic # Create a variable cost = 0.87 # Print Number feet print(' The number of feet of fiber optic is', numberFeet) print(numberFeet) # cable cost will change based on length input by user if 100 < numberFeet <= 250: # If Cabal length is between 101 and 250 then price is 0.80 cost = 0.80 elif 250<numberFeet <= 500: # If Cabal length is between 251 and 500 then price is 0.70 cost = 0.70 elif numberFeet > 500: # If Cabal length is more than 500 then price is 0.5 cost = 0.50 else: cost = 0.87 # If Cabal length is less than 100 then price is 0.87 # Calculate the installation cost of fiber optic totalCost = (numberFeet * cost) print("The installation cost is", totalCost) # Printing out the receipt print('Printing Receipt for Company: ', companyName) print('Length of Fiber optic Cable in Feet: ', numberFeet) print('Cable installation Cost Calculation:', numberFeet,'ft x $',cost) print('Total Cost: $', totalCost )
true
ea17d0d98e64c444106d0c018c8ac171a84c3b32
pangyang1/Python-OOP
/Python OOP/bike.py
794
4.15625
4
class Bike(): """docstring for Bike.""" def __init__(self,price,max_speed,miles): self.price = price self.max_speed =max_speed self.miles = 0 def displayinfo(self): print "The price is $" + str(self.price) + ". The max speed is " + str(self.max_speed) + ". The total miles are " + str(self.miles) def ride(self): self.miles +=10 print "Riding" return self def reverse(self): if self.miles >5: self.miles -=5 print "Reversing" return self bike1 = Bike(200, "25mph",0) bike2 = Bike(100, "20mph",0) bike3 = Bike(400, "30mph",0) bike1.ride().ride().ride().reverse().displayinfo() bike2.ride().ride().reverse().reverse().displayinfo() bike3.reverse().reverse().reverse().displayinfo()
true
b38b3a2082f4da3dc269982aab04ac935a5e96bd
IeuanOwen/Exercism
/Python/triangle/triangle.py
1,087
4.25
4
import itertools def valid_sides(sides): """This function validates the input list""" if any(side == 0 for side in sides): return False for x, y, z in itertools.combinations(sides, 3): if (x + y) < z or (y + z) < x or (z + x) < y: return False else: return True def is_equilateral(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x == y and x == z: return True else: return False def is_isosceles(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x == y or y == z or x == z: return True else: return False def is_scalene(sides): for x, y, z in itertools.combinations(sides, 3): res = valid_sides(sides) if not res: return False if x != y and x != z and y != z: return True else: return False
true
9f865f967c9a164b95c49e5f84b17d5d0204c5f8
IeuanOwen/Exercism
/Python/prime-factors/prime_factors.py
428
4.1875
4
"""Return a list of all the prime factors of a number.""" def factors(startnum): prime_factors = [] factor = 2 # Begin with a Divisor of 2 while startnum > 1: if startnum % factor == 0: prime_factors.append(factor) startnum /= factor # divide the startnum by the factor else: # If the divisor is not a factor increase it by 1 factor += 1 return prime_factors
true
375e0bf125558618bb74238ec40264ce59ca9344
Jeevan-Palo/oops-python
/Polymorphism.py
1,050
4.5
4
# Polymorphism achieved through Overloading and Overriding # Overriding - Two methods with the same name but doing different tasks, one method overrides the other # It is achieved via Inheritance class Testing: def manual(self): print('Automation Tester with 5 years Experience') class ManualTest(Testing): def manual(self): super().manual() print('Manual Tester with 5 years Experience') test = ManualTest() test.manual() # Method Overloading # Python does not support method overloading by default # Method overloading in Python is that we may overload the methods but can only use the latest defined method. # The below example object will call same method with and without parameter class Testing_MOL: def Hello(self, testing=None): if testing is not None: print('Hello ' + testing) else: print('Hello Manual Tester') # Create an instance obj = Testing_MOL() # Call the method obj.Hello() # Call the method with a parameter obj.Hello('Automnation Tester')
true
cc50929915eae260da1160b515b30cbea4268108
MicheSi/Data-Structures
/binary_search_tree/sll_queue.py
2,213
4.1875
4
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList2: def __init__(self): # first node in the list self.head = None self.tail = None def add_to_head(self, value): new_node = Node(value) if not self.head and not self.tail: self.head = new_node self.add_to_tail = new_node else: new_node.set_next(self.head) self.head = new_node def add_to_tail(self, value): # regardless of if the list is empty or not, we need to wrap the value in a Node new_node = Node(value) # what if the list is empty? if not self.head and not self.tail: self.head = new_node self.tail = new_node # what if the list isn't empty? else: self.tail.set_next(new_node) self.tail = new_node def contains(self, value): current = self.head if current is None: return while current is not None: if current.get_value() == value: return True current = current.get_next() return False def remove_head(self): # what if the list is empty? if not self.head and not self.tail: return # what if it isn't empty? else: # we want to return the value at the current head value = self.head.get_value() if self.head == self.tail: self.head = None self.tail = None return value else: self.head = self.head.get_next() return value def get_max(self): current = self.head value = current.value if not self.head and not self.tail: return if self.head == self.tail: return current.value while current.get_next() is not None: if current.value > value: value = current.value current = current.get_next() else: current = current.get_next return value
true
572e08a21a64a898d60e2bd26bec4f350da44d65
his1devil/lintcode-note
/flattenlist.py
449
4.1875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): """ Given a list, each element in the list can be a list or integer. Flatten it into a simply list with integers. 递归 """ def flatten(self, nestedList): result = [] if isinstance(nestedList, int): return [nestedList] for i in nestedList: result.extend(self.flatten(nestedList)) return result
true
cd54caff7a61f615fd855cc9a012871652fb4c2a
his1devil/lintcode-note
/rotatestring.py
1,055
4.25
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): """ Given a string and an offset, rotate string by offset. (rotate from left to right) offset=2 => "fgabcde" """ def rotateString(self, s, offset): # 防止offset越界,offset 对len(s)取模 if s is None or len(s) == 0: return -1 offset = offset % len(s) first = s[:len(s) - offset] end = s[len(s) - offset:] s = first[::-1] + end[::-1] s = s[::-1] return s # 借助mutable structure 原地变换字符串 因为字符串不可变 def rotateString2(self, s, offset): if s is None or len(s) == 0: return -1 offset = offset % len(s) self.reverse(s, 0, len(s) - offset - 1) self.reverse(s, len(s) - offset, len(s) - 1) self.reverse(s, 0, len(s) - 1) def reverse(self, _str, start, end): while start < end: _str[start], _str[end] = _str[end], _str[start] start += 1 end -= 1
true
6c78661c73b2892e248eff64a7395e6b1e84359b
paulmagnus/CSPy
/mjenkins-programs/windchill.py
447
4.3125
4
def windChill(): print 'Welcome to the windchill calculator!' temperature = input("Enter the temperature: ") windspeed = input("Enter the wind speed: ") windchill = 35.74 + (0.6215 * temperature) - (35.75 * (windspeed ** 0.16)) + (0.4275 * temperature * (windspeed ** 0.16)) print 'At ' + str(temperature) + ' degrees, with a wind speed of ' + str(windspeed) + ' miles per hour, the windchill is: ' + str(windchill) + ' degrees' windChill()
true
fd8809831149570c0750c8d612f2bd99c0d31479
katyduncan/pythonintro
/lesson2/8IntegersFloats.py
409
4.1875
4
# Check data type print(type(3)) print(type(4.3)) # whole number float print(type(4.)) # operation involving int and float always results in float print(3 + 2.5) # cut decimal off float to convert to int print(int(49.7)) # 49 no rounding occurs # add .0 to convert int to float print( float(3520 + 3239)) # 6759.0 # NOTE floats are approx, 0.1 is actually slightly more print(.1 + .1 + .1 == .3) # False
true
a57f59a87013bed7f79d9524af8858e8c48c024d
Bumskee/-Part-2-Week-2-assignment-21-09-2020
/Problem 2.py
483
4.15625
4
"""Problem 2 finding the average score tests of 3 students""" #Assigning the value for the student scores student1 = 80 student2 = 90 student3 = 66.5 #Function for finding the average out of those student scores def findAverage(student1, student2, student3): scoreAverage = (student1 + student2 + student3) / 3 return scoreAverage #Assigning the value to the average variable average = findAverage(student1, student2, student3) #prints the value of average print(average)
true
bdda614bb2a711d293961a0ce85ee4df83f0c6c6
kosiA1/Pythonlevel1
/Practice 2.py
1,988
4.15625
4
#------------------------------------------------------------------------------- # Name: module 2 # Purpose: Learning Variables # Author: Kosisochi # Created: 06-12-2020 # Copyright: (c) anado 2020 # Licence: <your licence> #------------------------------------------------------------------------------- #Representing Variables x = 1 print(x) print("\n") name = "Kosisochi" print(name) print("\n") #addition of numbers sum = 1+2 print (sum) print("\n") # addition of Variables x = 2 y = 4 sum = x + y print (sum) print("\n") #X was 1 and now has been replaced by the second value of x x = 1 x = 10 print (x) print("\n") #adding a string to a print x = 1 print("The number is", x) print("\n") name = "Kosisochi" print ("The name is", name) print("\n") sum = 1+2 print("The sum is", sum) print("\n") x = 2 y = 4 sum = x+y print("The sum is",sum) print("\n") x = 1 print ("x is", x) x = 10 print("x is now", x) print("\n") #Input #input is treated like a sting regardless of what is entered x = input ("What is your favourite color ") print ("Your favorite color is", x) print("\n") #It returns an empty string input() #The input is assigned a variable x = input() name = input("What is your name? ") # .format #"{placeholder}".format(value) # {placeholders} is used to specify how many characters of a string is going to show #{placeholder} is identified with {:.x} "x being whatever number" print("{}".format(42)) # The placeholder above is empty so it shows all characters print("\n") print("{} {} {}".format(42, "Hello World", 10.00)) #These place holders would make only the selected number of Charaters get printed print("\n") print("{:.1}".format("Hello World")) print("{:.3}".format("Hello World")) print("{:.1}{:.3}".format("Hello","World")) #using variables print("\n") name = "Kosisochi" number = "123456789" print("{:.4} {:.3}".format(name,number)) print("My 1st four letters is{:.4}and the 1st three numbers is{:.3}".format(name,number))
false
63d1c825ba44f094558ed37759d9f9d018a7a484
samanthaalcantara/codingbat2
/Logic-1/caught_speeding.py
758
4.28125
4
""" Date: 06 12 2020 Author: Samantha Alcantara Question: You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. """ #Answer def caught_speeding(speed, is_birthday): speed_adj = 0 if (is_birthday == True): speed_adj = 5 if speed < 61 + speed_adj: return 0 if speed < 81 + speed_adj: return 1 return 2 # no ticket small ticket big ticket # 0 <= Speed < 61 61<= Speed < 81 Speed >= 81
true
19a6de32c4a6c72a5dbd89ad23600d9de5893ce6
peterhchen/runBookAuto
/code/example/01_Intro/05_Age.py
539
4.4375
4
#!/usr/bin/python3 # Display different format based on age. # Age 1 to 18: Important # Age 21, 50, or >= 65: Important # All othera Ages: Not important # Get age and store in age age = eval (input('Enter age: ')) # if age >= 1 and <= 18: important if (age >= 1) and (age <= 18): print ("Important") # if age == 21 or 50: important elif (age == 21) or (age == 50): print ("Important") # if age < 65, convert the true to false. elif not(age < 65): print ("Important") # else not import. else: print ("Not Important")
true
3b3012a175b7e66ea1d9d57b493b6df098ae68f3
peterhchen/runBookAuto
/code/example/01_Intro/03_UnitConv.py
449
4.28125
4
#!/usr/bin/python3 # Problem: Receive miles and convert to kilometers # kilometers = miles * 1.6 # Enter Miles 10. # 10 Miles euqls to 16 kilometer. # ask the user to input miles and assign it to the mile variable. mile = input ('Enter Mile: ') # Convert the string to integer. mile = int (mile) # Perform multiplication 1.6 kilometer = mile * 1.6034 # print result using format. print ("{} mile equals {} kilometer ".format (mile, kilometer))
true
36b71ce66e635ac8c938e50bd3f18cc2731ec79e
peterhchen/runBookAuto
/code/example/07_Dict/01_Dict.py
460
4.4375
4
#!/usr/bin/python3 myDict = {"fName": "Peter", "lName": "Chen", "address": "652 Calle Victoria"} print("My Name:", myDict["fName"]) myDict["address"] = "1225 Vienna Drive" myDict ["city"] = "Suunyvale" print ("Is there a city:", "city" in myDict) print(myDict.values()) for i in myDict: print (i) myDict.clear() employees = [] fName, lName = input ("Enter Employee Name: ").split() employees.append({'fName': fName, 'lName': lName}) print (employees)
false
c208d5ee251a4de8b5d953ad057143ab9ef49bb2
peterhchen/runBookAuto
/code/example/01_Intro/04_Calculator.py
655
4.40625
4
#!/usr/bin/python3 # Enter Calculator: 3 * 6 # 3 * 6 = 18 # Store the user input of 2 number and operator. num1, oper , num2 = input ('Enter Calculator: ').split() # Conver the strings into integers num1 = int (num1) num2 = int (num2) # if + then need to provide the output based on addition # Print the result. if oper == '+': print ("{} + {} = {}".format(num1, num2, num1+num2)) elif oper == "-": print ("{} - {} = {}".format(num1, num2, num1-num2)) elif oper == "*": print ("{} * {} = {}".format(num1, num2, num1*num2)) elif oper == "/": print ("{} / {} = {}".format(num1, num2, num1/num2)) else: print ("Only support + - * .")
true
91679fa0afb893e30dd4c04fd8acfd1b85659c36
peterhchen/runBookAuto
/code/example/05_Func/06_MultiValue.py
208
4.15625
4
#!/usr/bin/python3 # How to return the multiple values. def mult_divide (num1, num2): return (num1 * num2), (num1 / num2) mult, divide = mult_divide (5, 4) print ("5 * 4 =", mult) print ("5 / 4 =", divide)
false
4a425f72e61d4dd08b5c413a2ecec116ec5c767e
jamariod/Day-5-Exercises
/WordSummary.py
397
4.1875
4
# Write a word_histogram program that asks the user for a sentence as its input, and prints a dictionary containing the tally of how many times each word in the alphabet was used in the text. any_word = input( "Enter any word to tally how many times each letter in the alphabet was used in the word: ") word_split = any_word.split(' ') i = {a: any_word.count(a) for a in word_split} print(i)
true
641aae71ec1efa9634631c16e6b8faa5f4742706
boringPpl/Crash-Course-on-Python
/Exercises on IDE/7 String/ex7_2_string.py
614
4.375
4
'''Question 7.2: Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km". ''' def convert_distance(km): miles = km * 0.621 # 1km is equal to approximately 0.621 miles result = "{} km equals {} miles" return result print(convert_distance(19.2)) # Should be: 19.2 km equals 11.92 miles print(convert_distance(8.8)) # Should be: 8.8 km equals 5.46 miles print(convert_distance(17.6)) # Should be: 17.6 km equals 10.92 miles
true
59155ff91c8651d8db1bd9273b46e12b9de074c1
boringPpl/Crash-Course-on-Python
/Exercises on IDE/6 For Loops/ex6_2_for.py
441
4.65625
5
'''Question 6.2: This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling mul_table(1, 3) will print out: 1 2 3 2 4 6 3 6 9 ''' def mul_table(start, stop): for x in ___: for y in ___: print(str(x*y), end=" ") print() mul_table(1, 3) # Should print the multiplication table shown above
true
2f0d5f695e42fb4e7027352362c147ba68a491be
boringPpl/Crash-Course-on-Python
/Exercises on IDE/3 Function/ex3_2_function.py
994
4.65625
5
''' Question 3.2: This function converts kilometers (km) to miles. 1. Complete the function. Your function receive the input kilometers, and return the value miles 2. Call the function to convert the trip distance from kilometers to miles 3. Fill in the blank to print the result of the conversion 4. Calculate the round-trip in miles by doubling the result, and fill in the blank to print the result ''' # 1) Complete the function to return the result of the conversion def convert_distance(km): miles = km * 0.621 # 1km is equal to approximately 0.621 miles return miles trip_in_km = 50 # 2) Convert trip_in_km to miles by calling the function above trip_in_miles = convert_distance(trip_in_km) # 3) Fill in the blank to print the result of the conversion print("The distance in miles is " + str(trip_in_miles)) # 4) Calculate the round-trip in miles by doubling the result, # and fill in the blank to print the result print("The round-trip in miles is " + str(trip_in_miles * 2))
true
3664bf0af663c33035ab8e699dd1f2d5f8af76cc
boringPpl/Crash-Course-on-Python
/Exercises on IDE/6 For Loops/ex6_3_for.py
636
4.6875
5
'''Question 6.3: The display_even function returns a space-separated string of all positive numbers that are divisible by 2, up to and including the maximum number that's passed into the function. For example, display_even(4) returns “2 4”. Fill in the blank to make this work. ''' def display_even(max_num): return_string = "" for x in ___: return_string += str(x) + " " return return_string.strip() print(display_even(6)) # Should be 2 4 6 print(display_even(10)) # Should be 2 4 6 8 10 print(display_even(1)) # No numbers displayed print(display_even(3)) # Should be 2 print(display_even(0)) # No numbers displayed
true
2cf55be5afac37d8737a9e4254ffccb2394ce111
nigelginau/practicals_cp1404
/prac_03/password_entry.py
872
4.3125
4
"""" Nigel Ginau """ """"write a program that asks the user for a password, with error-checking to repeat if the password doesn't meet a minimum length set by a variable. The program should then print asterisks as long as the password. Example: if the user enters "Pythonista" (10 characters), the program should print "**********".""""" minimum_length = 5 length_of_password = 0 while length_of_password < minimum_length: password = input("Please input your password :") length_of_password = len(password) print("Password must be more than {0} characters and greater than {1} characters".format(minimum_length, length_of_password)) print("Password is the correct length of {} characters".format(minimum_length)) asterisks = length_of_password * "*" print(asterisks)
true
6570314af2afc2a8491dfeabec25383deda462e2
tikale/SOLID_Python
/SOLID_SingleResponsibility.py
2,145
4.25
4
# 1. Single Responsibility Principle - jedna odpowiedzialność # Każda funkcja, klasa lub modół powinien mieć tylko jeden powód do zmiany. # Taki kod łatwiej zrozumieć, naprawić i utrzymać. Łatwiej się go testuje. # klasa prostokąt ma 3 odpowiedzialności class Rectangle: def __init__(self, width=0, height=0): self.width = width self.height = height def draw(self): #Rysujemy print("\"Rysujemy prostokat\"") def area(self): return self.width * self.height def printRE(self): print (f"Szerokosc = {self.width}") print (f"Wysokosc = {self.height}") print (f"Powierzchnia = {self.area()}") # ========================================================= # We can split it into three... class GeometricRectangle: def __init__(self, width=0, height=0): self.width = width self.height = height def area(self): return self.width * self.height class DrawRectangle: def draw(self): # Do some drawing print("\"Rysujemy prostokat\"") class PrintRectangleData: def __init__(self, width=0, height=0, area=0): self.width = width self.height = height self.area = area print (f"Szerokosc = {self.width}") print (f"Wysokosc = {self.height}") print (f"Powierzchnia = {self.area}") # ========================================================== # The downside of this solution is that the clients of the this code have to deal # with few classes. A common solution to this dilemma is to apply the Facade # pattern. class RectangleFacade: def __init__(self, width=0, height=0): self.width = width self.height = height self.DR = DrawRectangle() self.GR = GeometricRectangle(width, height) def area(self): return self.GR.area() #self.width * self.height def DrawRe(self): return self.DR.draw() def PrintREdata(self): PrintRectangleData(self.width, self.height, self.area()) # ============================================================= # Run script print("No to zaczynamy:") print("") print("klasa Rectangle:") r1 = Rectangle(2, 3) r1.printRE() r1.draw() print("") print("klasa RectangleFacade:") r2 = RectangleFacade(5,9) r2.DrawRe() r2.PrintREdata()
false
e00334f1474a2caa644d4f60498ffc3497570701
Arslan0510/learn-basic-python
/3strings.py
574
4.40625
4
language = 'Python' # print(len(language)) # Access each individual letter # letter = language[3] # letter = language[0:3] # first to third letter # letter = language[1:] # skip first letter and show all the remaining part letter = language[-1] # get reverse of string # String Methods languageString = 'Street of The Dead White Walkers RIP 1 EPISODE' upper_language = languageString.upper() lower_language = languageString.lower() find_text = languageString.find("Dead") replace_text = languageString.replace("White", "Black") print(replace_text)
true
1cbf04f88b879ad37b959c8b41a19ec8fe0b1b9a
dguzman96/Python-Practice
/Chapter 4/counter.py
336
4.21875
4
#Counter #Demonstrates the range() function print("Counting:") for i in range(10): print(i, end = " ") print("\n\nCounting by fives:") for i in range (0, 50, 5): print(i, end = " ") print("\n\nCounting backwards:") for i in range (10, 0, -1): print(i,end = " ") input("\n\nPress the enter key to exit.")
false
7866ce25883a04152b4587c683ff0be544a85ce5
bigbillfighter/Python-Tutorial
/Part1/chap9_p2.py
845
4.21875
4
#the python library practise from collections import OrderedDict favourite_languages = OrderedDict() favourite_languages['Lily'] = 'C' favourite_languages['Max'] = 'Ruby' favourite_languages['Lucas'] = 'Java' favourite_languages['Peter'] = 'C' for name, language in favourite_languages.items(): print(name.title()+"'s favourite language is "+language.title()) #random library includes the meethods that generate random numbers #for example, randint(a, b) can return an integer that between a and b from random import randint num = list(range(1, 7)) for i in range(1,10000): x = randint(1,6) num[x-1]+=1 print(num) #when we define classes, we let all the first letters capital instead of using '_' #like what we do on functions #for example: class MyFavouriteFood(): #def get_my_favourite_food(self):
true
c7a140cabdf8de7fb2dc7b46420ec7951b8e8052
felipeandrademorais/Python
/Basico/BasicoPython.py
981
4.25
4
""" ########### Imprimir valores ############# num_int = 5 num_dec = 7.3 val_str = "Qualquer valor" print("Concatenando Inteiro:", num_int) print("Concatenando Inteiro: %i" %num_int) print("Concatenando Inteiro" + str(num_int)) print("Concatenando Decimal: ", num_dec) print("Concatenando Decimal: %.10f" %num_dec) print("Concatenando Decimal:" + str(num_dec)) print("Concatenando String: ", val_str) print("Concatenando String: %s", val_str) print("Concatenando String: " + val_str) ########### Entrada de Dados ############# login = input("Login: ") senha = input("Senha: ") print("Login informado %s e a Senha %s" %(login, senha)) ########### Operadores Matemátcos ############# print(10 + 10) #20 print(10 - 10) #0 print(10*10) #100 print(10/5) #2 print(10//6) #retira as casas decimais print(2**4) #Potênciação print(2**(1/2)) #raiz quadrada do número ########### Resto de uma divisão ############# print(3%2) #1 (2 esta contido uma vez dentro do 3) """
false
a1de6e3402e992ba1cb9503dd3308d1c6fa31c38
yourback/OfflineDataConversionAndDrawingSoftware
/clac_module/rangecalc.py
1,171
4.125
4
# 区间数据计算 # 获取最小值 def max_calc(list_data): i = list_data[0] for d in list_data: if i < d: i = d return i def min_calc(list_data): i = list_data[0] for d in list_data: if i > d: i = d return i def average_calc(list_data): i = 0 for d in list_data: i += round(d, 2) return round(i / len(list_data), 2) def max_min(list_data): return round(max_calc(list_data) - min_calc(list_data), 2) def get_range_values(base_data): return { "max": max_calc(base_data), "min": min_calc(base_data), "diff": max_min(base_data), "average": average_calc(base_data), "integral": integral_range_values(base_data), } def integral_range_values(list_data): result = 0 for index, data in enumerate(list_data): # 如果是第一项不做处理 if index == 0: continue else: # 如果不是第一项,则这个小面积为 (data - list_data[index-1]) /2 result += (data + list_data[index - 1]) / 2 # print('结果:%s' % ) return round(result, 3)
false
f04a47dd64a1cae114c053e53a1ce85533fec5e9
mrggaebsong/Python_DataStructure
/PythonSort.py
2,576
4.125
4
def bubble_sort(list): for last in range(len(list)-1,-1,-1): swap = False for i in last: if l[i] > l[i+1]: l[i], l[i+1] = l[i+1], l[i] swap = True if not swap: break return list l = [5,6,2,3,0,1,4] print("Bubble Sort") print(l) bubble_sort(l) print(l) print() def selection_sort(list): for last in range(len(list)-1,-1,-1): biggest = l[0] biggest_i = 0 for i in range(1,last+1): if l[i] > biggest: biggest = l[i] biggest_i = i l[last], l[biggest_i] = l[biggest_i], l[last] return list l = [6,9,8,5,4] print("Selection Sort") print(l) selection_sort(l) print(l) print() def insertion(list): for i in range(1,len(list)): iEle = l[i] for j in range(i, -1, -1): if iEle > l[j-1] and j > 0: l[j] = l[j-1] else: l[j] = iEle return list l = [8,6,7,5,9] print("Insertion Sort") print(l) insertion(l) print(l) print() def merge_sort(list): #print("Splitting ",list) if len(list)>1: mid = len(list)//2 lefthalf = list[:mid] righthalf = list[mid:] merge_sort(lefthalf) merge_sort(righthalf) i=j=k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: list[k]=lefthalf[i] i=i+1 else: list[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): list[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): list[k]=righthalf[j] j=j+1 k=k+1 #print("Merging ",list) l = [5,3,6,1,2,7,8,4] print("Merge Sort") print(l) merge_sort(l) print(l) print() def quick_sort(list, first, last): if first < last: pos = partition(list, first, last) #print(list[first:pos-1], list[pos+1:last]) # Start our two recursive calls quick_sort(list, first, pos-1) quick_sort(list, pos+1, last) def partition(list, first, last): wall = first for pos in range(first, last): if list[pos] < list[last]: # last is the pivot list[pos], list[wall] = list[wall], list[pos] wall += 1 list[wall], list[last] = list[last], list[wall] #print(wall) return wall l = [5,1,4,9,6,3,8,2,7,0] print("Quick Sort") first = 0 last = len(l) - 1 print(l) quick_sort(l,first,last) print(l) print()
false
ec9d6f83ed95af87724cc60be71c9c14d3b1ae3a
Yash25gupta/Python
/Tutorial_Codes/12 Chapter - Lambda Expressions.py
765
4.21875
4
# Tutorial 150 - Lambda Expression # anonymous function def add(a,b): return a+b add2 = lambda a,b : a+b print(add2(2,3)) multiply = lambda a,b : a*b print(multiply(2,3)) print(add) print(add2) print(multiply) # Tutorial 151 - Lambda Expression Practice def is_even(a): return a % 2 ==0 print(is_even(5)) iseven2 = lambda a : a % 2 == 0 print(iseven2(6)) def lastchar(s): return s[-1] print(lastchar('yash')) lastchar2 = lambda s : s[-1] print(lastchar2('yash')) # lambda with if else def func(s): if len(s) > 5: return True return False func2 = lambda s : True if len(s) > 5 else False func3 = lambda s : len(s) > 5 print(func('yashg')) print(func2('yashgup')) print(func3('yasg'))
false
a2aaf99fcc1b5ce257d8506092ed273c1fd432a3
amitsindoliya/datastructureandalgo
/selection_sort.py
577
4.3125
4
## selection Sort ## ## In selection sort we find the minimum element or maximum element # of the list and place it at the start # continue this operation until we have an sorted array # complexity O(N^2)/2 # unstable def selection_sort(iterable): for i in range(len(iterable)-1): for j in range(i+1,len(iterable)): if iterable[j] < iterable[i]: iterable[i], iterable[j] = iterable[j], iterable[i] return iterable if __name__ == "__main__": iterable = [ 4,2,5,2,-6,2,8,5,2,1,8] print(selection_sort(iterable))
true
f65d0d677044624e03d82e2f43cb8c48a94f7226
razmikmelikbekyan/ACA_2019_python_lectures
/homeworks/CapstoneProject/database/books.py
1,422
4.28125
4
from typing import Dict, List BOOKS = "database/books.txt" def create_books_data(): """ Creates an empty txt file for storing books data. If the file already exists, it should not do anything. """ pass def get_all_books() -> List[Dict]: """Returns all books data in a list, where each item in a list is one book.""" pass def find_book(code: str) -> Dict: """ Finds book by its code in library and returns it's data in the form of dict. If the book is not in the library, return an empty dict. For example: { 'code': 'a1254', 'name': 'The Idiot', 'author': 'Fyodor Dostoyevsky', 'quantity': 4, 'available_quantity': 2 } """ pass def add_book(code: str, name: str, author: str, quantity: int): """Adds given book to the database, which is a txt file, where each row is book.""" pass def delete_book(code: str): """Deletes book from database.""" pass def _interact_with_user(code: str, increase: bool): """ Helper function for interacting with user. It increases or decreases available_quantity by 1. """ pass def give_book_to_user(code: str): """ Gives book to user from library: decreases book available_quantity by 1. """ pass def get_book_from_user(code: str): """ Gets book from user back to library: increases book available_quantity by 1. """ pass
true
cc9f9dc9810af12141c6f005a9b951c25bffd1e0
lowks/py-etlt
/etlt/cleaner/DateCleaner.py
1,871
4.3125
4
import re class DateCleaner: """ Utility class for converting dates in miscellaneous formats to ISO-8601 (YYYY-MM-DD) format. """ # ------------------------------------------------------------------------------------------------------------------ @staticmethod def clean(date): """ Converts a date in miscellaneous format to ISO-8601 (YYYY-MM-DD) format. :param str date: The input date. :rtype str: """ # Return empty input immediately. if not date: return date parts = re.split('[\-/\. ]', date) if len(parts) == 3 or (len(parts) == 4 and (parts[3] in ('00:00:00', '0:00:00'))): if len(parts[0]) == 4 and len(parts[1]) <= 2 and len(parts[2]) <= 2: # Assume date is in YYYY-MM-DD of YYYY-M-D format. return parts[0] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[2])[-2:] if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 4: # Assume date is in DD-MM-YYYY or D-M-YYYY format. return parts[2] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:] if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 2: # Assume date is in DD-MM-YY or D-M-YY format. year = '19' + parts[2] if parts[2] >= '20' else '20' + parts[2]; return year + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:] if len(parts) == 1 and len(date) == 8: # Assume date is in YYYYMMDD format. return date[0:4] + '-' + date[4:2] + '-' + date[6:2] # Format not recognized. Just return the original string. return date # ----------------------------------------------------------------------------------------------------------------------
true
5f59166ef3478ece7bb0bed7ea6e3fc02ef1ca44
sb17027/ORS-PA-18-Homework07
/task4.py
1,336
4.34375
4
""" =================== TASK 4 ==================== * Name: Number of Appearances * * Write a function that will return which element * of integer list has the greatest number of * appearances in that list. * In case that multiple elements have the same * number of appearances return any. * * Note: You are not allowed to use built-in * functions. * * Note: Please describe in details possible cases * in which your solution might not work. * * Use main() function to test your solution. =================================================== """ # Write your function here def mostOccurences(arr): mostNumber = arr[0] maxNumberOfOccurences = 1 currNumberOfOccurences = 0 currNumber = 0 i = 1 while i < len(arr): currNumber = arr[i] currNumberOfOccurences = 0 j = 0 while j < len(arr): if(arr[j] == currNumber): currNumberOfOccurences = currNumberOfOccurences + 1 j = j + 1 if currNumberOfOccurences > maxNumberOfOccurences: maxNumberOfOccurences = currNumberOfOccurences mostNumber = currNumber i = i + 1 return mostNumber def main(): arr = [1, 3, 4, 6, 1, 1, 12, 12, 12, 12, 12, 12, 12] mostNumber = mostOccurences(arr) print("Number with most occurences: ", mostNumber) main()
true
115490da841034c40a2c2c3029adede809f4c499
mali0728/cs107_Max_Li
/pair_programming/PP9/fibo.py
1,017
4.25
4
""" PP9 Collaborators: Max Li, Tale Lokvenec """ class Fibonacci: # An iterable b/c it has __iter__ def __init__(self, val): self.val = val def __iter__(self): return FibonacciIterator(self.val) # Returns an instance of the iterator class FibonacciIterator: # has __next__ and __iter__ def __init__(self, val): self.index = 0 self.val = val self.previous = 1 self.previous_previous = 0 def __next__(self): if self.index < self.val: next_value = self.previous + self.previous_previous self.previous_previous = self.previous self.previous = next_value self.index += 1 return next_value else: raise StopIteration() def __iter__(self): return self # Allows iterators to be used where an iterable is expected if __name__ == "__main__": fib = Fibonacci(10) print(list(iter(fib))) fib2 = Fibonacci(2) print(list(iter(fib2)))
true
379181112c350d080fae6376a2cae3029ec35a9d
goulartw/noob_code
/curso-noob-python/variaveis-tipos-dados/hello.py
1,409
4.3125
4
# hello world # print("hello world") # string # nome = input("Qual é o seu nome: ") # print(nome) # inteiros # numero1 = int(input("Digite um número: ")) # numero2 = int(input("Digite um número: ")) # numero3 = int(input("Digite um número: ")) # calc = numero1 + numero2 * numero3 # print(calc) # float # numero1 = float(input("Digite um número: ")) # numero2 = float(input("Digite um número: ")) # print(numero1, numero2) # booleano # numero = 11 # verdadeiro = "Verdade" # if numero == 10: # print(verdadeiro) # lista (Array) vetores # lista1 = ['diego', 'joao', 'maria'] # print(lista1) # lista1.append('thiago') # print(lista1) # lista1.insert(0, "jose") # print(lista1) # pos = lista1.index('joao') # print(pos) # lista1.remove("diego") # print(lista1) # numero_da_lista = lista1[3][0] # print(numero) # nome = lista1[1] # print(nome) # tupla # tupla = ("Diego", "João") # author = ("Diego Araujo") # print(author) # conjuntos # conjunto = {"diego", "joao", "maria"} # conjunto2 = {"diego", "fulano"} # print(conjunto2.difference(conjunto)) # dicionário # dic = { # "nome1": "Diego", # "nome2": "Joao", # "nome3": "Maria", # } # for chave, valor in dic.items(): # print(chave, valor) # string - manipulação nome = "Diego" nome1 = "diego" nome2 = "DIEGO" sobrenome = "Araujo" nome_completo = "Diego Araujo" nome_mudado = nome_completo.replace("Diego", "João") print(nome.find('o'))
false
6a98a213ff9063964adc7731056f08df3ac755ae
gatisnolv/planet-wars
/train-ml-bot.py
2,062
4.25
4
""" Train a machine learning model for the classifier bot. We create a player, and watch it play games against itself. Every observed state is converted to a feature vector and labeled with the eventual outcome (-1.0: player 2 won, 1.0: player 1 won) This is part of the second worksheet. """ from api import State, util # This package contains various machine learning algorithms import sys import sklearn import sklearn.linear_model from sklearn.externals import joblib from bots.rand import rand # from bots.alphabeta import alphabeta from bots.ml import ml from bots.ml.ml import features import matplotlib.pyplot as plt # How many games to play GAMES = 1000 # Number of planets in the field NUM_PLANETS = 6 # Maximum number of turns to play NUM_TURNS = 100 # Train for symmetric start states SYM = True # The player we'll observe player = rand.Bot() # player = alphabeta.Bot() data = [] target = [] for g in range(GAMES): state, id = State.generate(NUM_PLANETS, symmetric=SYM) state_vectors = [] i = 0 while not state.finished() and i <= NUM_TURNS: state_vectors.append(features(state)) move = player.get_move(state) state = state.next(move) i += 1 winner = state.winner() for state_vector in state_vectors: data.append(state_vector) if winner == 1: result = 'won' elif winner == 2: result = 'lost' else: result = 'draw' target.append(result) sys.stdout.write(".") sys.stdout.flush() if g % (GAMES/10) == 0: print("") print('game {} finished ({}%)'.format(g, (g/float(GAMES)*100))) # Train a logistic regression model learner = sklearn.linear_model.LogisticRegression() model = learner.fit(data, target) # Check for class imbalance count = {} for str in target: if str not in count: count[str] = 0 count[str] += 1 print('instances per class: {}'.format(count)) # Store the model in the ml directory joblib.dump(model, './bots/ml/model.pkl') print('Done')
true
09bfd4953bc24b2ab0eafac8b7bdb73074b1a4bf
bats64mgutsi/MyPython
/Programs/power.py
205
4.40625
4
# Calculates a^b using a for loop # Batandwa Mgutsi # 25/02/2020 a = eval(input("Enter a: ")) b = eval(input("Enter b: ")) ans = 1 for _ in range(1, b+1): ans *= a print(a, "to the power of ", b, "is", ans)
false
41895c829a967c20cb731734748fe7f407b364a3
bats64mgutsi/MyPython
/Programs/graph.py
2,244
4.28125
4
# A program that draws the curve of the function given by the user. # Batandwa Mgutsi # 02/05/2020 import math def getPointIndex(x, y, pointsPerWidth, pointsPerHeight): """Returns the index of the given point in a poinsPerWidth*pointsPerHeight grid. pointsPerWidth and pointsPerHeight should be odd numbers""" # These calculations take the top left corner as the (0;0) point # and both axes increase from that point. originRow = int(pointsPerHeight/2) originColumn = int(pointsPerWidth/2) # A positive x value increases the column, and vice versa # A positive y value decrease the row since the above calculations took the row as increasing # when going downwards. pointRow = originRow - y pointColumn = originColumn + x index = pointRow*pointsPerWidth+pointColumn return index def printGraph(graph, pointsPerWidth, pointsPerHeight): for row in range(pointsPerHeight): for column in range(pointsPerWidth): print(graph[row*pointsPerWidth+column], end='') print() def drawCurve(function, graph, pointsPerWidth, pointsPerHeight, fill='o'): output = list(graph) halfOfXAxis = int(pointsPerWidth/2) for x in range(-halfOfXAxis, halfOfXAxis+1): try: # Using a try/except will prevent the program from crashing in case an error occurs while # evaluating the function at the current x value. For example, if the function is a hyperbola # the try/except will prevent the program from crashing when x is an asymptote of the function. y = eval(function) except: continue y = round(y) pointIndex = getPointIndex(x, y, pointsPerWidth, pointsPerHeight) if pointIndex < 0 or pointIndex >= len(buffer): continue else: output[pointIndex] = fill return output # Using a grid with [-10, 10] endpoints buffer = list(''.rjust(21*21)) # Draw the axes for y in range(-10, 11): buffer[getPointIndex(0, y, 21, 21)] = '|' buffer = drawCurve('0', buffer, 21, 21, '-') buffer[getPointIndex(0, 0, 21, 21)] = '+' function = input('Enter a function f(x):\n') buffer = drawCurve(function, buffer, 21, 21) printGraph(buffer, 21, 21)
true
768ffb93219b9d95d73ec3075fbb191ed00837a6
Tobi-David/first-repository
/miniproject.py
625
4.15625
4
## welcome message print("\t\t\tWelcome to mini proj! \nThis application helps you to find the number and percentage of a letter in a message.") ## User message input user_message = input("This is my message ") ## user letter input user_letter = input("this is my letter ") ## count letter in message letter_freq = user_message.count(user_letter) ## calculate percentage total_chr = len(user_message) percentage = int(letter_freq/total_chr*100) # # print result print ("the count of", user_letter, "is", letter_freq ) print (f"the percentage of '{user_letter}' in '{user_message}' is {percentage} percent" )
true
637267a96a001520af71a7c748f1a05109726f5e
Colosimorichard/Choose-your-own-adventure
/Textgame.py
2,513
4.15625
4
print("Welcome to my first game!") name = input("What's your name? ") print("Hello, ", name) age = int(input("What is your age? ")) health = 10 if age >= 18: print("You are old enough to play.") wants_to_play = input("Do you want to play? (yes/no) ").lower() if wants_to_play == "yes": print("You are starting with", health, "health") print("Lets Play!") left_or_right = input("First choice....Left or Right? (left/right) ").lower() if left_or_right == "left": ans = input("Nice, you follow the path and reach a lake....do you swim across or go around? (across/around) ").lower() if ans == "around": print("You go around and reached the other side of the lake.") elif ans == "across": print("You managed to get across but were bit by a fish and lost 5 health") health -= 5 print("Your health is at", health) ans = input("You notice a house and a river. Which do you go to? (river/house) ").lower() if ans == "house": print("You've entered the house and are greeted by the owner... He doesn't like you.") ans = input("Give him a gift or spit in his eye? (gift/spit) ").lower() if ans == "spit": print("He did not like that and hit you over the head with a cane. You lose 5 health.") health -= 5 if health <= 0: print("You now have 0 health and you lose the game...Sucks to suck,", name,) else: print("Well,",name, ", your health is", health, "and you're not dead and im over this so You Win. Congratulations or whatever.") quit() if ans == "gift": print("He decided not to hit you with a cane. You have", health, "health left. You survived. I don't want to do this anymore, You win,", name,) else: print("You fell in the river and drowned. Sucks to suck.") else: print("You fell in that giant well directly to your right that literally anyone could see. Seriously, how did you miss that? Sucks to suck. Buh bye!") else: print("Geez, fine. Buh Bye") else: print("You are not old enough to play. I don't know why this is a question in the first place. See ya.")
true
d3f40012da083979a5c97407e2e2b6a43346ece0
december-2018-python/adam_boyle
/01-python/02-python/01-required/07-functions_intermediate_2.py
2,453
4.15625
4
# 1. Given x = [[5,2,3], [10,8,9]] students = [ {'first_name' : 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'] } z = [ {'x': 10, 'y': 20} ] x[1][0] = 15 # Changes the value 10 in x to 15 students[0]['last_name'] = 'Bryant' # Changes the last_name of the first student from 'Jordan' to 'Bryant' sports_directory['soccer'][0] = 'Andres' # Changes 'Messi' to 'Andres' in sports_directory z[0]['y'] = 30 # Changes the value 20 to 30 # 2. Create a function that given a list of dictionaries, it loops through each dictionary in the list and prints each key and the associated value. For example, given the following list: students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def names(): i = 0 while i < len(students): print('first_name -', students[i]['first_name'] + ',','last_name -', students[i]['last_name']) i += 1 names() # 3. Create a function that given a list of dictionaries and a key name, it outputs the value stored in that key for each dictionary. students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] def names(): i = 0 while i < len(students): print(students[i]['first_name']) i += 1 names() #4. Say that dojo = { 'locations': ['San Jose', 'Seattle', 'Dallas', 'Chicago', 'Tulsa', 'DC', 'Burbank'], 'instructors': ['Michael', 'Amy', 'Eduardo', 'Josh', 'Graham', 'Patrick', 'Minh', 'Devon'] } # Create a function that prints the name of each location and also how many locations the Dojo currently has. Have the function also print the name of each instructor and how many instructors the Dojo currently has. def coding(): i = 0 print(len(dojo['locations']),'LOCATIONS') while i < len(dojo['locations']): print(dojo['locations'][i]) i += 1 print('') i = 0 print(len(dojo['instructors']), 'INSTRUCTORS') while i < len(dojo['instructors'][i]): print(dojo['instructors'][i]) i += 1 coding()
true
34533f19a443b7063a4637c798b97233006acc02
Seon2020/data-structures-and-algorithms
/python/code_challenges/ll_zip/ll_zip.py
698
4.375
4
def zipLists(list1, list2): """ This function takes in two linked lists and merges them together. Input: Two linked lists Output: Merged linked list the alternates between values of the original two linked lists. """ list1_current = list1.head list2_current = list2.head while list1_current and list2_current: list1_next = list1_current.next list2_next = list2_current.next list1_current.next = list2_current list2_current.next = list1_next last_list1_current = list1_current.next list1_current = list1_next list2_current = list2_next if not list1_current and list2_current: last_list1_current.next = list2_current return list1
true
04f7f3d62fe77d102c4bf88ef08621bb6b0b1740
Seon2020/data-structures-and-algorithms
/python/code_challenges/reverse_linked_list.py
351
4.28125
4
def reverse_list(ll): """Reverses a linked list Args: ll: linked list Returns: linked list in reversed form """ prev = None current = ll.head while current is not None: next = current.next current.next = prev prev = current current = next ll.head = prev return ll
true
d70c86867376ccb77491b6d1e20c3f1a0b98bfe2
concon121/project-euler
/problem4/answer.py
688
4.3125
4
# A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. ZERO = 0 MIN = 100 MAX = 999 def isPalindrome(number): reverse = str(number)[::-1] if (str(number) == str(reverse)): return True else: return False lhs = MAX palindromes = [] while (lhs >= MIN): rhs = MAX; while (rhs >= MIN): palindrome = isPalindrome(lhs * rhs) if (palindrome): palindromes.append(lhs * rhs) rhs = rhs -1 lhs = lhs - 1 print("The largest palindrome is: ", max(palindromes))
true
7af9a74b13af5cc1c52a70970744b0a837bc52ca
cepGH1/dfesw3cep
/convTemps.py
413
4.21875
4
#°F = (°C × 9/5) + 32. #C =(F -32)*(5/9) myInput = input("please enter the temperature using either 'F' or 'C' at the end to show the scale: ") theNumber = int(myInput[:-1]) theScale = myInput[-1] print(theNumber) print(theScale) if theScale == "C": fahrenheit = (theNumber*(9/5)) + 32 print(fahrenheit, "F") if theScale == "F": centigrade = (theNumber - 32)*(5/9) print(centigrade, "C")
true
cdb5dff43e44f80ce8cc79bdc4424b24e06f1094
balvantghanekar11/python-lern
/cal1.py
686
4.21875
4
def operation(op,n1,n2): if op == "+": return n1+n2 elif op == "-": return n1-n2 elif op == "*": return n1-n2 elif op == "/": return n1-n2 elif op == "%": return n1-n2 elif op == "**": return n1**n2 else: print("Wrong Choice") while(1): print("__________ Calculator by blu ______") operator = input("Enter Your Choice (+,-,*,/,%,**) :") No1=int(input("Enter no1 :")) No2=int(input("Enter no2 :")) ans=operation(operator,No1,No2) print("Your Answer :",ans) que =input("Do you want to continue: (y/n)") if que=="n": break
false
f505a0fff46edd244a7c3472acf385440b76ae01
salcosser/learningPython
/FizzBuzz.py
542
4.21875
4
# Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number # and for the multiples of five print “Buzz”. For numbers which # are multiples of both three and five print “FizzBuzz”. def fb(): for i in range(100): if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(str(i)) fb()
false
1cb7a726b1074a78252ba83a4b358821fd6f6385
LeoBaz20/Netflix-Style-Recommender
/netflix-style-recommender-master/PythonNumpyWarmUp.py
1,770
4.28125
4
# coding: utf-8 # In[25]: # Handy for matrix manipulations, likE dot product and tranpose from numpy import * # In[26]: # Declare and initialize a 2d numpy array (just call it a matrix, for simplicity) # This how we will be organizing our data. very simple, and easy to manipulate. data = array([[1, 2, 3], [1, 2, 3]]) print (data) # In[27]: # Get dimensions of matrix data.shape # In[28]: # Declare and initialize a matrix of zeros zeros_matrix = zeros((1,2)) print (zeros_matrix) # In[29]: # Declare and initialize a matrix of ones ones_matrix = ones((1,2)) print (ones_matrix) # In[30]: # Declare and initialize a matrix of random integers from 0-10 rand_matrix = random.randint(10, size = (10, 5)) print (rand_matrix) # In[31]: # Declare and initialize a column vector col_vector = random.randint(10, size = (10, 1)) print (col_vector) # In[32]: # Access and print the first element of the column vector print (col_vector[0]) # In[33]: # Change the first element of the column vector col_vector[0] = 100 print (col_vector) # In[34]: # Access and print the first element of rand_matrix print (rand_matrix[0, 0]) # In[35]: # Access and print the all rows of first column of rand_matrix print (rand_matrix[:, 0:1]) # In[36]: # Access and print the all columns of first row of rand_matrix print (rand_matrix[0:1, :]) # In[37]: # Access the 2nd, 3rd and 5th columns fo the first row rand_matrix # Get the result in a 2d numpy array cols = array([[1,2,3]]) print (rand_matrix[0, cols]) # In[38]: # Flatten a matrix flattened = rand_matrix.T.flatten() print (flattened) # In[39]: # Dot product rand_matrix_2 = random.randint(10, size = (5,2)) dot_product = rand_matrix.dot(rand_matrix_2) print (dot_product) # In[ ]:
true
a0c0f8f6df218174460ece178e34a090775f0ccc
Annu86/learn_Python
/anu_ex8.py
824
4.125
4
# Membership and Bitwise Operators #Membership in and not in a = 14 b=10 list = [11, 12, 14, 15, 16, 17] print('a is present in the list:', a in list) print('b is present in the list:', b in list) if(a in list): print('a is present in the list') if(b not in list): print('b is not in the list') #Bitwise Operators a = 10 b = 13 c = a&b # Binary AND print(c) d = a|b # Binary OR print(d) e = a^b # Binary XOR print(e) #f = a ~ b # Binary Not #print(f) g = a<<1 # Binary Left Shift print(g) h = b>>1 # Binary Right Shift print(h) # by Jai # the ~ operator # it is actually complement of any number # we represent the number in machines by 0s and 1s # so to speak >> in binary we have 1011010 results in 90 in decimal number system # now it works like -x-1 jai = 37 shree = ~jai print(jai) print(shree)
false
52b9c167b058db6092d8f6b5dc760a306cc9b608
jdellithorpe/scripts
/percentify.py
1,497
4.15625
4
#!/usr/bin/env python from __future__ import division, print_function from sys import argv,exit import re def read_csv_into_list(filename, fs): """ Read a csv file of floats, concatenate them all into a flat list and return them. """ numbers = [] for line in open(filename, 'r'): parts = line.split() numbers.append(parts) return numbers def percentify(filename, column, fs): # Read the file into an array of numbers. numbers = read_csv_into_list(filename, fs) acc = 0 for row in numbers: acc += float(row[column-1]) for row in numbers: i = 0 for col in row: if i == column-1: print("%f " % (float(row[i])/acc), end='') else: print(row[i] + " ", end='') i += 1 print() def usage(): doc = """ Usage: ./percentify.py <input-file> <column> <field_separator> Percentify the values in a given column in a csv file. Replaces values with their relative weight in the sum of the values in the column. Sample Input File: 8 1 10 14 12 29 14 34 16 23 18 4 ./percentify.py input.txt 2 " " Sample Output: 8 0.0095 10 0.1333 12 0.2762 14 0.3238 16 0.2190 18 0.0381 """ print(doc) exit(0) if __name__ == '__main__': if len(argv) < 4: usage() percentify(argv[1], int(argv[2]), argv[3])
true
a4bd50b4ac26814d745411ca815aa8115c058d0c
bettymakes/python_the_hard_way
/exercise_03/ex3.py
2,343
4.5
4
# Prints the string below to terminal print "I will now count my chickens:" # Prints the string "Hens" followed by the number 30 # 30 = (30/6) + 25 print "Hens", 25 + 30 / 6 # Prints the string "Roosters" followed by the number 97 # 97 = ((25*3) % 4) - 100 # NOTE % is the modulus operator. This returns the remainder (ex 6%2=0, 7%2=1) print "Roosters", 100 - 25 * 3 % 4 # Prints the string below to terminal print "Now I will count the eggs:" # Prints 7 to the terminal # 4%2=[0], 1/4=[0] # 3 + 2 + 1 - 5 + [0] - [0] + 6 # NOTE 1/4 is 0 and not 0.25 because 1 & 4 are whole numbers, not floats print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # Prints the string below to terminal print "Is it true that 3 + 2 < 5 - 7?" # Prints false to the screen # 5 < -2 is false # NOTE the < and > operators check whether something is truthy or falsey print 3 + 2 < 5 - 7 # Prints the string below followed by the number 5 print "What is 3 + 2?", 3 + 2 # Prints the string below followed by the number -2 print "What is 5 - 7?", 5 - 7 # Prints the string below to terminal print "Oh, that's why it's False." # Prints the string below to terminal print "How about some more." # Prints the string below followed by 'true' print "Is it greater?", 5 > -2 # Prints the string below followed by 'true' print "Is it greater or equal?", 5 >= -2 # Prints the string below followed by 'false' print "Is it less or equal?", 5 <= -2 # ================================ # ========= STUDY DRILLS ========= # ================================ #1 Above each line, use the # to write a comment to yourself explaining what the line does. ### DONE! #2 Remember in Exercise 0 when you started Python? Start Python this way again and using the math operators, use Python as a calculator. ### DONE :) #3 Find something you need to calculate and write a new .py file that does it. ### See calculator.py file #4 Notice the math seems "wrong"? There are no fractions, only whole numbers. You need to use a "floating point" number, which is a number with a decimal point, as in 10.5, or 0.89, or even 3.0. ### Noted. #5 Rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point. ### Only rewrote line 20 because that's the only statement that would be affected by floating points. ### Rewrote calculator.py as well :).
true
fb4089bcce2764ddd695f378f9911c1374ee911b
jxq0816/psy_learn_python
/diamond.py
241
4.25
4
#请输入一个奇数,打印出一个行数为奇数行的菱形 n=int(input("number=?")) for i in range(1,n+1,2): string_1="*"*i print(string_1.center(n)) for i in range(n-2,0,-2): string_1="*"*i print(string_1.center(n))
false
77ff1d18e2d88269716f2eda2e09270d78d39840
eckoblack/cti110
/M5HW1_TestGrades_EkowYawson.py
1,650
4.25
4
# A program that displays five test scores # 28 June 2017 # CTI-110 M5HW1 - Test Average and Grade # Ekow Yawson # #greeting print('This program will get five test scores, display the letter grade for each,\ \nand the average of all five scores. \n') #get five test scores score1 = float(input('Enter test score 1: ')) score2 = float(input('Enter test score 2: ')) score3 = float(input('Enter test score 3: ')) score4 = float(input('Enter test score 4: ')) score5 = float(input('Enter test score 5: ')) #display a letter grade for each score def determine_grade(score): if score >= 90: print('letter grade: A') elif score >= 80: print('letter grade: B') elif score >= 70: print('letter grade: C') elif score >= 60: print('letter grade: D') else: print('letter grade: E') return score #display average test score def calc_average(score1, score2, score3, score4, score5): average = (score1 + score2 + score3 + score4 + score5) / 5 print('The average is: ', average) return average #define main def main(): print('-----------------------------------------------------------------------') print('Test score 1') determine_grade(score1) print('Test score 2') determine_grade(score2) print('Test score 3') determine_grade(score3) print('Test score 4') determine_grade(score4) print('Test score 5') determine_grade(score5) print('-----------------------------------------------------------------------') calc_average(score1, score2, score3, score4, score5) #run main main()
true
40867a0b45d2f9f37f5d4bcfe0027bd954c82c36
eckoblack/cti110
/M6T1_FileDisplay_EkowYawson.py
451
4.1875
4
# A program that displays a series of integers in a text file # 5 July 2017 # CTI-110 M6T1 - File Display # Ekow Yawson # #open file numbers.txt def main(): print('This program will open a file named "numbers.txt" and display its contents.') print() readFile = open('numbers.txt', 'r') fileContents = readFile.read() #close file readFile.close() #display numbers in file print(fileContents) #call main main()
true
4fdb7741fa84ad336c029825adf0994f174aaa2b
ocean20/Python_Exercises
/functions/globalLocal.py
602
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 23 16:41:56 2019 @author: cawang """ x = 2 def fun1(): x = 1 print("Inside function x =", x) fun1() # Inside function x = 1 print("Outside function x =", x) # Outside function x = 2 def fun2(): print("Inside function x =", x) fun2() # Inside function x = 2 # the function did not declare a local variable x, so it looked for the global one def fun3(): print("Inside function x =", x) x = 3 print("Inside function x after change:", x) fun3() # error: local variable 'x' referenced before assignment
true
28bf46ca0222b8365920e445c6e85d78dd2ae452
Caiovg/Algoritimos-de-Ordenacao-e-Busca
/heap_sort.py
1,049
4.125
4
def heap_sort(data): length = len(data) index = length // 2 parent = 0 child = 0 temp = 0 while True: if index > 0: index -= 1 temp = data[index] else: length -= 1 if length == 0: return temp = data[length] data[length] = data[0] parent = index child = index * 2 + 1 while child < length: if (child + 1) < length and data[child + 1] > data[child]: child += 1 if data[child] > temp: data[parent] = data[child] parent = child child = parent * 2 + 1 else: break data[parent] = temp lista = [] n = int(input("Digite qual vai ser o tamanho da sua lista: ")) for i in range(n): aux = int(input("Digite o " + str(i) + "º valor: ")) lista.append(aux) print("Sua lista não ordenada") print(lista) heap_sort(lista) print("Lista ordenada com heap sort: ") print(lista)
false
30f36be3d0fbe3105c4a29a5e770ceab051505c9
henriquelorenzini/EstruturasDeDecisao
/Exercicio24.py
1,184
4.3125
4
# Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar. O resultado da operação deve ser acompanhado de uma frase que diga se o número é: # par ou ímpar; # positivo ou negativo; # inteiro ou decimal. numero1 = float(input("Digite o número 1: ")) numero2 = float(input("Digite o número 2: ")) operacao = input("Digite a operação que deseja realizar: [+, -, /, *]: ") def check(): if ( resOper // 1 == resOper): print("Inteiro") if resOper % 2 == 0: print("Par") if resOper > 0: print("Positivo") else: print("Negativo") else: print("Impar") else: print("Decimal") if operacao == '+': resOper = numero1 + numero2 print("Resultado: ", resOper) check() elif operacao == '-': resOper = numero1 - numero2 print("Resultado: ", resOper) check() elif operacao == '/': resOper = numero1 / numero2 print("Resultado: ", resOper) check() elif operacao == '*': resOper = numero1 * numero2 print("Resultado: ", resOper) check() else: print("Valor Invalido")
false
a8f0b493d291147afa08f2e699112412f5ccbeb9
henriquelorenzini/EstruturasDeDecisao
/Exercicio15.py
1,180
4.3125
4
# Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. # Dicas: # Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o terceiro; # Triângulo Equilátero: três lados iguais; # Triângulo Isósceles: quaisquer dois lados iguais; # Triângulo Escaleno: três lados diferentes print('Digite 3 valores para os lados e veja que tipo de triângulo é') lado1 = float(input('Digite o valor do primeiro lado: ')) lado2 = float(input('Digite o valor do segundo lado: ')) lado3 = float(input('Digite o valor do terceiro lado: ')) #Forma um triangulo if lado1 > (lado2 + lado3) or lado2 > (lado1 + lado3) or lado3 > (lado1 + lado2): print('Não é possível formar um triângulo') #Equilatero elif lado1 == lado2 == lado3: print('É possível formar um triângulo equilátero') #Isóceles elif lado1 == lado2 or lado1 == lado3 or lado2 == lado3: print('É possível formar um triângulo isóceles') #Escaleno else: print('É possível formar um triângulo escaleno')
false
921035af4cf9beef9eea8661aab63cbd26477227
henriquelorenzini/EstruturasDeDecisao
/Exercicio06.py
586
4.125
4
#Faça um Programa que leia três números e mostre o maior deles. print('Veja qual dos três números é maior') num1 = float(input('Digite o primeiro valor: ')) num2 = float(input('Digite o segundo valor: ')) num3 = float(input('Digite o terceiro valor: ')) if num1 > num2 and num1 > num3: print('O número {:.2f} é maior'.format(num1)) elif num2 > num1 and num2 > num3: print('O número {:.2f} é maior'.format(num2)) elif num3 > num1 and num3 > num1: print('O número {:.2f} é maior'.format(num3)) elif num1 == num2 == num3: print('Os números são iguais')
false
128039caec432553bb36875e92b86d6578175728
AndreasGustafsson88/assignment_1
/assignments/utils/assignment_1.py
1,179
4.46875
4
from functools import lru_cache """ Functions for running the assignments """ def sum_list(numbers: list) -> int: """Sums a list of ints with pythons built in sum() function""" return sum(numbers) def convert_int(n: int) -> str: """Converts an int to a string""" return str(n) def recursive_sum(item: list) -> int: """Calculates the sum of a nested list with recursion""" return item if isinstance(item, int) else sum_list([recursive_sum(i) for i in item]) @lru_cache def fibonacci(n: int) -> int: """ Calculate the nth number of the fibonacci sequence using recursion. We could memoize this ourselves but I prefer to use lru_cache to keep the function clean. """ return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2) def sum_integer(number: int) -> int: """Calculates the sum of integers in a number e.g 123 -> 6""" return sum_list([int(i) for i in convert_int(number)]) def gcd(a: int, b: int) -> int: """ Calculated the GCD recursively according to the Euclidean algorithm gcd(a,b) = gcd(b, r). Where r is the remainder of a divided by b. """ return a if not b else gcd(b, a % b)
true
d48a7f13d05b9e5c3f955873c5185258b8d05a04
KarlVaello/python-programming-challenges
/SpaceArrange_PPC2.py
1,974
4.15625
4
from random import randint import math from Point import Point # def that sort an array of points (bubble algorithm) def bubbleSort(alist): n = len(alist) for i in range(len(alist)-1): swp = False for j in range(len(alist)-1): if (alist[j][2] > alist[j+1][2]): tempPoint = alist[j] alist[j] = alist[j+1] alist[j+1] = tempPoint swp = True if (swp == False): break nPoint = 9 # numer of points points = [] # points array pointRange = 90 #aleatory range # loop to create new random points for x in range (nPoint): newPointObjet = Point(randint(-pointRange,pointRange),randint(-pointRange,pointRange),randint(-pointRange,pointRange)) newPoint = [x+1, newPointObjet] points.append(newPoint) # loop to print element on creation order print("Element on creation order [x,y,z]") for i in range(nPoint): print("(" + str(points[i][0]) + ",["+ str(points[i][1].getXc())+ ", "+ str(points[i][1].getYc())+ ", "+ str(points[i][1].getZc()) + "])") print() # loop to calculate distance to [0, 0, 0] of each point for e in range (nPoint): d = math.sqrt(((points[e][1].getXc()-0)**2)+((points[e][1].getYc()-0)**2)+((points[e][1].getYc()-0)**2)) points[e].append(d) # loop to print element on creation order and distance to [0, 0, 0] print("Element on creation order ( n [x,y,z] / DistanceTo0,0,0]") for i in range(nPoint): print("(" + str(points[i][0]) + ",["+ str(points[i][1].getXc())+ ", "+ str(points[i][1].getYc())+ ", "+ str(points[i][1].getZc()) + "], " + str(points[i][2]) + ")") # bubble sort algorithm bubbleSort(points) print() # print elements in order print("Elements ordered by distance") for i in range(nPoint): print("(" + str(points[i][0]) + ",["+ str(points[i][1].getXc())+ ", "+ str(points[i][1].getYc())+ ", "+ str(points[i][1].getZc()) + "], " + str(points[i][2]) + ")")
false
fd50491b2f67bc3b76ff3b1b5391952b0bed92eb
JonSeijo/project-euler
/problems 1-9/problem_1.py
825
4.34375
4
#Problem 1 """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ MAXNUM = 1000 def findMultiples(number): """Return a list with the multiples of the number, between 1 and MAXNUMBER""" multiples = [] for n in range(1, MAXNUM): #If remainder is zero, is multiple if n % number == 0: multiples.append(n) return multiples def main(): answer = 0 multiples = findMultiples(3) + findMultiples(5) #Remove numbers multiples of both 3 and 5 using set multiples = set(multiples) #Sum all the multiples for n in multiples: answer += n print answer if __name__ == "__main__": main()
true
ec2a73d8147e75ab14f1453c16295bb50e52a58e
JonSeijo/project-euler
/problems 50-59/problem_57.py
1,689
4.125
4
# -*- coding: utf-8 -*- # Square root convergents # Problem 57 """ It is possible to show that the square root of two can be expressed as an infinite continued fraction. √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? """ def crearSucesiones(): """ Jonathan Seijo Las fracciones que quiero analizar son: 1+(1/2), 1+(2/5), 1+(5/12), 1+(12/29), 1+(29/70),.. considero an/bn = (1/2), (2/5), (5/12), (12/29), (29/70), .. puedo definir esta sucesion por recurrencia como: a1 = 1 b1 = 2 an = b(n-1) bn = 2*b(n-1) + a(n-1) --> 'an' contiene al numerador en la posicion n --> 'bn' contiene al denominador en la posicion n """ an = [1] bn = [2] for n in range(1, 1001): an.append(bn[n-1]) bn.append(2*bn[n-1] + an[n-1]) return an, bn def main(): # Creo las suceciones de numeradores y denominadores an, bn = crearSucesiones() answer = 0 for n in range(0, 1000): # 1 + (an/bn) = (bn + an)/bn if len(str(bn[n] + an[n])) > len(str(bn[n])): answer += 1 print "answer: " + str(answer) if __name__ == "__main__": main()
true
a09e6de32320dca2795f35f7218ec5bd4d4f85bb
brennobrenno/udemy-python-masterclass
/Section 11/spam.py
1,525
4.15625
4
def spam1(): def spam2(): def spam3(): z = " even" z += y print("In spam3, locals are {}".format(locals())) return z y = " more " + x # y must exist before spam3() is called y += spam3() # do not combine these assignments print("In spam2, locals are {}".format(locals())) return y # x = "spam" + spam2() # breaks because spam2() tries to use the value of x when it is called, but x does not x = "spam" # x must exist before spam2() is called x += spam2() # do not combine these assignments print("In spam1, locals are {}".format(locals())) # yet have a value return x print(spam1()) # wherever possible, try to write functions so that they only use local variables and parameters # only access global and nonlocal variables when it is absolutely necessary # no matter how trivial the change you make, test the program thoroughly to make sure nothing has been broken # often simple changes will break code # if you write unexpected code, make sure to write a comment so the next person who looks at the code understands it # and doesn't mess it up # at the module level, the local scope is the same as the global scope print(locals()) print(globals()) # free variables are returned by locals() when it is called in function blocks, but not in class blocks # order in which python searches for names: local -> enclosing (nonlocal or free) -> global -> built_ins (python stuff)
true
1f6689ff4d8990151ca329843ec12486157182b3
brennobrenno/udemy-python-masterclass
/Section 7 & 8/43.py
863
4.21875
4
# list_1 = [] # list_2 = list() # # print("List 1: {}".format(list_1)) # print("List 2: {}".format(list_2)) # # if list_1 == list_2: # print("The lists are equal") # # print(list("The lists are equal")) # even = [2, 4, 6, 8] # another_even = even # # another_even = list(even) # New list # another_even2 = sorted(even, reverse=True) # Also new list # # print(another_even is even) # Same variable/thing # print(another_even == even) # Same content # # print("another_even 2") # print(another_even2 is even) # Same variable/thing # print(another_even2 == even) # Same content # # another_even.sort(reverse=True) # print(even) even = [2, 4, 6, 8] odd = [1, 3, 5, 7, 9] numbers = [even, odd] # A list containing two lists print(numbers) for number_set in numbers: print(number_set) for value in number_set: print(value)
true
7a4c6e46d471dee68f06f28956a964fd56559912
wesbasinger/LPTHW
/ex22/interactive.py
1,213
4.15625
4
print "Let's just take a little quiz." print "On this section, you were supposed to just review." points = 0 def print_score(): print "So far you have %d points." % points print_score() print ''' Here's your first question. Which of the following objects have we talked about so far? a Strings b Integers b Functions d All of the above ''' answer = raw_input(">>> ") if answer.lower() == "d": print "Good job!" points += 1 else: print "Nope, sorry." print_score() print ''' Here's another question. T/F Strings can be enclosed by double OR single quotes. T F ''' answer = raw_input('>>> ') if answer.upper() == "T": print "Good job!" points += 1 else: print "Nope, sorry." print_score() print ''' Here's another question. Will this command read a file? file = open('somefile.txt') yes no ''' answer = raw_input('>>> ') if answer.lower() == "no": print "Good job!" points += 1 else: print "Nope, sorry." print_score() print ''' One last question. What keyword makes a function 'give back' a value and is frequently used at the end of a function? ''' answer = raw_input('>>> ') if answer.lower() == "return": print "Good job!" points += 1 else: print "Nope, sorry." print_score()
true
edaff19fc7b3ea2a8ab87e1ab10ad6c029009841
wesbasinger/LPTHW
/ex06/practice.py
739
4.34375
4
# I'll focus mostly on string concatenation. # Honestly, I've never used the varied types of # string formatting, although I'm sure they're useful. # Make the console print the first line of Row, Row, Row Your Boat # Do not make any new strings, only use concatenation first_part = second_part = # should print 'Row, row, row your boat Gently down the stream." # ***please note*** the space is added for you print first_part + " " + second_part main_char = "Mary" space = " " verb = "had" indef_art = "a" adjective = "little" direct_object = "lamb" # should print 'Mary had a little lamb' print YOUR CODE GOES HERE one = "one" one_digit = "1" # should print 'Takes 1 to know one." print "Takes " + XXX + " to know " + XXX + "."
true
cf4a99e1a7c7562f04bb9d68cc91673f7d108309
wesbasinger/LPTHW
/ex21/interactive.py
1,924
4.28125
4
from sys import exit def multiply_by_two(number): return number * 2 def subtract_by_10(number): return number - 10 def compare_a_greater_than_b(first_num, second_num): return first_num > second_num print "So far, you've done only printing with function." print "Actually, most of the time you will want your" print "function to return something." print "Instead of printing the value to the screen," print "you save the value to variable or pass it in" print "somewhere else." print "These functions have been defined already for you." print ''' def multiply_by_two(number): return number * 2 def subtract_by_10(number): return number - 10 def compare_a_greater_than_b(first_num, second_num): return first_num > second_num ''' print "Let's do some math with those." print "Give this command: multiply_by_two(40)" prompt = raw_input('>>> ') if prompt == "multiply_by_two(40)": multiply_by_two(40) print "See, nothing was printed." else: print "Not quite, try again." exit(0) print "This time let's print the value." print "Give this command: print multiply_by_two(40)" prompt = raw_input('>>> ') if prompt == "print multiply_by_two(40)": print multiply_by_two(40) print "See, that worked." else: print "Not quite, try again." exit(0) print "Let's do some more." print "Give this command: compare_a_greater_than_b(5,5)" prompt = raw_input('>>> ') if prompt == "compare_a_greater_than_b(5,5)": compare_a_greater_than_b(5,5) print "See, nothing was printed." else: print "Not quite, try again." exit(0) print "This time let's save the value to a variable." print "Give this command: result = compare_a_greater_than_b(5,5)" prompt = raw_input('>>> ') if prompt == "result = compare_a_greater_than_b(5,5)": result = compare_a_greater_than_b(5,5) print "Your value is stored in result." print "Now I will print 'result' for you." print result else: print "Not quite, try again." exit(0)
true
50f7a379886e1b687eafe0ae37ff11c2461ec95b
wesbasinger/LPTHW
/ex40/interactive.py
2,919
4.40625
4
from sys import exit print "This is point where things take a turn." print "You can write some really great scripts and" print "do awesome stuff, you've learned just about" print "every major data type and most common pieces" print "of syntax." print "But, if you want to be a real programmer," print "and write applications and programs beyond" print "simple utility scripts, you'll need to dive" print "into object-oriented programming." print "Press Enter when you're ready to read more." raw_input() print "The first step of OOP is using modules, which" print "really are just other files that have your" print "code in them. This is a great way to keep" print "things organized." print "I'll try as best I can to show you this in an" print "interactive session." print """ Imagine you have a file in the same directory as where you are running this imaginary prompt. The file is called stairway_to_heaven.py This is a variable inside that file. first_line = 'Theres a lady who's sure' There is also a function. def sing_chorus(): print 'And as we wind on down the road' Import the module by giving this command. import stairway_to_heaven """ prompt = raw_input('>>> ') if prompt == "import stairway_to_heaven": print "Module successfully imported." else: print "Nope, try again." exit(0) print "Now let's call a property from the module." print "Give this command: print stairway_to_heaven.first_line" prompt = raw_input('>>> ') if prompt == "print stairway_to_heaven.first_line": print "There's a lady who's sure" else: print "Nope, not quite." exit(0) print "Now let's access a method in the same way." print "Give this command: stairway_to_heaven.sing_chorus()" prompt = raw_input('>>> ') if prompt == "stairway_to_heaven.sing_chorus()": print "And as we wind on down the road." else: print "Not quite, try again." exit(0) print "But object oriented programming goes beyond" print "just modules. You can also do what are called classes." print "Classes create objects." class Candy(object): def __init__(self, name): self.name = name def eat(self): print "All gone. Yummy." print """ This class has been defined for you. class Candy(object): def __init__(self, name): self.name = name def eat(self): print "All gone. Yummy." Let's create an instance of candy. Give this command: snickers = Candy('snickers')""" prompt = raw_input(">>> ") if prompt == "snickers = Candy('snickers')": print "Good job. Object instantiated." snickers = Candy('snickers') else: print "Not quite, try again." exit(0) print "Let's call a method on snickers." print "Give this command: snickers.eat()" prompt = raw_input('>>> ') if prompt == "snickers.eat()": snickers.eat() else: print "Not quite, try again." exit(0) print "That should be enough to get your feet wet." print "If you're like me, it might take a while for" print "this to sink in. But, maybe you're smarter."
true
64bd98e9099267c2b5239a12c68a1c0108f4d92a
AmenehForouz/leetcode-1
/python/problem-0832.py
1,144
4.34375
4
""" Problem 832 - Flipping an Image Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. """ from typing import List class Solution: def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: for i in A: i.reverse() for j in range(len(i)): if i[j] == 0: i[j] = 1 elif i[j] == 1: i[j] = 0 return A if __name__ == "__main__": img1 = [[1, 1, 0], [1, 0, 1], [0, 0, 0]] img2 = [[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]] # Should return [[1, 0, 0], [0, 1, 0], [1, 1, 1]] print(Solution().flipAndInvertImage(img1)) # Should return [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]] print(Solution().flipAndInvertImage(img2))
true
9f489fa5b55db295368c9ea6ff621fe59f2e37e9
AmenehForouz/leetcode-1
/python/problem-0088.py
625
4.15625
4
""" Problem 88 - Merge Sorted Array Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. """ from typing import List class Solution: def merge( self, nums1: List[int], m: int, nums2: List[int], n: int ) -> None: """ Do not return anything, modify nums1 in-place instead. """ for i in range(n): nums1[i + m] = nums2[i] nums1.sort() if __name__ == "__main__": nums1 = [1, 2, 3, 0, 0, 0] nums2 = [2, 5, 6] # Should return [1, 2, 2, 3, 5, 6] Solution().merge(nums1, 3, nums2, 3) print(nums1)
true
2315e0c5f7b08cb87aab56f835a7122e096e5a80
priyankabhalode/Test
/Hungry.py
316
4.15625
4
hungry = input("Are u hungry?") if hungry == "yes": print("eat samosa") print("eat pizza") print("eat burger") print("eat fries") else: #print("Do your home work") thirsty = input("Are u thirsty?") if thirsty == "yes": print("drink water") print("drink soda or coldrink")
false
1d79a965da3406b42c492b8a9aa2bfd6ae4c1bba
nathanielam0ah/homework
/exercise009.py
230
4.21875
4
#!/usr/bin/env python def maxList(Li): currentMax = Li[0] for index in Li: if index > currentMax: currentMax = index return currentMax myList = ['3', '4', '6', '3', '-100'] print(maxList(myList))
true
030622a70d0b52144a0b3e604fd7105e97511e0a
dishit2141/Internship-Work
/day3(basic programme)/smallestno.py
246
4.15625
4
no1=int(input("Enter Number 1:")) no2=int(input("Enter Number 2:")) no3=int(input("Enter Number 3:")) if(no1<no2 and no1<no3): print(no1,"is Smallest") elif(no2<no1 and no2<no3): print(no2,"is Smallest") else: print(no3,"is Smallest")
false
da6106e6aa5268cc241d03472d3ff572f0a63e58
ucsd-cse-spis-2020/spis20-lab03-Sidharth-Theodore
/lab3Letters_pair.py
596
4.5625
5
#Sidharth and Theodore #1.the "anonymous turtle" is the default turtle used if none are created in Code, or the first created if multiple are created #2."turtle" refers to the turtle library while "Turtle()" refers to the turtle class #3.myTurtle.sety(100) import turtle def drawT(theTurtle, size): '''Takes a turtle, uses it to draw letter T''' theTurtle.pd() theTurtle.forward(10*size) theTurtle.right(180) theTurtle.forward(5*size) theTurtle.left(90) theTurtle.forward(10*size) bobRoss = turtle.Turtle() myScreen = turtle.Screen() myScreen.screensize(400,400) drawT(bobRoss, 20)
true
0c399de5188adb0418cef31a5896a2376afdf4bb
linzifan/python_courses
/misc-Stack.py
1,487
4.40625
4
""" Stack class """ class Stack: """ A simple implementation of a FILO stack. """ def __init__(self): """ Initialize the stack. """ self._items = [] def __len__(self): """ Return number of items in the stack. """ return len(self._items) def __str__(self): """ Returns a string representation of the stack. """ return str(self._items) def push(self, item): """ Push item onto the stack. """ self._items.append(item) def pop(self): """ Pop an item off of the stack """ return self._items.pop() def clear(self): """ Remove all items from the stack. """ self.items = [] ############################ # test code for the stack my_stack = Stack() my_stack.push(72) my_stack.push(59) my_stack.push(33) my_stack.pop() my_stack.push(77) my_stack.push(13) my_stack.push(22) my_stack.push(45) my_stack.pop() my_stack.pop() my_stack.push(22) my_stack.push(72) my_stack.pop() my_stack.push(90) my_stack.push(67) while len(my_stack) > 4: my_stack.pop() my_stack.push(32) my_stack.push(14) my_stack.pop() my_stack.push(65) my_stack.push(87) my_stack.pop() my_stack.pop() my_stack.push(34) my_stack.push(38) my_stack.push(29) my_stack.push(87) my_stack.pop() my_stack.pop() my_stack.pop() my_stack.pop() my_stack.pop() my_stack.pop() print my_stack.pop()
true
f74f78bb3fc27e9abd3158ff8cdbe7a93a7dc8b6
Shruti0899/Stack_to_list
/stcklst.py
1,837
4.25
4
print("list to stack\n") class StackL: def __init__(self): self.menu() def add(self,my_list,l): val=input("value:") if len(my_list)==l: print("\nStack is full.\nCannot add further.\nYou may choose to delete items to proceed.") else: my_list.append(val) print("\ncurrent list is:",my_list) print("\nDo you want to add more elements?Y/N") c=input() if c=="y": self.add(self.my_list,self.l) elif c=="n": self.dele(self.my_list,self.l) def dele(self,my_list,l): if len(my_list)==0: print("\nStack is empty.\nCannot delete further") else: print("list is:",my_list) print("\n Sure you want to delete the last ele added?y/n\n") k=input() if k=='y': my_list.pop() print("\ncurrent list is:",my_list) print("\ndo you further want to delete?Y/N") c=input() if c=="y": self.dele(my_list,l) elif c=="n": sel.add(self.my_list,self.l) else: print("current list:",my_list) def menu(self): self.my_list=[] print("choose an operation:\n") print("\n1.Add\n2.Delete\n3.Exit") op=input() if op !="3": print("\nEnter the length of the list?\n") self.l=int(input()) if op=='1': self.add(self.my_list,self.l) self.menu() elif op=='2': self.dele(self.my_list,self.l) self.menu() else: exit() myob=StackL()
false
2384c7c82af5eccdb070c7522a11895f2c3f4aa6
ldocao/utelly-s2ds15
/clustering/utils.py
674
4.25
4
###PURPOSE : some general purposes function import pdb def becomes_list(a): """Return the input as a list if it is not yet""" if isinstance(a,list): return a else: return [a] def add_to_list(list1, new_element): """Concatenate new_element to a list Parameters: ---------- list1: list Must be a list new_element : any new element to be added at the end of list1 Output: ------ result: list 1D list """ return list1+becomes_list(new_element) def is_type(a,type): """Test if each element of list is of a given type""" return [isinstance(i,type) for i in a]
true
a3d90fc11ec40efd2f075b1f5e1ee1f03f66d465
qiao-zhi/pythonCraw
/HelloPython/function1.py
1,638
4.25
4
# python函数练习 # 1.python自带的一些常见函数的练习 print(abs(-95)) print(hash(-95)) print("sssssssssssssssss"+str(95)) # 2.自定义函数 def my_abs(a): if a >= 0: return a else: return -a # 3.定义不带参数与返回值的函数(无返回值的函数类似于return None,可以简写为return) def print_star(): print("***********") print_star() x=print_star() #实际返回的为None print(x) # 4.多个返回值的函数定义以及使用方法(实际返回的是一个tuple,用多个值获取tuple的时候实际是将每个tuple的元素赋给对应的值) def twoReturnValue(): return 'a','b' x, y = twoReturnValue(); print(x, y) value=twoReturnValue() print(value) # 5.递归函数的用法(自己调用自己的函数) # 5.1.计算裴波那契数列的第N个数字1 1 2 3 5 8 13 ... def count(index): if index == 1: return 1 if index == 2: return 1 return count(index-1)+count(index-2) print(count(7)) # 5.2计算N的阶乘 def jiecheng(n): if n==1: return 1 else: return n*jiecheng(n-1) print(jiecheng(3)) # 6.默认参数的用法 # 6.1默认参数求n的x次方,如果不传入n的话默认为2 def power(x, n=2): s=1 while n > 0: s=s*x n=n-1 return s print(power(5,3)) print(power(5)) # 可变参数的用法(实际传入的是一个集合) def fun3(*arg): print(len(arg)) print(arg) for ele in arg: print(ele) fun3(1,5,8,5) # 定义一个空函数(pass关键字是空语句,是为了保持程序结构的完整性) def fun4(): pass fun4()
false