blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
827a75178963d0b672460e8b7f01a566fd1a0177
thiagorangeldasilva/Exercicios-de-Python
/pythonBrasil/02.Estrutura de Decisão/15. triangulo.py
1,090
4.28125
4
#coding: utf-8 """ 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; """ a = [] x = 0 while x < 3: i = float(input("Informe o " + str(x+1) + "º valor do ângulo: ")) a.append(i) if x == 1: s1 = a[x] + a[x-1] elif x == 2: s2 = a[x] + a[x-1] s3 = a[x] + a[x-2] if s1 <= a[2] or s2 <= a[0] or s3 <= a[1]: x = -1 print() print("Não é um triângulo, digite os lados novamente.") print() x += 1 print() if a[0] != a[1] and a[0] != a[2] and a[1] != a[2]: print("O triângulo é Escaleno.") elif a[0] == a[1] and a[0] == a[2] and a[1] == a[2]: print("O triângulo é Equilátero.") else: print("O triângulo é Isósceles.") input()
false
359ae83a4c2f4184a35587ab2dca1c2840629e5d
Gokulancv10/CodeBytes
/2-Week_Array/Spot The Difference.py
1,723
4.125
4
""" This question is asked by Google. You are given two strings, s and t which only consist of lowercase letters. t is generated by shuffling the letters in s as well as potentially adding an additional random character. Return the letter that was randomly added to t if it exists, otherwise, return ''. Note: You may assume that at most one additional character can be added to t. Ex: Given the following strings... s = "foobar", t = "barfoot", return 't' s = "ide", t = "idea", return 'a' s = "coding", t "ingcod", return '' """ from collections import Counter print('------Using Counter---------') def solution(s, t): a = Counter(s) b = Counter(t) res = b - a if not res: return 'None' for i in res: return i print(solution('foobar', 'barfoot')) print(solution('ide', 'idea')) print(solution('coding', 'ingcod')) print('------Using Set And For---------') def solution(s, t): res = set(t) for i in res: if i not in s: return i return 'None' print(solution('foobar', 'barfoot')) print(solution('ide', 'idea')) print(solution('coding', 'ingcod')) print('------Using Set---------') def solution(s, t): a = set(s) b = set(t) res = b - a if not res: return 'None' for i in res: return i print(solution('foobar', 'barfoot')) print(solution('ide', 'idea')) print(solution('coding', 'ingcod')) print('---------Using XOR------------') def solution(s, t): ans = 0 for c in s: ans ^= ord(c) for c in t: ans ^= ord(c) return chr(ans) if ans else 'None' print(solution('foobar', 'barfoot')) print(solution('ide', 'idea')) print(solution('coding', 'ingcod'))
true
0a601544eea489d94afbcedd7b5bc054c43459bb
greencodespace/code_data
/py_scipy/엔지니어를위한_파이썬/chapter05/class1.py
789
4.40625
4
# 클래스 정의 class MyClass(object): # (1) 상속하는 클래스 없음 """ (2) 클래스의 닥스트링 """ # (3) 변수 x, y의 정의 x = 0 y = 0 def my_print(self): self.x += 1 # x를 인스턴스마다 별도로 존재하는 변수로 다룸 MyClass.y += 1 # y를 클래스마다 존재하는 변수로 다룸 print('(x, y) = ({}, {})'.format(self.x, self.y)) # 클래스의 인스턴스를 생성 f = MyClass # (5) ()가 없으면 클래스에 별명을 붙인다는 의미 a = MyClass() # (6) MyClass 클래스의 인스턴스를 만들고 여기에 a라는 이름을 붙임 b = f() # (7) f()는 MyClass()와 같은 의미((5)에서 별명을 붙였으므로) # (8) 메소드 실행 a.my_print() b.my_print() b.my_print()
false
612234d53d3d28701fdb0d4992a6b9be51fdc0c3
Raymond-P/Github-Dojo
/Python_200_Problems/arrays/array_rotate.py
405
4.15625
4
# Rotate an array of n elements to the right by k steps. # For example, with n = 7 and k = 3, # the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. # Note: # Try to come up as many solutions as you can, # there are at least 3 different ways to solve this problem. def rotate1(array, steps): if len(array) > steps > 0: array = array[-1*steps:]+array[:len(array)-steps] return array
true
62d903677f5a006144cf2f01530863cfca8c3bde
PAVISH2002/my-captain
/fibonocii.py
281
4.1875
4
#code for fibonacci numbers n1=0 n2=1 count = 0 nterms=int(input("Enter how many terms :")) if nterms<=0: print("Enter a positive interger :") else: while(count<nterms): print(n1) nth=n1+n2 n1=n2 n2=nth count+=1
false
1a646975d309c839d68874299c25d90b118e6108
Icarus-150/KMCSSI19
/Welearn/M3-PYTHON/LABS/lab1-pluralizeit/pluralize.py
618
4.15625
4
def pluralize(word,num): if num > 1: if word [-3:]== "ife" : return( word[:-3] + "ives") elif word[-2:] == "sh" or word[-2:] == "ch" : return( word + "es") elif word[-2:] == "us": return(word[:-2] + "i") elif word[-2:] == "ay" or word[-2:] == "oy" or word[-2:] == "ey" or word[-2:] == "uy": return(word + "s") elif word[-1:] == "y": return(word[:-1] + "ies") else: return(word +"s") else: return word print(pluralize(raw_input("enter word: "),int(raw_input("enter number: "))))
false
3991269b55ef51fd1e75c2e56d21d36c6960080a
yuvan11/python_basic_practice
/python_class/operators.py
1,288
4.21875
4
x = 15 y = 4 # Arithmetic # Addition print('5 + 5 =',x+y) # # subtraction print('6- 3 =',x-y) # # Multiplication print('7* 7 =',x*y) # Division print('50/ 5 =',x/y) # # floor division // quotient print('x // y =',x//y) # Exponent print('x ** y =',x**y) # # #Modulus // remainder print('x % y =',x%y) # # # Comparison # # Greater than print('3 > 2 is',x>y) # # Lesser than print('3 < 2 is',x<y) # # # equal to print('x 2== 2 is',x==y) # # # not equal to print('2 != 4 is',x!=y) # # # greater than equal to print('x9>= 10 is',x>=y) # # # lesser than equal to print('4 <= 6 is',x<=y) # # # Logical # x=0 # y=1 # # and # print('x and y is',x and y) # # # or # print('x or y is',x or y) # # print('not y is',not y) # # # # Identity operators # # is print('x is y',x is y) # # #is not print('x is not y', x is not y) # # # # Bitwise operators # # AND print('x & y', x & y) # # OR print('x | y',x|y) # # XOR print('x^y', x^y) # # NOT print('~x', ~x) # # Zero fill left shift x=2 y=1 print('x<<y', 4<<2) # # Signed right shift print('x>>y',4>>2) # # # Membership operators # # in x=["python", "java", "dotnet" ] # print('x in list',"java" in x ) # # # not in print('x not in list',"python" not in x) #
false
7da8c3be50b482c5e40d2e94b7dda7650ea0bfa3
Mariakhan58/simple-calculator
/calculator.py
1,343
4.25
4
# Program to make a simple calculator # This function adds two numbers def Calculate(): def add(a, b): return a+b # This function subtracts two numbers def subt(a, b): return a-b # This function multiplies two numbers def mult(a, b): return a*b #This function divides two numbers def div(a, b): return a/b print('Operations this calculator can perform:') print('a. Addition') print('b. Subtraction') print('c. Multiplication') print('d. Division') while True: operation = input('\nEnter the option for the operation you want to perform (a/b/c/d): ') if operation in ('a','b','c','d'): number1 = float(input('Enter first number: ')) number2 = float(input('Enter second number: ')) if operation == 'a': print(number1, ' + ', number2, ' = ', add(number1, number2)) if operation == 'b': print(number1, ' - ', number2, ' = ', subt(number1, number2)) if operation == 'c': print(number1, ' * ', number2, ' = ', mult(number1, number2)) if operation == 'd': print(number1, ' / ', number2, ' = ', div(number1, number2)) break else: print("Invalid choice") Calculate()
true
f304dca7c8c76a0be1fab0a06e1087a5d31089e1
AnaLeonor/labs
/lab2.py
1,140
4.15625
4
#LAB2 #Exercicio1 shoppingList = ['potatoes', 'carrots', 'cod', 'sprouts'] #Exercicio2 scnElem = shoppingList[1] print(scnElem) lastElem = shoppingList[-1] print(lastElem) #Exercicio3 for i in shoppingList: print(i) #Exercicio4 studentList = [] #Exercicio5 shoppingList.append('orange') shoppingList.append('lime') print(shoppingList) #Exercicio6 shoppingList.remove('carrots') shoppingList = shoppingList[1:-1] print(shoppingList) #Exercicio7 del studentList #Exercicio8 squares = [x**2 for x in range (1,15)] print(squares) #Exercicio9 print(squares [:3]) #Exercicio10 shopping = shoppingList copy = shoppingList[:] print(shopping) #Exercicio11 shopping = shoppingList shopping.append('orange') print(shopping) #Exercicio12 shoppingList.clear #Exercicio13 newPurchases= ("bananas", "beans", "rice") print(newPurchases[1]) #Ao colocarmos o newPurchases[0] = "apple" iremos obter um erro pois #nao eh possivel atribuir este item ao tuplo #Exercicio14 fruit = {1: 'orange', 2: 'apple', 3: 'pear', 4: 'grape', 5: 'peach' } print(fruit) #Exercicio15 weekList={1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []} print(weekList)
false
416bce7ea5543c5d05b52d9cfb0e26d1d3cbd510
Reece323/coding_solutions
/coding_solutions/alphabeticShift.py
467
4.15625
4
""" Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). """ def alphabeticShift(inputString): #97(a) - 122(z) to_list = list(inputString) for i in range(len(to_list)): if to_list[i] == 'z': to_list[i] = 'a' else: to_list[i] = chr(ord(to_list[i]) + 1) return ''.join(to_list)
true
25916d96dec4108171537a9ac039b2110ee31bc4
Reece323/coding_solutions
/coding_solutions/first_not_repeating_character.py
843
4.21875
4
""" Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'. Example For s = "abacabad", the output should be first_not_repeating_character(s) = 'c'. There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first. For s = "abacabaabacaba", the output should be first_not_repeating_character(s) = '_'. There are no characters in this string that do not repeat. """ def first_not_repeating_character(s): table = {} for i in range(len(s)): if s[i] not in table: table[s[i]] = 1 else: table[s[i]] += 1 for key,value in table.items(): if value == 1: return key return '_'
true
d869fc6cf5f3cdf029c4d8ea4439fb6a62c4cd28
Digikids/Fundamentals-of-Python
/if statements.py
477
4.21875
4
number_1 = int(input("Input a number: ")) number_2 = int(input("Input a second number: ")) operation = input("What do you want to do with the two numbers: ") output = "" if operation == "+": output = number_1 + number_2 elif operation == "-": output = number_1 - number_2 elif operation == "*": output = number_1 * number_2 elif operation == "/": output = number_1 / number_2 else: print("Ivalid selection!!!!!!") print("The answer is: " + str(output))
true
e5bd64932169fa7beed4c6f919d07d97d2b02dab
shaokangtan/python_sandbox
/reverse_linked_list.py
662
4.21875
4
class Node: def __init__(self, value): self.value = value self.nextnode = None def reverse_linked_list(node): current = node prev = None next = None while current: next = current.nextnode current.nextnode = prev prev = current current = next a = Node(1) b = Node(2) c = Node (3) d = Node (4) a.nextnode = b b.nextnode = c c.nextnode = d def print_linked_list(node): while (node): print ("{} ".format(node.value)) node = node.nextnode print_linked_list(a) print ("reverse linked list") reverse_linked_list(a) print_linked_list(d)
true
d49d6a35fe93577fecb7810aa0e151160d02ae06
shaokangtan/python_sandbox
/hello_world.py
994
4.125
4
print("hello world %c" % '!') class Dog(): """Represent a dog.""" def __init__(self, name): """Initialize dog object.""" self.name = name def sit(self): """Simulate sitting.""" print(self.name + " is sitting.") class SARDog(Dog): """Represent a search dog.""" def __init__(self, name): """Initialize the sardog.""" super().__init__(name) def search(self): """Simulate searching.""" print(self.name + " is searching.") a = 1 def test (): a = 1 v = memoryview(a) print (v[0]) print (locals()['a']) print (locals()) my_dog = Dog('Peso') print(my_dog.name + " is a great dog!") my_dog.sit() my_dog = SARDog('Willie') print(my_dog.name + " is a search dog.") my_dog.sit() my_dog.search() list = (1,2,3) print ("list[-3]=%d" % list[-3]) str = "123 " print ("str=%s !" % str.strip(" ")) hello="hello world" print ("hello=%s" % hello[3:5])
false
e14bb95ae0b24e82ed8f92fcfa17bc7d6e339cf8
JianFengY/codewars
/codes/bit_counting.py
627
4.15625
4
# -*- coding: utf-8 -*- ''' Created on 2018年2月2日 @author: Jeff Yang ''' ''' Write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number. Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case ''' def count_bits(n): """count number of bits that are equal to 1""" return bin(n).count('1') # return '{:b}'.format(n).count('1') print(count_bits(0)) print(count_bits(4)) print(count_bits(7)) print(count_bits(9)) print(count_bits(10))
true
48780254b9319513472ab29b52c1074f34b439db
JianFengY/codewars
/codes/format_a_string_of_names.py
1,372
4.1875
4
# -*- coding: utf-8 -*- ''' Created on 2018年2月2日 @author: Jeff Yang ''' ''' Given: an array containing hashes of names Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. Example: namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ]) #'Bart, Lisa & Maggie' namelist([ {'name': 'Bart'}, {'name': 'Lisa'} ]) # 'Bart & Lisa' namelist([ {'name': 'Bart'} ]) # 'Bart' namelist([]) # '' ''' def namelist(names): """format names with commas and ampersand""" return '' if len(names) == 0 else ', '.join([x['name'] for x in names[:-1]]) + \ ' & ' + names[-1]['name'] if len(names) > 1 else names[0]['name'] # return ", ".join([name["name"] for name in names])[::-1].replace(",", "& ", 1)[::-1] # if len(names) > 1: # return '{} & {}'.format(', '.join(name['name'] for name in names[:-1]), names[-1]['name']) # elif names: # return names[0]['name'] # else: # return '' print(namelist([{'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'}, {'name': 'Homer'}, {'name': 'Marge'}])) print(namelist([{'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'}])) print(namelist([{'name': 'Bart'}, {'name': 'Lisa'}])) print(namelist([{'name': 'Bart'}])) print(namelist([]))
false
65260f9763e0ebeb995c3a7c5260c2b8420206c7
JianFengY/codewars
/codes/binary_addition.py
486
4.21875
4
# -*- coding: utf-8 -*- ''' Created on 2018年2月1日 @author: Jeff Yang ''' ''' Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. ''' def add_binary(a, b): """add two numbers and return sum in binary""" return bin(a + b)[2:] # return '{0:b}'.format(a + b) print(add_binary(2, 2)) print(add_binary(51, 12))
true
98638499b765de5668015c9425b882f5721ede52
afrazn/Projects
/MemoizationDynamicProgramming.py
1,144
4.1875
4
'''This program uses memoization dynamic programming to find the optimal items to loot based on weight capacity and item value''' from util import Loot def knapsack(loot, weight_limit): grid = [[0 for col in range(weight_limit + 1)] for row in range(len(loot) + 1)] for row, item in enumerate(loot): row = row + 1 for col in range(weight_limit + 1): weight_capacity = col if item.weight <= weight_capacity: item_value = item.value item_weight = item.weight previous_best_less_item_weight = grid[row - 1][weight_capacity - item_weight] capacity_value_with_item = item_value + previous_best_less_item_weight capacity_value_without_item = grid[row - 1][col] grid[row][col] = max(capacity_value_with_item, capacity_value_without_item) else: grid[row][col] = grid[row - 1][col] return grid[-1][-1] available_loot = [Loot("Clock", 3, 8), Loot("Vase", 4, 12), Loot("Diamond", 1, 7)] weight_capacity = 4 best_combo = knapsack(available_loot, weight_capacity) print("The ideal loot given capacity {0} is\n{1}".format(weight_capacity, best_combo))
true
8437ae1338934cdf4937ab1e97967a097731e77c
srirachanaachyuthuni/object_detection
/evaluation.py
2,508
4.1875
4
"This program gives the Evaluation Metrics - Accuracy, Precision and Recall" def accuracy(tp, tn, total): """ Method to calculate accuracy @param tp: True Positive @param tn: True Negative @param total: Total @return: Calculated accuracy in float """ return (tp + tn ) / total def precision(tp, fp): """ Method to calculate precision @param tp: True Positive @param fp: False Positive @return: Calculated precision in float """ return tp / (tp + fp) def recall(tp, fn): """ Method to calculate recall @param tp: True Positive @param fn: False Negative @return: Calculated recall in float """ return tp / (tp + fn) def evaluation_before_augmentation(tp, tn, fp, fn): """ Method to run evaluation with before augmentation values @param tp: True Positive @param tn: True Negative @param fp: False Positive @param fn: False Negative @return: None """ total = tp + tn + fp + fn print("Evaluation before augmentation") print("Accuracy : " + str(accuracy(tp, tn, total) * 100) + " %" ) print("Precision : " + str(precision(tp, fp) * 100) + " %") print("Recall : " + str(recall(tp, fn) * 100) + " %") def evaluation_after_augmentation(tp, tn, fp, fn): """ Method to run evaluation with after augmentation values @param tp: True Positive @param tn: True Negative @param fp: False Positive @param fn: False Negative @return: None """ total = tp + tn + fp + fn print("Evaluation after augmentation") print("Accuracy : " + str(accuracy(tp, tn, total) * 100) + " %" ) print("Precision : " + str(precision(tp, fp) * 100) + " %") print("Recall : " + str(recall(tp, fn) * 100) + " %") def main(): """ Main driver function of the program @rtype: object """ # The following are values calculated manually after running test on 25 images from different videos true_positive = 29 true_negative = 5 false_positive = 5 false_negative = 6 evaluation_before_augmentation(true_positive, true_negative, false_positive, false_negative) # The following are values calculated manually after running test on 25 images from different videos with # augmentation true_positive = 34 true_negative = 3 false_positive = 5 false_negative = 3 evaluation_after_augmentation(true_positive, true_negative, false_positive, false_negative) if __name__ == '__main__': main()
true
3f15cde13c1183324a580bac67c3f2ffcee42c73
simplifies/Coding-Interview-Questions
/hackerrank/noDocumentation/countingValleys.py
1,393
4.125
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): # so instantly i'm thinking switch the DD UU to 1 and -1 # so [DDUUUU] would become [-1, -1, 1, 1, 1, 1] # So a valley is determined when he goes below sea level # this solves that, because we always keep track of his elevation this way. if elevation < 0, hes in a valley # we then add + 1 to a counter until he goes above sea level again # Sooo, we go one by one through this list. # each new iter-item we check to see if evelation < 0 # if it is, we add +1 to a counter. # We also set inValley = True # if elevation < 0 and not inValley, we execute valley # else we don't, meaning we're still in the valley currentElevation = 0 inValley = False valleys = 0 for step in s: if step == "U": currentElevation += 1 else: currentElevation -= 1 if currentElevation < 0 and not inValley: inValley = True valleys += 1 if currentElevation >= 0 and inValley: inValley = False return valleys if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() result = countingValleys(n, s) fptr.write(str(result) + '\n') fptr.close()
true
c1904c47cfe04e5bacb7261cf7a1d2501dfc3332
viththiananth/My-Python-Practise
/11. Check Primality Functions.py
1,713
4.1875
4
#Ask the user for a number and determine whether the number # is prime or not. (For those who have forgotten, # a prime number is a number that has no divisors.). # You can (and should!) use your answer to Exercise 4 to # help you. Take this opportunity to practice using functions, # described below. #num=int(input("Please type the Number you want to calculate :")) #list1=[] # ##Solution 1 #def prime_num(num): ## if num==1: # # for i in range(2,num): # if num%i==0: # list1.append(i) # if list1==[]: # print("This is a Prime Number") # else: # print("This is not a Prime Number") # #a=prime_num(num) # # ##Solution 2 #list2=[a for a in range(2,num) if num%a==0] #print(list2) # #def check_prime(new_list): # if num==1: # print("Print Value other than 1") # elif num==2: # print("This is a Prime Number") # elif list2==[]: # print("This is a Prime Number") # else: # print("This is not a Prime Number") # #a=check_prime(list2) #Soution 3 (From Online) def input_text(prompt): '''Return the Integer Value''' return int(input(prompt)) def is_prime(number): '''Returns True for prime numbers, False otherwise''' if number==1: prime=False elif number==2: prime=True else: prime=True for i in range(2,number): if number%i==0: prime=False break return prime def print_prime(number): prime=is_prime(number) if prime: descriptor="" else: descriptor="not" print("This is",descriptor,"Prime Number") while 1==1: print_prime(input_text("Please Input the Number to check or CTRL+C for Exit"))
true
8b3bfb58367bd57f4e474a7dc475b983214b3bcd
viththiananth/My-Python-Practise
/16. Password Generator.py
1,118
4.1875
4
#Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method. #Ask the user how strong they want their password to be. For weak passwords, pick a word or two from a list. #Solution 1 import random import string s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?" print("".join(random.sample(s,20))) #Solution 2 import random import string def password_gen(size,char=string.ascii_letters+string.digits+string.punctuation): return ''.join(random.choice(char) for i in range(size)) a=password_gen(int(input("Please type length of the Password"))) print(a) #Solution 3 import random import string def password_gen1(size=12, char=string.ascii_letters+string.punctuation+string.digits): lst1=[] for i in range(size): lst1.append(random.choice(char)) return ''.join(lst1) c=password_gen1(15) print(c)
true
57e8501523b862c44d87e29d8577bfd759a54da8
oldman1991/learning_python_from_zero
/work/work_demo05.py
1,671
4.21875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # create by oldman # Date: 2019/1/10 # 1,编程实现9*9乘法表 # 2. 用函数实现一个判断,用户输入一个年份,判断是否是闰年 # 3. 用函数实现输入某年某月某日,判断一下这一天是这一年的第几天,需要考虑闰年 import datetime def multiplication_table(): for i in range(1, 10): for j in range(1, i + 1): print(str(j) + "*" + str(i) + "=" + str(i * j), end="\t") # \t 横向制表符 print() # multiplication_table() def is_leap_year(year): assert type(year) == int if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return False # print(is_leap_year(1997)) # print(is_leap_year(2000)) def get_which_days(date): date_today = datetime.datetime.strptime(date, '%Y-%m-%d') print(type(date_today)) print(date_today.year) print(date_today.month) print(date_today.day) count = 0 # 判断该年是平年还是闰年 if (date_today.year % 4 == 0 and date_today.year % 100 != 0) or date_today.year % 400 == 0: print('%d年是闰年,2月份有29天!' % date_today.year) li1 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] for i in range(date_today.month - 1): count += li1[i] return count + date_today.day else: print('%d年是平年,2月份有28天!' % date_today.year) li2 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] for i in range(date_today.month - 1): count += li2[i] return count + date_today.day print(get_which_days('2018-02-1'))
false
197c33c4b87a081269f3223c5a5828e728f34bbe
Aswin-Sureshumar/Python-Programs
/bubble.py
227
4.21875
4
def bubble_sort(list): for i in range(len(list)-1,0,-1): for j in range(i): if list[j]>list[j+1]: list[j],list[j+1]=list[j+1],list[j] list=[9,8,7,5,1,11] bubble_sort(list) print(" The sorted list is : ",list)
false
9bf1d0dd74c501be2fcba420a3c4e9fa4d9b25b0
ziyingye/python_intro
/HW/HW3/HW3.py
2,472
4.15625
4
from math import pi from pprint import pprint from icecream import ic # 120% def compute_rect(top_left, bottom_right): """ compute the area of square :param top_left: vertices of top left corner :type top_left: tuple :param : vertices of bottom right corner :type bottom_right: tuple :return area_square """ assert isinstance(top_left, tuple), "top_left must be tuple" assert isinstance(bottom_right, tuple), "bottom_right must be tuple" assert len(top_left) == 2 assert len(bottom_right) == 2 x1, y1 = top_left x2, y2 = bottom_right w = y2 - y1 l = x2 - x1 return abs(w*l) if __name__ == '__main__': ''' # P1: Calculate the area of square, name your function an compute_square(top_left, bottom_right) where top_left, bottom_right should ba vertices of top left corner and bottom right corner respectively e.g top_left = (i,j) bottom_right = (i+k, j+k) where k is the length of the side in the square return the area of square and print the result using fstring in 3 decimal place ''' tl, br = (-1, 2), (2, -1) area = compute_rect(tl, br) print(area) ''' # P2: Create an dictionary which contain at least 5 info of yourself. Inverse the dictionary and store inverse dictionary's key in a list. Finally add this list to original dictionary with key="comb_info" ''' # my_dict: dict = {} # my_dict["name"] = "Ziyingye" # my_dict["age"] = [22] # my_dict["height"] = [169] # my_dict["weight"] = [118.5] # my_dict["birthday"] = (6,2,1998) # print(my_dict) from typing import List, Set, Dict, Tuple, Optional, Any my_dict: Dict[str, Any] = { "name": "Ziyingye", "age": 22, "height": 169, "weight": 118.5, "birthday": (6, 2, 1998) } print(my_dict) # for key,value in my_dict.items(): # print(key,value) inv_dict = {v: k for k, v in my_dict.items()} print(inv_dict, "\n") lst = list(inv_dict.items()) print(lst, "\n") # my_dict.update({"combo_info": lst}) # print(my_dict, "\n") my_dict["combo_info"] = lst print(my_dict, "\n") ''' # P3: Loop through the key's in you dictionary(original dict after adding comb_info) create in P2, stores key in a list and sort it in alphabetic order ''' lst2 = list(my_dict.keys()) print(lst2, "\n") lst2 = sorted(lst2) print(lst2)
false
946deb8b75fb2f6aa256423df749acd46b53af28
lroolle/CodingInPython
/leetcode/336_palindrome_pairs.py
1,150
4.1875
4
#!usr/bin/env python3 """LeetCode 336. Palindrome Pairs > Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. - Example 1: Given words = ["bat", "tab", "cat"] Return [[0, 1], [1, 0]] The palindromes are ["battab", "tabbat"] - Example 2: Given words = ["abcd", "dcba", "lls", "s", "sssll"] Return [[0, 1], [1, 0], [3, 2], [2, 4]] The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] """ def is_palindrome(s): length = len(s) for i in range(length // 2 + 1): if s[i] != s[-(i + 1)]: return False return True def palindrome_pairs(l): res = list() for i, item in enumerate(l): for j in range(i + 1, len(l)): if is_palindrome(item + l[j]): res.append([i, j]) if is_palindrome(l[j] + item): res.append([j, i]) return res def palindrome_pairs2(l): pass print(palindrome_pairs(["abcd", "dcba", "lls", "s", "sssll"]))
true
4197a945fa1cea1dfd132bb21a12340640d50c69
Virjanand/LearnPython
/005_stringFormatting.py
474
4.3125
4
# String formatting with argument specifiers name = "John" print("Hello, %s!" % name) # Use two or more argument specifiers name = "Jane" age = 23 print("%s is %d years old." % (name, age)) # objects have "repr" method to format it as string mylist = [1, 2, 3] print("A list: %s" % mylist) # Exercise: write Hello John Doe. Your current balance is $53.44. data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%.2f" print(format_string % data)
true
cdfc3b31fed2480004ec70e5e03cfb0ff491716b
Virjanand/LearnPython
/009_functions.py
1,455
4.40625
4
# Functions are blocks of code #block_head: # 1st block line # 2nd block line # Functions are defined using def func_name def my_function(): print("Hello from my function!") # Arguments def my_function_with_args(username, greeting): print("Hello, %s, from my function! I wish you %s" % (username, greeting)) # Return values def sum_two_numbers(a, b): return a + b # Call function my_function() my_function_with_args("John Doe", "a great year!") x = sum_two_numbers(1, 2) print(x) # Exercise use existing function and create own # 1. list_benefits() returns list of strings: # "More organized code", # "More readable code", # "Easier code reuse", # "Allowing programmers to share and connect code together" # 2. build_sentence(info) returns string with info at start and # " is a benefit of functions!" at the endswith # Modify this function to return a list of strings as defined above def list_benefits(): return ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"] # Modify this function to concatenate to each benefit - " is a benefit of functions!" def build_sentence(benefit): return benefit + " is a benefit of functions!" def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print(build_sentence(benefit)) name_the_benefits_of_functions()
true
0d23ff1b5d66a7d90d77af0a6d30ae3c6bac8118
herereadthis/timballisto
/tutorials/abstract/abstract_04.py
808
4.4375
4
"""More on abstract classes.""" """ AbstractClass isn't an abstract class because you can create an instance of it. Subclass must implement the (abstract) methods of the parent abstract class. MyClass does not show an implementation of do_something() """ from abc import ABC, abstractmethod class AbstractClass(ABC): """A simple class.""" @abstractmethod def do_something(self): """Demo abstract method.""" print('from the abstract method') class MyClass(AbstractClass): """Subclass of abstract class.""" def do_something(self): """Demo subclass method.""" super().do_something() print('from the sub class') if __name__ == '__main__': a = MyClass() a.do_something() # >>> from the abstract method # >>> from the sub class
true
a3fa46c6ae0d0316e11dba1e8a556ac65e80fc8c
priyeshkolte/EDUYEAR-PYTHON---20
/Day 3.py
959
4.1875
4
# Day 3 Assignments #age year calculator print("welcome to age in years calculator") a=input("please enter the year of bitth and press enter " ) age = int(a) result = 2021-age print("YOUR AGE IS"+" " + str (result) + " years \n") ##simple calculator print(" \n welcome to simple arithmatic claculation operator program") print("you are requested to enter two number viz. A and B on which the arithmatic operations will be perfored") a = input("please enter value for A ") b = input("please enter value for B ") A=int(a) B=int(b) add =A+B sub =A-B div =A/B mul =A*B mod =A%B exp =A**B floor_div =A//B print("A added B = "+ str(add)) print("A subtracted B = "+ str(sub)) print("A divided by B = "+ str(div)) print("A multiplied by B = "+ str(mul)) print("A modulus of B = "+ str(mod)) print("A exponent of B = "+ str(exp)) print("A floor division of B = "+ str(floor_div)) # end of Day 3 Assignments
false
abc124c578327b3e4b9a4ee3ce9e5300d6374af9
amaurya9/Python_code
/fileReverseOrder.py
762
4.375
4
#Write a program to accept a filename from user & display it in reverse order import argparse items=[] def push(item): items.append(item) def pop(): return items.pop() def is_empty(): return (items == []) def ReadFile(i): fd=open(i) char1=fd.read(1) while char1: push(char1) char1=fd.read(1) fd1=open("NewTestFile.txt","w+") while not is_empty(): fd1.write(pop()) fd1.close() fd1=open("NewTestFile.txt") print(fd1.read()) def main(): parser=argparse.ArgumentParser("please enter file name to reverse") parser.add_argument("-i",type=str,help="enter input file name") pars=parser.parse_args() ReadFile(pars.i) if __name__ == '__main__': main()
true
29877f7706f9b95ae71fd344bfd4ec031e481b35
Shaners/Python
/collatzSeq.py
424
4.25
4
def collatz(num): if num % 2 == 0: return num // 2 else: return 3 * num + 1 while True: try: print("Please provide a number.") num = int(input('> ')) except ValueError: print("Error: Invalid argument. You did not provide a number.") continue else: break while collatz(num) != 1: print(collatz(num)) num = collatz(num) print(collatz(num))
true
0e7d16c28f81bd3a89965e28314437257da5bf72
Shaners/Python
/weightHeightConverter.py
354
4.15625
4
# Height and Weight Converter # Set height variable to height in inches # Set weight variable to weight in lbs # This will print to console height in centimeters and weight in Kilograms height = 74 # inches weight = 180 # lbs print(f"{height} inches is {height * 2.54} centimeters tall.") print(f"{weight} lbs is {weight * 0.453592} kilograms heavy.")
true
2276cbfff7abb897c84bfba8b32999689da9890e
juliagarant/LearningPython
/COMP2057/Assignment3_104987469.py
657
4.21875
4
""" Assignment 3 for Programming for Beginners Julia Garant 104987469 Mar 29 2020 """ def main(): user_num = int(input("Enter an integer greater than 1: ")) numbers = [] for count in range(2, user_num + 1): # range is (inclusive,exclusive) which is why I need +1 numbers.append(count) for i in range(len(numbers)): prime_or_composite(numbers[i]) def prime_or_composite(n): has_divisor = False for i in range(2, n): if n % i == 0: has_divisor = True if has_divisor: # if true print(n, " is composite.") elif not has_divisor: # if false print(n, " is prime.") main()
true
87e55d48afe12116907a2c60c8639a3312e34568
RodrigoTXRA/Python
/If.Statement.py
527
4.40625
4
# If statements are either true or false # If condition is true it will action something otherwise it action sth else # boolean variable below is_male = True is_tall = True # Using OR one of the condition can be true # Using AND both conditions must be true if is_male and is_tall: print("You are a male or tall or both") elif is_male and not(is_tall): print("You are a short male") elif not(is_male) and is_tall: print("You are not a male and is tall") else: print("You are neither male or tall")
true
a677bbd4b38851ef90af67fc9be48af051c29cec
EllaT/pickShape
/pickShape.py
573
4.1875
4
from turtle import * from random import randint shapes = int(input("How many shapes?")) for i in range(shapes): length_of_side = int(input("How many sides?")) size = int(input("How many forward steps?")) color = (input("What color?")) number = (randint (20, 90)) for i in range(length_of_side): pencolor(color) pendown() forward(size) if length_of_side <= 2: print("no no") # Hmmm = False else: print("ok") angle = 360/length_of_side right (angle) #count += 1 right (randint(20, 360)) penup() forward(number) getscreen()._root.mainloop()
true
e94c488be437105918c000ac79a3551ab7841b84
limanmana/python-
/pycharm_wenjian/L10-数据库基础和sqlite/2-sqlite示例1.py
1,706
4.25
4
# (重点)sqlite示例 创建表,写数据 import sqlite3 connect = sqlite3.connect("testsqlite.db") cursor = connect.cursor() # cursor.execute("""CREATE TABLE student( # id INT PRIMARY KEY, # name VARCHAR(10) # ); """) cursor.execute(""" INSERT INTO student (id, name) VALUES (2, "小明"); """) cursor.close() connect.commit() connect.close() """ (了解)数据库驱动:数据库有自己本身的软件构造和操作语言,数据库暴露出操作接口,方便跟其它各种编程语言对接。编程语言到数据库的对接中介 叫驱动。所以我们用python操作数据库要使用驱动。 步骤: 1. 引入驱动包 2. 连接数据库,得到会话。 中大型数据库需要先用户名、密码验证,再创建数据库,再连接数据库;而轻量级的sqlite省略了前面的过程直接连接,如果这个数据库不存在的话,会新生成一个库,数据保存在一个单db文件中。 3. 生成游标。 游标:游标是对数据库某一行某一格进行增删改查的操作者,就好像操作excel表格时的鼠标。 4. 插入一些数据。 注意主键id列不能重复。 5. 关闭游标。 这一步可以省略。 6. 提交 commit。 除了查询,增加、修改、删除操作都需要在执行sql提交,否则不生效,好像平时用软件保存时的确认对话框。 7. 断开会话连接,释放资源。 """ """ 可能的异常: 1. 唯一约束错误,主键重复。 sqlite3.IntegrityError: UNIQUE constraint failed: student.id 2. 表已存在重复创建。sqlite3.OperationalError: table student already exists """
false
832c2e39b074233947a2783eaeba6f4f7ce44114
mehakgarg911/Basics_of_Python_Programming_1
/question7.py
246
4.125
4
def factorial(num1): fact =1 for x in range(2,num1+1): fact*=x return fact def rec_factorial(num1): if num1==0 or num1==1: return 1; else: return num1*rec_factorial(num1-1); print(factorial(6)) print(rec_factorial(6))
true
87eb176f50ef2a325f6bb8408fd4e4e3bfce1a01
feminas-k/MITx---6.00.1x
/problemset6/applycoder.py
396
4.15625
4
def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ r = '' for char in text: if char in coder: r += coder[char] else: r += char return r
true
fe8f96cff7baa842c2397a7a4d0750ee8a7aa292
AJsenpai/codewars
/titleCase.py
1,295
4.25
4
""" Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed. """ # my solution def title_case(title, minor_words=""): newtitle = "" for index, val in enumerate(title.split()): if val.lower() in minor_words.lower().split() and index != 0: newtitle += f"{val.lower()} " else: newtitle += f"{val.title()} " return newtitle.strip() print(title_case(title="First a of in", minor_words="an often into")) # Expected 'First A Of In' but # print(title_case("THE WIND IN THE WILLOWS", "The In")) # Test.assert_equals(title_case('a clash of KINGS', 'a an the of'), 'A Clash of Kings') # Test.assert_equals(title_case('THE WIND IN THE WILLOWS', 'The In'), 'The Wind in the Willows') # Test.assert_equals(title_case('the quick brown fox'), 'The Quick Brown Fox') # codewars solution def title_case(title, minor_words=""): return " ".join( c if c in minor_words.lower().split() else c.title() for c in title.capitalize().split() )
true
16f4933df1f63e9e92a5f136e4d61802f376bb16
AJsenpai/codewars
/isSquare.py
1,028
4.21875
4
# Kyu 7 """ Given an integral number, determine if it's a square number: In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. The tests will always use some integral number, so don't worry about that in dynamic typed languages. Examples -1 => false (negative number is not a perfect square) 0 => true 3 => false 4 => true 25 => true 26 => false """ # my solution import math def is_square(n): return True if n >= 0 and math.isqrt(n) ** 2 == n else False # codewars 1 def is_square(n): return n >= 0 and (n ** 0.5) % 1 == 0 # anything % 1 will always have no remainder, in other words whole number will # always give remainder 0, and floated numbers will give precision value as remainder # codewars 2 import math def is_square(n): if n < 0: return False sqrt = math.sqrt(n) return sqrt.is_integer() print(is_square(26)) # print(is_square(25)) # print(is_square(-1))
true
e0fc750cd3c4a2260e6cc12a364d9d2efbdf4c64
mepky/verzeo-project
/verzeo minor project/prime_or_not.py
378
4.125
4
n=int(input('Enter the number:')) def checkprime(n): if n<=1: return False for i in range(2,n): if (n%i==0): return False return True if checkprime(n): print(n,"is prime number") else: print(n,'is not a prime number') #time complexity o(n) #space comlexity o(n)
true
9093342f336ee965a5c0ac03f783477b571d217a
SmurfikComunist/light_it_calculator
/calculator/calculator.py
972
4.1875
4
""" Calculator module """ from math import sqrt class Calculator: """ Calculator implementation """ def add(self, x: int, y: int) -> int: """ Add to attributes to each other """ return x + y def subtract(self, x: int, y: int) -> int: """ Subtract one attribute from another """ return x - y def divide(self, x: int, y: int) -> float: """ Divide x attribute on y """ if y == 0: raise ZeroDivisionError('division by zero') return x / y def multiply(self, x: int, y: int) -> int: """ Multiply x attribute on y """ return x * y def mod(self, x: int, y: int) -> int: """ Take mod of one attribute from another """ return x % y def power(self, x: int, y: int) -> int: """ Raise attributes x to a power y """ return x ** y def root(self, x: int) -> float: """ Take a root from attributes """ return sqrt(x)
false
b1c3e745d09b7a1ce161a41b5bf1ec70d6f33353
953250587/leetcode-python
/LargestTriangleArea_812.py
1,748
4.1875
4
""" You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points. Example: Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]] Output: 2 Explanation: The five points are show in the figure below. The red triangle is the largest. Notes: 3 <= points.length <= 50. No points will be duplicated. -50 <= points[i][j] <= 50. Answers within 10^-6 of the true value will be accepted as correct. """ class Solution(object): def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float 441ms """ import math def LENGTH_2(a): return a[0] ** 2 + a[1] ** 2 ans = 0 l = len(points) for i in range(l - 2): for j in range(i, l - 1): for k in range(j, l): a = [points[i][0] - points[k][0], points[i][1] - points[k][1]] b = [points[j][0] - points[k][0], points[j][1] - points[k][1]] c = a[0] * b[0] + a[1] * b[1] ans = max(ans, math.sqrt(LENGTH_2(a) * LENGTH_2(b) - c ** 2)) return ans / 2.0 def largestTriangleArea_1(self, p): """ :type points: List[List[int]] :rtype: float 158ms """ import itertools def f(p1, p2, p3): (x1, y1), (x2, y2), (x3, y3) = p1, p2, p3 return 0.5 * abs(x2 * y3 + x1 * y2 + x3 * y1 - x3 * y2 - x2 * y1 - x1 * y3) return max(f(a, b, c) for a, b, c in itertools.combinations(p, 3)) print(Solution().largestTriangleArea(points = [[0,0],[0,1],[1,0],[0,2],[2,0]])) print(Solution().largestTriangleArea([[8,10],[2,7],[9,2],[4,10]]))
true
ae33090f151b891fe79a8e2286e13745ff2f3900
953250587/leetcode-python
/KdiffPairsInAnArray_532.py
2,322
4.125
4
""" Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs. Example 2: Input:[1, 2, 3, 4, 5], k = 1 Output: 4 Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). Example 3: Input: [1, 3, 1, 5, 4], k = 0 Output: 1 Explanation: There is one 0-diff pair in the array, (1, 1). Note: The pairs (i, j) and (j, i) count as the same pair. The length of the array won't exceed 10,000. All the integers in the given input belong to the range: [-1e7, 1e7]. """ from collections import Counter class Solution(object): def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int 59ms """ # sum=0 if k > 0: # print(set(nums)) # print(set(n + k for n in nums)) # print(set(nums) & set(n + k for n in nums)) return len(set(nums) & set(n + k for n in nums)) elif k == 0: for i in [v > 1 for v in Counter(nums).values()]: if i==True: sum+=1 return sum else: return 0 def findPairs_1(self, nums, k): sum=0 if k==0: for i in [v > 1 for v in Counter(nums).values()]: if i==True: sum+=1 return sum if k>0: l2=sorted(list(set(nums))) k1=0 for i in range(len(l2)): k1=max(i+1,k1) for j in range(k1,len(l2)): if l2[j]==l2[i]+k: sum+=1 k1=j break elif l2[j]>l2[i]+k: k1=j break return sum print(Solution().findPairs_1([1,3,1,5,6],0)) print(Solution().findPairs_1([3, 1, 4, 1, 5],2)) print(Solution().findPairs_1([1,2,3,4,5],1))
true
3cea738e3ba2ed6322d0ca1c5beaf65379977b69
953250587/leetcode-python
/DifferentWaysToAddParentheses_MID_241.py
2,744
4.15625
4
""" Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. Example 1 Input: "2-1-1". ((2-1)-1) = 0 (2-(1-1)) = 2 Output: [0, 2] Example 2 Input: "2*3-4*5" (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10 Output: [-34, -14, -10, -10, 10] """ class Solution(object): def diffWaysToCompute(self, input): """ :type input: str :rtype: List[int] 106ms """ def operation(input): count=0 operationlist=[] for i in input: if i.isdigit(): pass else: operationlist.append(count) count+=1 # print('position',operationlist) return operationlist def calc_Compute(input): operation_lists=operation(input) if len(operation_lists)==0: return [int(input)] if len(operation_lists)==1: i=operation_lists[0] result=eval(str(input[0:i]) + input[i] + str(input[i+1:])) return [result] all_together = [] for i in range(len(operation_lists)): left = [] right = [] left.extend(calc_Compute(input[0:operation_lists[i]])) right.extend(calc_Compute(input[operation_lists[i]+1:])) for l in left: for r in right: all_together.append(eval(str(l) + input[operation_lists[i]] + str(r))) return all_together # operation(input) return calc_Compute(input) def calculate(self, l, r, oper): if oper == "*": return l * r elif oper == "+": return l + r else: return l - r def diffWaysToCompute_1(self, inpt): """ :type input: str :rtype: List[int] 58ms """ ret = [] if inpt.isdigit(): ret.append(int(inpt)) return ret else: for i in range(len(inpt)): if inpt[i] in "*+-": ret1 = self.diffWaysToCompute(inpt[:i]) ret2 = self.diffWaysToCompute(inpt[i + 1:]) for l in ret1: for r in ret2: ret.append(self.calculate(l, r, inpt[i])) return ret print(Solution().diffWaysToCompute("20*3-4*5")) # print(eval('5*3-10*2')) # print([i for i in range(1,5,2)]) # a=3;b=4 # str=str(str(a)+'+'+str(b)) # print(eval(str))
true
738e8c67cba389fb6720beb1e5872f7713a20275
953250587/leetcode-python
/ShortestPalindrome_HARD_214.py
2,620
4.21875
4
""" Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa". Given "abcd", return "dcbabcd". """ class Solution(object): def shortestPalindrome(self, s): """ :type s: str :rtype: str """ if s == "": return "" def getnext(a, next): al = len(a) next[0] = -1 k = -1 j = 0 while j < al - 1: if k == -1 or a[j] == a[k]: j += 1 k += 1 if a[j] == a[k]: next[j] = next[k] else: next[j] = k else: k = next[k] b = s next = [0] * len(b) getnext(b, next) print(next) self.nums = 0 def KmpSearch(a, b): i = j = 0 al = len(a) bl = len(b) while i < al and j < bl: if j == -1 or a[i] == b[j]: i += 1 j += 1 else: j = next[j] self.nums = j KmpSearch(s[::-1], s) print(self.nums) return s[self.nums:][::-1] + s def shortestPalindrome_1(self, s): """ :type s: str :rtype: str 52ms """ size = len(s) while True: start = 0 end = size - 1 while end >= 0: if s[start] == s[end]: start += 1 end -= 1 if start == size: return s[size:][::-1] + s size = start def shortestPalindrome_2(self, s): """ :type s: str :rtype: str 42ms """ if len(s) <= 1: return s maxj, c = 1, 0 while c <= len(s) / 2: i = j = c while j + 1 < len(s) and s[j + 1] == s[j]: j += 1 if i > len(s) - j - 1: break c = j + 1 while i >= 0 and j < len(s) and s[i] == s[j]: i -= 1 j += 1 if i < 0: maxj = max(maxj, j) return s[maxj:][::-1] + s print(Solution().shortestPalindrome("aacecaaa")) # print(Solution().shortestPalindrome("abcd")) print(Solution().shortestPalindrome("aabba")) print(Solution().shortestPalindrome("aabbaa"))
true
4b17f1f4bd5fd6067b3fe78acd92cd4a76c6bfff
cvelezca/Practica_uso_git
/modulo_json.py
2,040
4.15625
4
""" Probar la libreria json de forma basica""" import json #json= string (cadena de caracteres). a continuacion se crea una variable tipo json con f (fstring) #f (fstring)= tipo de codificacion de python que permite meter variables dentro de cadenas de strings se ponen #tres comillas para indicar que se debe hacer salto de linea. variable_json ="""{"Carolina":"Velez", "Terry":"Rojas", "Juan Jose":"Rojas"}""" diccionario_json=json.loads(variable_json,) #transformar el string variable_json en un diccionario print(diccionario_json) #Para traer o cargar a python un archivo json with open('archivo.json','r') as f: #with = keyword para generar un entorno de ejecucion (scopes o ambitos) dentro animales = json.load(f) #de mi codigo para ejecutar funciones o acciones que deban ser cerradas justo despues de terminar su #ejecucion (se usa cuando la ejecucion representa una alta carga computacional) #open('archivo','r') funcion para abrir archivos. el argumento 'r' indica que #solo se leera el archivo. # as f indica que el archivo se guardara en una variable f #json.load(f) convierte el archivo json en un objeto de python tipo diccionario print(animales) print(type(animales)) diccionario={'Carolina':'Velez', 'Terry':'Rojas', 'Juan Jose':'Rojas'} print(json.dumps(diccionario)) # el metodo dumps convierte objetos tipo diccionario de python a formato json #Para crear archivos en formato json with open('D:/D/DEVNET ASSOCIATE/Practicas Juanjo/diccionario.json','w') as a: # open('ruta_archivonuevo','w') funcion #para crear un archivo .json. el argumento 'w' indica que se escribira sobre el # nuevo archivo. json.dump(diccionario,a) #tomar el diccionario, transformarlo en json y meterlo en un archivo
false
07f2ab307ebc2804f0ff99df449cb7b358b5ef12
David-sqrtpi/python
/returning-functions.py
463
4.375
4
def calculate_recursive_sequence(number): print(number) if number == 0: return number return calculate_recursive_sequence(number-1) def calculate_iterative_sequence(number): for i in range(number, -1, -1): print(i) number = int(input("Write a number to calculate its descending sequence to 0: ")) print("Recursive sequence") calculate_recursive_sequence(number) print("Iterative sequence") calculate_iterative_sequence(number)
true
b9985aff1e6ae6d0fb2d695d54f167b9dc4eb97c
artmur0202/AaDS_1_184_2021
/zad1.№7.py
585
4.21875
4
from math import* x = int(input("Введите переменную x: ")) y = int(input("Введите переменную y: ")) z = int(input("Введите переменную z: ")) def funct(x, y, z): D = y**2 - 4*x*z if D<0: print("Корней нет") elif D==0: f1=(-1*y/2*x) print("Единственный корень = ",f1) else: f1=(-1*y + sqrt(D))/(2*x) f2=(-1*y - sqrt(D))/(2*x) print("Пeрвый корень = ",f1) print("Второй корень = ",f2) funct(x, y, z)
false
322465c7512f10bcaa51192c186995ef1af0f6c1
Dzhevizov/SoftUni-Python-Fundamentals-course
/Programming Fundamentals Final Exam - 14 August 2021/01. Problem.py
1,250
4.34375
4
username = input() command = input() while not command == "Sign up": command = command.split() action = command[0] if action == "Case": case = command[1] if case == "lower": username = username.lower() else: username = username.upper() print(username) elif action == "Reverse": start_index = int(command[1]) end_index = int(command[2]) if start_index in range(len(username)) and end_index in range(len(username)): substring = username[start_index:end_index + 1] substring = substring[::-1] print(substring) elif action == "Cut": substring = command[1] if substring in username: username = username.replace(substring, "") print(username) else: print(f"The word {username} doesn't contain {substring}.") elif action == "Replace": char = command[1] username = username.replace(char, "*") print(username) elif action == "Check": char = command[1] if char in username: print("Valid") else: print(f"Your username must contain {char}.") command = input()
true
02cb52724d606e22f5c6f4dad9b8550247d2f99a
Ssellu/python_tutorials
/ch06_operators/test06_멤버쉡연산자.py
423
4.15625
4
""" < 멤버쉽 연산자 > - 원소의 구성 여부를 확인하는 연산자 - 결과값의 자료형은 bool형 (True 혹은 False) in : a in iterables (iterables 에 a가 있으면 True) not in : a not in iterables (iterables 에 a가 없으면 True) """ num1 = 3 num2 = 10 lst = [1, 2, 3, 4, 5] print(num1 in lst) # True print(num2 in lst) # False print(num1 not in lst) # False
false
e5d9e9b8bbebea5b78b1ba4eb97cf9ca27021337
ZTatman/Daily-Programming-Problems
/Day 3/problem3.py
2,180
4.25
4
# Author: Zach Tatman # Date: 5/26/21 ''' Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' ''' # Create a binary tree class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def preorder(root): if root: print(root.val) preorder(root.left) preorder(root.right) else: return def insert(root, val): if not root: return Node(val) else: if root.val is val: return root elif val < root.val: root.left = insert(root.left, val) elif val > root.val: root.right = insert(root.right, val) return root def serialize(root): nodes = [] def helper(root, nodes): if root: # print(f'Appending... {root.val}') nodes.append(str(root.val)) helper(root.left, nodes) helper(root.right, nodes) else: # print(f'Appending... \'n\'') nodes.append('n') serialized = ','.join(nodes) # print(f'Serialized: {serialized}') return serialized return helper(root, nodes) def deserialize(tree): tree = tree.split(',') root = Node(int(tree[0])) tree.remove(tree[0]) for val in tree: if val == 'n': continue else: # print(f'Deserializing... {val}') root = insert(root, int(val)) return root # Instantiate tree root = Node(4) root = insert(root, 23) root = insert(root, 1) root = insert(root, 90) root = insert(root, 76) root = insert(root, 30) assert serialize(root) == serialize(deserialize(serialize(root)))
true
c3eadb1541b822fcad2aee32bd7700639f765f15
soccergame/mincepie
/mincepie/demo/wordcount.py
2,197
4.125
4
""" Wordcount demo This demo code shows how to perform word count from a set of files. we show how to implement a simple mapper and reducer, and launch the mapreduce process. To run the demo, run: python wordcount.py --input=zen.txt This will execute the server and the client both locally. Optionally, you can run the server and client manually. On the server side, run: python wordcount.py --launch=server --input=zen.txt And on the client side, simply run python wordcount.py --launch=client --address=SERVER_IP where SERVER_IP is the ip or the hostname of the server. If you are running the server and the client on the same machine, --address=SERVER_IP could be omitted. Optionally, you can add the following arguments to the server side so that the counts are written to a file instead of dumped to stdout: --writer=FileWriter --output=count.result (count.result could be any filename) """ # (1) Import necessary modules: You need mapreducer to write your mapper and # reducer, and launcher to launch your program. from mincepie import mapreducer from mincepie import launcher # (2) Write our mappers and reducers, derived from mapreducer.BasicMapper and # mapreducer.BasicReducer respectively. # For our case, the input value of the mapper is a string (filename), and the # input key does not matter. the input key of the reducer is the word, and the # value is a list of counts to be summed up. # Optionally, we register the mappers and reducers as default so we do not need # to specify them in the commandline arguments. class WordCountMapper(mapreducer.BasicMapper): """The wordcount mapper""" def map(self, key, value): with open(value,'r') as fid: for line in fid: for word in line.split(): yield word, 1 mapreducer.REGISTER_DEFAULT_MAPPER(WordCountMapper) class WordCountReducer(mapreducer.BasicReducer): """The wordcount reducer""" def reduce(self, key, value): return sum(value) mapreducer.REGISTER_DEFAULT_REDUCER(WordCountReducer) # (3) Finally, the main entry: simply call launcher.launch() to start # everything. if __name__ == "__main__": launcher.launch()
true
dde50d7e399e4d3e9414fa3a92492d5edbfdcc81
rwu8/MIT-6.00.2x
/Week 1/Lecture 2 - Decision Trees/Exercise1.py
751
4.21875
4
def yieldAllCombos(items): """ Generates all combinations of N items into two bags, whereby each item is in one or zero bags. Yields a tuple, (bag1, bag2), where each bag is represented as a list of which item(s) are in each bag. """ # Your code here N = len(items) # any given item have 3 condition: bag1, bag2, not taken # so enumerate 3**N possible combinations for i in range(3**N): bag_1 = [] bag_2 = [] for j in range(N): if (i // 3**j) % 3 == 1: bag_1.append(items[j]) elif (i // 3**j) % 3 == 2: bag_2.append(items[j]) yield (bag_1, bag_2) a = yieldAllCombos([1, 2, 3]) for n in a: print(n)
true
fc1863c9d52aeb479680be82aa4201694b9a0e21
rmoore2738/CS303e
/assignment4_rrm2738.py
1,599
4.28125
4
#Rebecca Moore RRM2738 #Question 1 print("I’m thinking of a number from 1 to 10000. Try to guess my \nnumber! (Enter 0 to stop playing.)") guess = input("Please enter your guess:") guess = int(guess) number = 1458 if guess == number: print("That's correct! You win! You guessed my number in X guesses.") while guess != number: if guess < number: print("Your guess is too low.") guess = input("Please enter your guess:") guess = int(guess) elif guess > number: print("Your guess is too high.") guess = input("Please enter your guess:") guess = int(guess) elif guess > 10000: guess = input("Please enter your guess:") guess = int(guess) elif guess == 0: print("Goodbye!") else: break #question 2 spaces = 4 #number of spaces before stars for i in range(1,6,1): #loop to draw stars print(" "*spaces + i*"*") spaces= spaces - 1 #question 3 import turtle #allows the use of turtle graphics turtle.speed(10) width=7 height=10 distance=30 for i in range (height): for i in range(width): turtle.circle(15) # This line creates a circle with a diameter of 30 turtle.penup() # This lifts the pen up so that when the turtle moves it does not draw. turtle.forward(distance) # Moves the turtle forward 30 turtle.pendown() # Puts the pen back down ready to draw the next time we go through the loop turtle.penup() turtle.back(distance*width) turtle.right(90) turtle.forward(distance) turtle.left(90) turtle.pendown() turtle.done()
true
ad7f18c17fb1757033f7647597c12a8187f1e824
rohitx/DataSciencePrep
/PythonProblems/coderbyte/Second_Great_Low.py
790
4.15625
4
''' Using the Python language, have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will contain at least 2 numbers. It can get tricky if there's just two numbers! ''' def SecondGreatLow(arr): max_val = max([n for n in arr if n!= max(arr)]) min_val = min([n for n in arr if n!=min(arr)]) result = str(min_val) + " " + str(max_val) return result # keep this function call here # to see how to enter arguments in Python scroll down #print SecondGreatLow([7, 7, 12, 98, 106]) #print SecondGreatLow([1,42,42,180]) print SecondGreatLow([4,90])
true
318f7d8acb098cd424025e2dd8bb9e085e8e3c58
rohitx/DataSciencePrep
/PythonProblems/precourse/problem9.py
499
4.25
4
def word_lengths2(phrase): ''' INPUT: string OUTPUT: list of integers Use map to find the length of each word in the phrase (broken by spaces) and return the values in a list. ''' # I will make use of the lambda function to compute the # length of the words # first I will break the string into words words = phrase.split(" ") return map(lambda x: len(x), words) if __name__ == '__main__': M = "Welcome to Zipfian Academy!" print word_lengths2(M)
true
699f4acd1a878494f7294565e6cafde8296398bc
rohitx/DataSciencePrep
/PythonProblems/precourse/problem6.py
1,121
4.4375
4
import numpy as np def average_rows1(mat): ''' INPUT: 2 dimensional list of integers (matrix) OUTPUT: list of floats Use list comprehension to take the average of each row in the matrix and return it as a list. Example: >>> average_rows1([[4, 5, 2, 8], [3, 9, 6, 7]]) [4.75, 6.25] ''' # This looks like a list of lists # I will use list comprehension to create a new list # and compute average for each list. Should I use the in-build # average function or create my own? Do both # # Using in-built function return [np.mean(col) for col in mat] # # Creating from scratch # First compute the sum for each col # Compute the length of each column # Calculate the average sums_len = {} for col in mat: count = 0 sums = 0 for element in col: sums += element count += 1 sums_len[sums] = count print sums_len return [total/float(count) for total, count in sums_len.iteritems()] if __name__ == '__main__': M = [[4, 5, 2, 8], [3, 9, 6, 7]] print average_rows1(M)
true
b2860e5741a5196f5cfded6bc2a8c8e7d1cd41e5
rohitx/DataSciencePrep
/PythonProblems/coderbyte/longest_word.py
780
4.46875
4
''' Using the Python language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. ''' def LongestWord(sen): d = {} words = sen.split(" ") for word in words: word = word.replace("&","").replace("!","").replace("*","").replace("?","").replace("#","").replace("#","").replace("$","").replace("%","") d[word] = len(word) sorted_d = sorted(d.items(), key=lambda x: x[1], reverse=True) return sorted_d # keep this function call here # to see how to enter arguments in Python scroll down print LongestWord( "hello world")
true
5bbca24e796907dd70f15221aa58438e860f97c0
rohitx/DataSciencePrep
/PythonProblems/coderbyte/Ex_Oh.py
761
4.3125
4
''' Using the Python language, have the function ExOh(str) take the str parameter being passed and return the string true if there is an equal number of x's and o's, otherwise return the string false. Only these two letters will be entered in the string, no punctuation or numbers. For example: if str is "xooxxxxooxo" then the output should return false because there are 6 x's and 5 o's. ''' def ExOh(str): string = str x_count = 0 o_count = 0 for l in string: if l == 'x': x_count +=1 elif l == 'o': o_count +=1 if x_count == o_count: return 'true' else: return 'false' # keep this function call here # to see how to enter arguments in Python scroll down print ExOh("xooxx")
true
16f44df0d5b4db85c87ec8bc0e7d4415802f14eb
elad-allot/Udemy
/cake/is_binary_search_tree.py
1,496
4.125
4
class BinaryTreeNode(object): def __init__(self, value): self.value = value self.right = None self.left = None def insert_left(self, value): self.left = BinaryTreeNode(value) return self.left def insert_right(self, value): self.right = BinaryTreeNode(value) return self.right def is_binary_search_tree(binary_tree: BinaryTreeNode): if not binary_tree: return True val = binary_tree.value left = binary_tree.left right = binary_tree.right if (not right or right.value < val) and (not left or left.value > val): return is_binary_search_tree(binary_tree.right) and is_binary_search_tree(binary_tree.left) else: return False tree = BinaryTreeNode(50) right = tree.insert_right(70) right_right = right.insert_right(60) right_right.insert_right(80) result = is_binary_search_tree(tree) print (is_binary_search_tree(tree)) def is_bst(root: BinaryTreeNode): node_and_bounds_stack = [(root, -float('inf'), float('inf'))] while len(node_and_bounds_stack): node, lower_bound, upper_bound = node_and_bounds_stack.pop() if (node.value <= lower_bound) or (node.value > upper_bound): return False if node.left: node_and_bounds_stack.append((node.left, lower_bound, node.value)) if node.right: node_and_bounds_stack.append((node.right, node.value, upper_bound)) return True print(is_bst(tree))
true
caee4a4b0415440b3d790033e791762a8542fe5c
syeluru/MIS304
/basic.py
696
4.125
4
# Program to demonstrate basic python statements print("Welcome to Python Programming") message = "Welcome to Python Programming!!!" print (message) print(type(message)) # message is a variable of type str number = 25 print (number) print (type(number)) # number is a variable of type num price = 12.99 print (price) print (type(price)) check = True print (check) print (type(check)) #List which are mutable cityList = ['Austin', 'Dallas', 'Chicago'] print (cityList) print (type(cityList)) #Tuple is immutable studentList = ('James', 'Lisa') print (studentList) print (type(studentList)) print (id(number)) print (id(price)) number = 12.99 print (id(number)) price = 25 print (id(price))
true
93842a724512bb1c706efd214c07bde85f43809d
syeluru/MIS304
/ComputeArea.py
1,693
4.40625
4
#program to compute area """ length = 20 width = 5 area = length * width print (type(length)) print (type(width)) print (area) print (type(area)) length = 12.8 width = 5.6 area = length * width print (type(area)) print (area) #f is format specifier for floating numbers #.2 is two decimal places print ("Area = %.3f" %(area)) print ("Area =", format(area, '.2f')) print( "Area of rectangle = {}" .format(area)) #{} acts as a placeholder print ("Area of rectangle = {0:.2f}" .format(area)) print ("{0:.2f} is the area of the rectangle" .format(area)) print ("Area of rectangle with length {0:.2f} \ and width {1:.2f} is {2:.2f}\ " .format(length,width,area)) """ ''' #Find the area with user input length = int(input ("Enter the length: ")) width = int(input ("Enter the width: ")) print (type(length)) print (type(width)) #l = int(length) #w = int(width) area = length * width print (area) #Find the area of a circle # Get the user input radius = float(input ("Enter the radius: ")) circleArea = 3.14159 * radius * radius print (circleArea) print ("Area of circle with radius %.2f \ is %.2f" %(radius, circleArea)) ''' def find_area(length, width): #these are parameters area = length * width return(area) # void function because no values are returned (only printed) def display_message(message): print(message) def main(): length = 0.0 width = 0.0 area = 0.0 message = '' length = eval(input("Enter the length: ")) width = eval(input("Enter the width: ")) #Call a function to compute area area = find_area(length, width) message = "Area of rectangle: %.2f" %area #print (message) display_message(message) main()
true
9abd36a53d1ac0e7ce8192da50de38e489016ab4
yurifarias/CursoEmVideoPython
/ex059.py
1,187
4.34375
4
# Crie um programa que leia dois # valores e mostre um menu como o # ao lado na tela: # Seu programa deverá realizar a # operação solicitada em casa caso. # # [1] somar # [2] multiplicar # [3] maior # [4] novos números # [5] sair do programa num1 = float(input('Digite o primeiro número: ')) num2 = float(input('Digite o segundo número: ')) opção = 0 while opção != 5: print('[1] - Somar') print('[2] - Multiplicar') print('[3] - Maior') print('[4] - Novos números') print('[5] - Sair do programa') opção = int(input('Digite sua opção: ')) if opção == 1: print('A soma entre {} e {} é {}.'.format(num1, num2, num1 + num2)) elif opção == 2: print('A multiplicação entre {} e {} é {}.'.format(num1, num2, num1 * num2)) elif opção == 3: print('O maior número entre {} e {} é {}.'.format(num1, num2, max(num1, num2))) elif opção == 4: num1 = int(input('Digite o novo primeiro número: ')) num2 = int(input('Digite o novo segundo número: ')) elif opção == 5: print('Finalizando...') else: int(input('Por favor, digite um número válido: '))
false
c879dfea0085fb99c3e0b55adcb2c91d5767e7ed
yurifarias/CursoEmVideoPython
/ex016.py
405
4.1875
4
from math import floor, trunc número = float(input('Digite um número decimal: ')) '''# Convertendo para int print('A porção inteira do número {} é {}'.format(número, int(número)))''' # Usando math.floor() print('A porção inteira do número {} é {}'.format(número, floor(número))) '''# Usando math.trunc() print('A porção inteira do número {} é {}'.format(número, trunc(número)))'''
false
d3f8cad90b395b080a6317319d6b9e8837f1e5ff
yurifarias/CursoEmVideoPython
/ex060.py
266
4.1875
4
# Faça um programa que leia um número # qualquer e mostre o seu fatorial. # # Ex: # 5! = 5 * 4 * 3 * 2 * 1 = 120 fatorial = 1 num = int(input('Digite um número para se calcular o seu fatorial: ')) while num > 0: fatorial *= num num -= 1 print(fatorial)
false
363096b85d7fec25acae5e64105c09c2b4fd8b1d
Will-Fahie/stack-implementation
/stack.py
1,713
4.125
4
class Stack(object): def __init__(self, max_size): self.__items = [] self.__reverse_stack = [] self.__max_size = max_size def is_full(self): return len(self.__items) == self.__max_size def is_empty(self): return len(self.__items) == 0 def print_stack(self): for i in range(self.get_num_elements() - 1, -1, -1): if i == self.get_num_elements() - 1: print(self.__items[i], "<--- top of stack") else: print(self.__items[i]) def create_reverse_stack(self): for i in range(self.get_num_elements() - 1, -1, -1): self.__reverse_stack.append(self.__items[i]) return self.__reverse_stack def print_reverse_stack(self): for i in range(self.get_num_elements() - 1, -1, -1): if i == self.get_num_elements() - 1: print(self.__reverse_stack[i], "<--- top of stack") else: print(self.__reverse_stack[i]) def push(self, item): if self.is_full(): print("Stack is full so cannot push") else: self.__items.append(item) def pop(self): if self.is_empty(): print("Stack is empty so cannot pop") else: self.__items.pop(-1) def set_max_size(self, new_size): self.__max_size = new_size def get_max_size(self): return self.__max_size def get_num_elements(self): return len(self.__items) def peak(self): return self.__items[-1] if __name__ == "__main__": stack = Stack(5) stack.push("Hello") stack.push(3.14) stack.push([3, 2, 1]) stack.print_stack()
false
a7301fbb2f49e5c3d6bfcba808ee87687797796b
spencerf2/coding_temple_task3_answers
/question3.py
426
4.34375
4
# Question 3 # ---------------------------------------------------------------------- # Please write a Python function, max_num_in_list to return the max # number of a given list. The first line of the code has been defined # as below. # ---------------------------------------------------------------------- # def max_num_in_list(a_list): def max_num_in_list(a_list): print(max(a_list)) max_num_in_list([-1,0,1,2,3])
true
93de2ea8bac4cc7070de874a254ff6668c284cb9
jeffreytzeng/HackerRank
/Algorithms/Sorting/Insertion Sort - Part 1/my_solution.py
569
4.21875
4
def PrintArray(arr): """Printing each array elements.""" for i in range(len(arr)): print(str(arr[i]) + ' ' if i != len(arr)-1 else str(arr[i]), end='') def Sort(arr): """Sorting array by ascending.""" for i in reversed(range(len(arr))): key = arr[i] j = i-1 while (j >= 0 and key <= arr[j]): arr[j+1] = arr[j] j -= 1 PrintArray(arr) print('') arr[j+1] = key PrintArray(arr) n = int(input()) numbers = list(map(int, input().split())) Sort(numbers)
false
393c9787c87ac3ec229da96a87d394fd681b744b
laxos90/MITx-6.00.1x
/Problem Set 2/using_bisection_search.py
1,425
4.46875
4
__author__ = 'm' """ This program uses bisection search to find out the smallest monthly payment such that we can pay off the entire balance within a year. """ from paying_debt_off_in_a_year import compute_balance_after_a_year def compute_initial_lower_and_upper_bounds(balance, annual_interest_rate): monthly_interest_rate = annual_interest_rate / 12.0 lower_bound = balance / 12.0 upper_bound = balance * (1 + monthly_interest_rate) ** 12 / 12.0 return lower_bound, upper_bound def compute_lowest_payment_using_binary_search(balance, annual_interest_rate): lower_bound, upper_bound = compute_initial_lower_and_upper_bounds(balance, annual_interest_rate) while True: lowest_payment = (lower_bound + upper_bound) / 2.0 balance_after_a_year = compute_balance_after_a_year(balance, lowest_payment, annual_interest_rate) if abs(balance_after_a_year) <= 0.01: return lowest_payment if balance_after_a_year > 0: lower_bound = lowest_payment else: upper_bound = lowest_payment def main(): balance = eval(input("Enter the initial balance: ")) annual_interest_rate = eval(input("Enter the annual interest rate: ")) lowest_payment = compute_lowest_payment_using_binary_search(balance, annual_interest_rate) print("Lowest Payment: " + str(round(lowest_payment, 2))) if __name__ == "__main__": main()
true
5a23a290af8452c425a290c8201146b14cc7081f
badladpancho/Python_103
/While_loop.py
204
4.34375
4
# This is the basic to a while loop # will loop through until it is false # This is like it is done in C programing i = 0 while i <= 10: print(i); i += 1; print("Done with this loop")
true
ccaca618954119e58e0d107e36cd5ce48be68e0c
badladpancho/Python_103
/Guessing_Game.py
692
4.25
4
# This is going to be a simple game in order to guess # We are going to be using if statments while loops and other things that i have # learned. # MADE BY BADLADPANCHO print("Player 1 enter the secret word\n"); secret_word = input(""); print("OK lets play!"); guess = "" i = 0; chance_limit = 3; while guess != secret_word: guess = input("Player 2 Enter the guess word:\n"); if guess == secret_word: print("You guessed the right word!\n"); break; if i >= 3: print("You ran out of chances to guess the word\n"); break; i += 1; chance_limit -= 1; print("you have " + str(chance_limit)+ " chances left");
true
df294dbacb1c93363b2c3e7a2b5a4a5b1470a116
reddevil7291/Python
/Program to find the sum of n natural 2.py
302
4.125
4
print("Program to Find the sum of n Natural Numbers") n = eval(input("\nEnter the value of n:")) sum = float if(not isinstance(n,int)): print("\nWRONG INPUT") else: if(n<=0): print("\nERROR") else: sum1 = (n*(n+1))/2 print("The sum is ",sum1)
true
93ceca59795a7577174652ea4ef9e81ffc46d7a4
Mark24Code/python_data_structures_and_algorithms
/剑指offer/37_FirstCommonNodesInLists(两个链表的第一个公共结点).py
2,598
4.3125
4
""" 面试题37:两个链表的第一个公共结点 题目:输入两个链表,找出它们的第一个公共结点。链表结点定义如下: https://leetcode.com/problems/intersection-of-two-linked-lists/ 思路: 两个链表连接以后,之后的节点都是一样的了。 1. 使用两个栈push 所有节点,然后比较栈顶元素,如果一样就 都 pop继续比较。如果栈顶不一样,结果就是上一次 pop 的值。 2. 先分别遍历两个链表,找到各自长度,然后让一个链表先走 diff(len1-len2)步骤,之后一起往前走,找到的第一个就是。 """ # Definition for singly-linked list. class Node(object): def __init__(self, x, next=None): self.val = x self.next = next class _Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA is None or headB is None or (headA is None and headB is None): return None len1 = 0 cura = headA while cura: len1 += 1 cura = cura.next len2 = 0 curb = headB while curb: len2 += 1 curb = curb.next difflen = abs(len1 - len2) if len1 > len2: for i in range(difflen): headA = headA.next else: for i in range(difflen): headB = headB.next while headA and headB: if headA == headB: # headA.val == headB.val and headA.next == headB.next return headA headA = headA.next headB = headB.next return None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if headA is None or headB is None: return None len1 = 0 cura = headA while cura: len1 += 1 cura = cura.next len2 = 0 curb = headB while curb: len2 += 1 curb = curb.next difflen = abs(len1 - len2) if len1 > len2: for i in range(difflen): headA = headA.next else: for i in range(difflen): headB = headB.next while headA and headB: if headA == headB: # headA.val == headB.val and headA.next == headB.next return headA headA = headA.next headB = headB.next return None
false
d135fd7ec20c5ad900a18256337f55c4272b4bb5
Galyopa/SoftServe_Marathon
/Sprint_05/question04.py
1,879
4.5625
5
""" Question text Write the function check_number_group(number) whose input parameter is a number. The function checks whether the set number is more than number 10: in case the number is more than 10 the function should be displayed the corresponding message - "Number of your group input parameter of function is valid"; in case the number is less than 10 the function should be raised the exception of your own class ToSmallNumberGroupError and displayed the corresponding message - "We obtain error: Number of your group can't be less than 10"; in the case of incorrect data the function should be displayed the message - "You entered incorrect data. Please try again." Function example: check_number_group(number) (4) #output: "We obtain error: Number of your group can't be less than 10" check_number_group(number) (59) #output: "Number of your group 59 is valid" check_number_group("25") #output: "Number of your group 25 is valid" check_number_group("abc") #output: "You entered incorrect data. Please try again." """ class ToSmallNumberGroupError(Exception): def __init__(self, data): self.data = data def __str__(self): return repr(self.data) def check_number_group(number): try: if type(int(number)) is not int: raise ToSmallNumberGroupError("You entered incorrect data. Please try again.") if int(number) > 10: print(f"Number of your group {number} is valid") else: print("We obtain error: Number of your group can't be less than 10") except ToSmallNumberGroupError as tsnge: print(tsnge) except ValueError: print("You entered incorrect data. Please try again.") check_number_group(75) check_number_group("96") check_number_group("abc") check_number_group(0.8) check_number_group(-9)
true
f01841425d4f7d890e3f170bfb7cdefcf53c28bf
Galyopa/SoftServe_Marathon
/Sprint_03/question3.py
2,039
4.3125
4
""" Create function create_account(user_name: string, password: string, secret_words: list). This function should return inner function check. The function check compares the values of its arguments with password and secret_words: the password must match completely, secret_words may be misspelled (just one element). Password should contain at least 6 symbols including one uppercase letter, one lowercase letter, special character and one number. Otherwise function create_account raises ValueError. For example: tom = create_account("Tom", "Qwerty1", ["1", "word"]) raises Value error If tom = create_account("Tom", "Qwerty1_", ["1", "word"]) then tom("Qwerty1_", ["1", "word"]) return True tom("Qwerty1_", ["word"]) return False due to different length of ["1", "word"] and ["word"] tom("Qwerty1_", ["word", "12"]) return True tom("Qwerty1!", ["word", "1"]) return False because "Qwerty1!" not equals to "Qwerty1_" """ import re def create_account(user_name, password, secret_words): tempDict = {'up': 0, 'low': 0, 'dig': 0, 'spec': 0} tempDict['up'] = len(re.findall(r'[A-Z]', password)) != 0 tempDict['low'] = len(re.findall(r'[a-z]', password)) != 0 tempDict['dig'] = len(re.findall(r'\d{1}', password)) != 0 tempDict['spec'] = len(re.findall(r'[|!|@|#|$|%|^|&|*|(|)|_|+|=]', password)) != 0 for key in tempDict: if not tempDict[key]: raise ValueError def check(own_password, checklist): if own_password == password and len(checklist) == len(secret_words): temp = [] + secret_words for item in checklist: if item in temp: temp.pop(temp.index(item)) return len(temp) <= 1 else: return False return check tom = create_account("Tom", "Qwerty1_", ["1", "word"]) check1 = tom("Qwerty1_", ["1", "word"]) check2 = tom("Qwerty1_", ["word"]) check3 = tom("Qwerty1_", ["word", "2"]) check4 = tom("Qwerty1!", ["word", "12"]) print(check1,check2,check3,check4)
true
4fa8cd4350ce3c53c4c3b861463a461962633197
dkhroad/fuzzy-barnacle
/prob2/string_validator.py
2,026
4.40625
4
class StringValidator(object): '''validate a string with brackes and numbers''' def validate_brackets(self,s): ''' ensures that string s is valid :type s: str :rtype: bool valiation criteria: - the string only contains the followin characters - '{', '(',']','[',')','}' - one of more digits - all open brackets (,),{,},(,) are followed by an approriate closing bracket - open bracket must be closed in the correct order return True if the input string is valid, else false ''' if type(s) != str: # punt early if bad input return False left_brackets = ['(','{','['] right_brackets = [')','}',']'] stack = [] # import pdb; pdb.set_trace() for char in s: if char in left_brackets: stack.append(char) elif char in right_brackets: if len(stack) < 1: #if stack is empty return False if left_brackets.index(stack.pop()) != right_brackets.index(char): # stack doesn't have the correct left bracket as its top # element return False elif not char.isdigit(): return False # we are done iterating over the string. # The stack has to be empty if string contained matching brackets in # a correct order return len(stack) == 0 if __name__ == "__main__": import sys if (len(sys.argv) == 1): print("Usage: {} \'string_to_validate\'".format(sys.argv[0])); sys.exit(1) if len(sys.argv[1:]) > 0: res = StringValidator().validate_brackets(sys.argv[1]) if res: print("input \"{}\" is a valid string".format(sys.argv[1])) else: print("input \"{}\" is NOT a valid string".format(sys.argv[1]))
true
554b090af2ba3bc3040e9e9acccf883928375c9c
dariclim/python_problem_exercises
/Directions_Reduction.py
2,372
4.1875
4
""" Once upon a time, on a way through the old wild west, a man was given directions to go from one point to another. The directions were "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too. Going to one direction and coming back the opposite direction is a needless effort. Since this is the wild west, with dreadfull weather and not much water, it's important to save yourself some energy, otherwise you might die of thirst! Not all paths can be made simpler. The path ["NORTH", "WEST", "SOUTH", "EAST"] is not reducible. "NORTH" and "WEST", "WEST" and "SOUTH", "SOUTH" and "EAST" are not directly opposite of each other and can't become such. Hence the result path is itself : ["NORTH", "WEST", "SOUTH", "EAST"]. """ def dirReduc(arr): opp = { 'NORTH':'SOUTH', 'SOUTH': 'NORTH', 'WEST': 'EAST', 'EAST': 'WEST' } new = [] for i in arr: if len(new) == 0: new.append(i) else: if new[len(new)-1] == opp[i]: new.pop() else: new.append(i) return new """ for each direction in the arr: if new is empty, we add that new direction into new. Now len(new) is 1. next direction: if the element at new[0] is the opposite of the direction: we now pop that element out. pop() pops the last item, which will always be the one in question if not: add it to new, it's a completely unrelated direction! """ def dirReduc_simplified(arr): opp = { 'NORTH':'SOUTH', 'SOUTH': 'NORTH', 'WEST': 'EAST', 'EAST': 'WEST' } new = [] for i in arr: if new and new[-1] == opp[i]: # if new: True. new is empty rn, so returns False # new[-1] grabs the very last. Reads new from the right new.pop() else: new.append(i) return new def dirReduc_clever(arr): dir = " ".join(arr) dir2 = dir.replace("NORTH SOUTH",'').replace("SOUTH NORTH",'').replace("EAST WEST",'').replace("WEST EAST",'') dir3 = dir2.split() print(dir3, arr) print(dirReduc(dir3)) print(len(dir3), len(arr)) print(len(dirReduc(dir3)), len(arr)) return dirReduc(dir3) if len(dir3) < len(arr) else dir3 print(dirReduc_clever(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]))
true
8bf7fbff0e0776f7af28af9627c2ebf9dbd6a32d
sohaib-93/SOIS_Assingment
/Embedded_Linux/Part_A/prog9.py
833
4.40625
4
# !/usr/bin/python3 # Python Assignment # Program 9: Implement a python code to count a) number of characters b) numbers of words c) number of lines from an input file to output file. f = open("finput.txt", "r+") text = f.read().splitlines() lines = len(text) # length of the list = number of lines words = sum(len(line.split()) for line in text) # split each line on spaces, sum up the lengths of the lists of words characters = sum(len(line) for line in text) # sum up the length of each line print ("The number of line: ", lines) print ("The number of word: ", words) print ("The number of characters: ", characters) f1 = open("foutput.txt", "w+") f1.write("The number of line: "+str(lines)+"\n") f1.write("The number of word: "+str(words)+"\n") f1.write("The number of characters: "+str(characters)) f.close() f1.close()
true
211d6ce07287364d6800a059625419ac93e88e12
sohaib-93/SOIS_Assingment
/Embedded_Linux/Part_A/prog3.py
769
4.53125
5
# !/usr/bin/python3 # Python Assignment # Program 3: Implement a python code to find the distance between two points.(Euclidian distance) # Formula for Euclidian distance, Distance = sqrt((x2-x1)^2 + (y2-y1)^2) def edist(x1,y1,x2,y2): dist1 = (x2-x1)**2 + (y2-y1)**2 dist = dist1**0.5 return dist x1 = float(input("Please enter the x co-ordinate of point 1: ")) y1 = float(input("Please enter the y co-ordinate of point 1: ")) x2 = float(input("Please enter the x co-ordinate of point 2: ")) y2 = float(input("Please enter the y co-ordinate of point 2: ")) #p1 and p2 contain x & y co-ordinates of Point 1 and Point 2 in the form of Tuples. p1 = (x1,y1) p2 = (x2,y2) print ("The distance between Point 1", p1, "and Point 2", p2, " is:", edist(x1,y1,x2,y2))
true
7d95ce35091a63117f24f34c936b485f9af5917e
sohaib-93/SOIS_Assingment
/Embedded_Linux/Part_A/prog8.py
497
4.28125
4
# !/usr/bin/python3 # Python Assignment # Program 8: Implement a python code to solve quadratic equation. # Quadratic Equation Formula: x = b^2 + (sqrt(b^2 - 4ac) / 2a) or b^2 - (sqrt(b^2 - 4ac) / 2a) print ("ax^(2)+bx+c") a = int(input("Enter the value of a:")) b = int(input("Enter the value of b:")) c = int(input("Enter the value of c:")) den = 2*a brack1 = ((b*b) - (4*a*c))**0.5 num1 = -b + brack1 num2 = -b - brack1 x1 = num1/den x2 = num2/den print ("The solution is", x1, ",", x2)
true
b9b98dc058b1f05f3833d3af575f9cea85292539
lxwc/python_start
/if_else.py
633
4.28125
4
age = 12 if age >= 18: print('your age is',age) print('adult') else: print('your age is',age) print('teenager') if age >= 18: print('adult') elif age >= 6: #elif is else if abbreviation print('teenager') else: print('kid') height = input("Please input your height:") if int(height) >= 180: print('tall,high') elif int(height) >=170: print('normal') else : print('low,short') h = 1.75 w = 80.5 BMI = float(w/(h*h)) print('BMI=',BMI) if BMI <= 18.5: print('under weight') elif BMI<=25: print('normal') elif BMI<=28: print('over weight') elif BMI<=32: print('obesity,fat') else : print('severe obesity');
false
9d0a50a37674344e868b687f47b9f4eeef8748fe
jtwray/cs-module-project-hash-tables
/applications/crack_caesar/sortingdicts-kinda.py
2,932
4.59375
5
# Can you sort a hash table? ## No! ## the hash function puts keys at random indices ​ # Do hash tables preserve order? ## NO ## [2, 3, 4, 5] # my_arr.append(1) # my_arr.append(2) # my_arr.append(3) # [1, 2, 3] ​ # my_hash_table.put(1) # my_hash_table.put(2) # my_hash_table.put(3) ​ ## *Dictionary ### Yes ### Since Python 3.5, keys are kept in order ### does that impact the time complexity for dict over regular hash tables? ​ ### contrast JS: when looping over object items, order is not guaranteed! #### Means JS object is a little closer to a pure hash table than the Python dict is ​ ​ ## vim mode and keyboard ​ ## Even with a Python dictionary, you can't sort ### We want to print these items, by key, descending order ​ ## How could we sort the keys? d = { 'foo': 12, 'bar': 30, 'quux': 21 } ​ # use .items() and sort the tuples # Two common functions/methods for sorting in Python? ## .sort(), sorted(arr) ​ ### .items() returns a 'dict_items' object ### can use sorted(), not .sort()... ​ ## could use list comprehension ​ ## iterable: any data structure you can run a for-loop on ​ my_list = list(d.items()) my_list.sort(reverse=True) # sorts in ascending order, by default. reverse=True to descende instead my_list.sort(key=lambda tupl: tupl[1]) # sort by value instead of key. optional function argument ​ for pair in my_list: print(pair) ​ ## JS: (a, b) => a * b ## Python: lambda x, y: x * y ​ my_list.sort(reverse=True, key=lambda tupl: tupl[1]) # sort by value instead of key. optional function argument for pair in my_list: print(pair) ​ ## SICP ​ ​ ## Given a string, print the number of occurrences of each letter ​ ## Print starting with the most numerous letter, down to least numerous ​ ## Built-in method # d[letter] = letter.count() ​ string_to_count = "The quick brown fox jumps over the lazy dog" ​ ## Store letter as dict key with value of 0, each time the letter appears, increase value by 1 ### how to handle spaces? ### upper and lower case? def letter_counts(s): d = {} for letter in s: letter = letter.lower() if letter == " ": continue elif letter not in d: d[letter] = 1 else: d[letter] += 1 ​ return d ​ def print_letters(s): counts_dict = letter_counts(s) ## sort by value counts_list = list(counts_dict.items()) counts_list.sort(reverse = True, key = lambda x: x[1]) # sort by value, and in descending order ​ ## loop through and print for pair in counts_list: print(f'count: {pair[1]} letter: {pair[0]}') ​ print_letters(string_to_count) ​ ## order goes by the order that the data is input if they are the same value ​ ​ # named keywords: def my_func(first_arg, second_arg): print(first_arg) print(second_arg) ​ my_func(1, 2) my_func(second_arg=2, first_arg=1) ​ ## like kwargs
true
9bb8498290f491440011fda2ab93b2f20570d4df
petercripps/learning-python
/code/time_check.py
368
4.25
4
# Use date and time to check if within working hours. from datetime import datetime as dt start_hour = 8 end_hour = 22 def working_hours(now_hour): if start_hour < now_hour < end_hour: return True else: return False if working_hours(dt.now().hour): print("It is during work hours") else: print("It is outside work hours")
true
ea9084b8b4da109d9d364e0c7fc44f961e8ceedc
emmagordon/python-bee
/group/reverse_words_in_a_string.py
602
4.28125
4
#!/usr/bin/env python """Write a function, f, which takes a string as input and reverses the order of the words within it. The character order within the words should remain unchanged. Any punctuation should be removed. >>> f('') '' >>> f('Hello') 'Hello' >>> f('Hello EuroPython!') 'EuroPython Hello' >>> f('The cat sat on the mat.') 'mat the on sat cat The' >>> f('So? much, punctuation:') 'punctuation much So' >>> f('a santa lived as a devil at nasa') 'nasa at devil a as lived santa a' """ import doctest # TODO: REPLACE ME WITH YOUR SOLUTION if __name__ == "__main__": doctest.testmod()
true
49ce4c0bc77b3f0eca3a3f93435b108cedd1e3c8
xuanngo2001/python-examples
/is_py.py
255
4.15625
4
#!/bin/python3 obj = 1 if type(obj) == int: print("Integer") obj = 12.2312 if type(obj) == float: print("Float") obj = 12.3213 if type(obj) == int or type(obj) == float: print("It is a number") else: print("It is NOT a number")
false
8d142982d667457fcf063bef95064599a5d51fe0
Mujeeb-Shaik/Python_Assignment_DS-AIML
/13_problem.py
1,966
4.1875
4
""" You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later? Note that there are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items. Example1: Input = [10, 5, 6, 4, 8] Output = 10 Example2: Input = [10, 5, 6, 4, 9] Output = 16 """ import unittest def knapsackLight(value1, weight1, value2, weight2, maxW): """ ??? Write what needs to be done ??? """ if (maxW >= weight1+weight2): return value1+value2 elif (value1>value2 and maxW >= weight1): return value1 elif (value1<value2 and maxW >= weight2): return value2 elif (maxW >= weight1): return value1 elif (maxW >= weight1): return value1 else: return 0 # Add these test cases, and remove this placeholder # 1. Test Cases from the Examples of Problem Statement # 2. Other Simple Cases # 3. Corner/Edge Cases # 4. Large Inputs # DO NOT TOUCH THE BELOW CODE class TestknapsackLight(unittest.TestCase): def test_01(self): input_nums = [10, 5, 6, 4, 8] output_nums = 10 self.assertEqual(knapsackLight(input_nums[0],input_nums[1],input_nums[2],input_nums[3],input_nums[4]), output_nums) def test_02(self): input_nums = [10, 5, 6, 4, 9] output_nums = 16 self.assertEqual(knapsackLight(input_nums[0],input_nums[1],input_nums[2],input_nums[3],input_nums[4]), output_nums) def test_03(self): input_nums = [5, 3, 7, 4, 6] output_nums = 7 self.assertEqual(knapsackLight(input_nums[0],input_nums[1],input_nums[2],input_nums[3],input_nums[4]), output_nums) if __name__ == '__main__': unittest.main(verbosity=2)
true
c20cfc1512539c2a887b763369e0e1d64211e839
mani5348/Python
/Day3/Exits_key.py
270
4.3125
4
#write a Program to Check if a Given Key Exists in a Dictionary or Not dict1={'Manish':1,'Kartik':2,'Shubham':3,'Yash':3,'Aman':4} key=input("enter the key values what we want to check:") if key in dict1.keys(): print("Exists") else: print("Not Exists")
false
be1bb2b7b2fa490f0a1c170ad281088047576532
mani5348/Python
/Day3/Sum_Of_Values.py
288
4.25
4
#write a Program to Sum All the Items in a Dictionary n=int(input("Enter the no. of keys :")) dict1={} for i in range(1,n+1): key=input("enter key values:") value=int(input("enter the values of keys:")) dict1.update({key:value}) sum1=sum(dict1.values()) print(sum1)
true
bbd4be4c2712c6e488b9a70a809032560e1f35d9
mani5348/Python
/Day3/Bubble_sort.py
353
4.28125
4
#write a program to Find the Second Largest Number in a List Using Bubble Sort list1=[9,3,6,7,4,5,8] length=len(list1) for i in range(0,length): for j in range(0,length-i-1): if(list1[j]>list1[j+1]): temp=list1[j] list1[j]=list1[j+1] list1[j+1]=temp print("Second largest no.is:",list1[length-2])
true
287ca547d96ce97e69e1f4d78a8647cdb9b11ffc
bishalpokharel325/python7am
/sixth day to 9th day/codewithharry decorators.py
2,253
4.5
4
"""Decorators modify functionality of function.""" """1. function can be assigned into another variable which itself act as a function""" def funct1(x,y): print(x+y) funct2=funct1 funct2(5,6) """2. function lai assigned garisakexi org funct lai delete garda will funct2 also get deleted?""" def funct3(x,y): print(x-y) funct4=funct3 del funct3 funct4(2,3) """3) function lai pani return garna sakincha....... write a program to define function and input function to be executed according to input of user """ def sum(x,y): return x+y def diff(x,y): return x-y def product(x,y): return x*y def division(x,y): return x/y x=float(input("Enter frst no:")) y=float(input("Enter second no:")) userchoice=input("Enter operation you want to perform in these parameters(sum/diff/product/division):") def functionreturner(choice): if choice=="sum": return sum elif choice=="diff": return diff elif choice =="product": return product elif choice=="division": return division else: return print funct5=functionreturner(userchoice) result=funct5(x,y) print(result) """4) function lai pani argument ko rup ma lina milcha WAP to take any function as argument, print starting the function at begining and print ended after exectution of function """ def progress(function): def inner(): print("Starting of the function") function() print("End of the function") return inner def printer(): print("in progress.......") printer=progress(printer) printer() """"5) no 4 nai decorater ho this can be done in similar way before defining any function """ def progress1(function): def inner(): print("Starting no 2") function() print("ending no 2") return inner @progress1 def printer1(): print("in prgress no 2") printer1() """6) WAP to create a function which takes two values a and b and will divide largest and smallest no for decorators and normal one asewell""" def smart_divider(funct): def inner(a,b): if a<b: a,b=b,a return funct(a,b) else: return funct(a,b) return inner @smart_divider def diff2(x,y): print(x-y) diff2(2,3) diff2(3,2)
true
93ca28d208ff5af73eb00b39535a17cc97092572
mubar003/bcb_adavnced_2018
/bcb.advanced.python.2018-master/review/functions.py
727
4.25
4
''' Paul Villanueva BCBGSO 2018 Advanced Python Workshop ''' # The function below squares a number. Run this code and call it on a # couple different numbers. def square(n): return n * n # Write a function named cube that cubes the input number. # Define a function square_area that takes the width and a length of a square # and returns its area. # Define a function peek that takes a file and prints out ONLY the first line. # We will need to do something similar to this later today. # Run the code and try it on a few files. ##def peek( ... ): ## ''' ## in - a file name ## out - the first line in the file ## ''' # Modify peek so that it also prints out the length of the first line.
true
5f5163b99870b9fac1d95f483fb9b64f346e7db2
VinneyJ/alx-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
645
4.1875
4
#!/usr/bin/python3 """Contains definition of text_indentation() function""" def text_indentation(text): """Print given text with 2 new lines after '.', '?', and ':' characters. Args: text (str): Text to be formatted. """ if not isinstance(text, str): raise TypeError("text must be a string") t1 = text.strip() t2 = t1.replace(". ", ".") t3 = t2.replace(": ", ":") t4 = t3.replace("? ", "?") for c in t4: if c == '.': print(".\n") elif c == '?': print("?\n") elif c == ':': print(":\n") else: print(c, end='')
true
9443bf14f31969ad00955eacf6b01164fd37f39d
the-code-matrix/python
/unit6/practice/Unit6_Dictionaries_practice.py
1,679
4.5
4
#!/usr/bin/python # 1. Write a program to map given fruit name to its cost per pound. #Solution: item_cost={ 'banana': 0.69, 'apple' : 1.29, 'pear' : 1.99, 'grapes' : 2.49, 'cherries' : 3.99 } print("Cost of apple per lb is: ",item_cost['apple']) print("Cost of grapes per lb is: ",item_cost['grapes']) # 2. Change cost of cherries to $4.99. #Solution: item_cost={ 'banana': 0.69, 'apple' : 1.29, 'pear' : 1.99, 'grapes' : 2.49, 'cherries' : 3.99 } item_cost['cherries'] = 4.99 print("Cost of cherries per lb is: ",item_cost['cherries']) # 3. Write a python program to sum all the item's cost in a dictionary #Solution: item_cost={ 'banana': 0.69, 'apple' : 1.29, 'pear' : 1.99, 'grapes' : 2.49, 'cherries' : 3.99 } total_cost=0.0 for cost_of_each_item in item_cost.values() : total_cost += cost_of_each_item print("Total cost: ", total_cost) # 4. Display items of dictionary in sorted order by fruit name. #Solution: item_cost={ 'banana': 0.69, 'apple' : 1.29, 'pear' : 1.99, 'grapes' : 2.49, 'cherries' : 3.99 } for fruit in sorted(item_cost) : print(fruit, 'cost is ', item_cost[fruit]) #5. Write a program to map two lists into dictionary. #Solution: item_list = ['banana','apple','pear','grapes','cherries'] cost_list = [0.89, 2.19, 1.69, 2.79, 2.99] # solution 1 item_cost = {} for index in range(len(item_list)) : item_cost[item_list[index]] = cost_list[index] print(item_cost) # solution 2 item_cost = dict(zip(item_list, cost_list)) print(item_cost)
true
8aef5e8d21ab0f028466b88aa7c7c24ed85b5501
the-code-matrix/python
/unit1/practice/echo.py
320
4.5625
5
# Create a program that prompts the # user to enter a message and echoes # the message back (by printing it). # Your program should do this 3 times. message_1 = input("Enter message 1: ") print(message_1) message_2 = input("Enter message 2: ") print(message_2) message_3 = input("Enter message 3: ") print(message_3)
true
5a3eb2642017b2adf55a16bd1aa2d939ea65c3f3
raptogit/python_simplified
/Programs/06_operators.py
1,196
4.46875
4
# #Arithmetic Operators :: a=5 #Addition operator b=3 c=a+b print(c) s=8-5 #Substraction operator print(s) print(9*2) #Multiplication Operator print(6/3) #division Operator print(13%3) #Modulus operator print(2**5) #Exponentiation 2*2*2*2*2 print(12//4) #Floor division operator # Comparison Operators :: print(2==4) #Equal to operator print(3!=2) #Not Equal to operator print(15>4) #Greater than operator print(3<5) #Less than operator print(14>=14) #Greater than equal to operator print(14<=12) #LEss than equal to operator #Identity operators :: x=["Apple","Banana"] #Is operator y=["Apple","Banana"] z=x print(x is z) print(x is y) print(x==z) print(x is not z) #Is not operator print(x is not y) print(x!=z) #Python Membership Operators :: print("Banana" in x) #in operator print("Pineapple"not in y) #not in
true
de9529d4f66915a08b636c0c112185a455119c9d
jabc1/ProgramLearning
/python/python-Michael/ErrorPdbTest/debug.py
2,448
4.25
4
# -*- coding: utf-8 -*- # 调试 # 1.简单粗暴:print()把可能有问题的变量打印出来 def fn(s): n = int(s) print('>>> n = %d' % n) return 10 / n def main(): fn('0') main() # 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息 # 2.断言(assert) # 用断言(assert)替代print()辅助查看的地方 def fn(s): n = int(s) assert n != 0, 'n is zero!' return 10 / n def main(): fn('0') # assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错 # 如果断言失败,assert语句本身抛出异常AssertionError # 启动Python解释器时可以用-O参数来关闭assert:把所有的assert语句当成pass来看 $ python3 -O err.py # 调用方法 # 3.logging # 把print()替换为logging,logging不会抛出错误,而且可以输出到文件 import logging logging.basicConfig(level = logging.INFO) # 配置后,才有具体错误信息 s = '0' n = int(s) logging.info('n = %d' % n) print(10 / n) # logging.info()就可以输出一段文本 # logging 记录信息的级别: debug,info,warning,error等 # 指定level=INFO时,logging.debug就不起作用了。同理,指定level=WARNING后,debug和info就不起作用 # logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件 # 4.pdb :Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态 # debug.py s = '0' n = int(s) print(10 / n) $python3 -m pdb pdbmanule.py # 启动调试 # 以参数-m pdb启动后,pdb定位到下一步要执行的代码-> s = '0' # 命令l : 查看代码 # 命令n : 单步执行代码 # 命令 p + 变量名 : 来查看变量 # 命令q : 结束调试,退出程序 # 命令c :继续执行 # 5.pdb.set_trace() # 不需要单步执行,只需要import pdb,然后,在可能出错的地方放一个pdb.set_trace(),就可以设置一个断点: # debug.py import pdb s = '0' n = int(s) pdb.set_trace() # 运行到此处,会自动暂停 print(10 / n) # 运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行: # 6.IDE # 图形界面比较容易设置断点、单步执行等操作 PyCharm ## 虽然用IDE调试起来比较方便,logging才是终极武器
false
dbc534f073b45146d9be6f04d243320051cad014
jabc1/ProgramLearning
/python/python-Michael/functionProgramming/higherfunction.py
1,469
4.125
4
# 函数式编程 #函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用 #允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。 # 函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数! #Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。 # 高阶函数英文叫Higher-order function abs(-10) #abs(-10)是函数调用,而abs是函数本身 f = abs #变量可以指向函数 f(-10) abs = 10 #函数名也是变量 #注:由于abs函数实际上是定义在__builtin__模块中的,所以要让修改abs变量的指向在其它模块也生效,要用__builtin__.abs = 10。 # 使用 del abs 也能恢复 abs 的使用 #传入函数 #一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数: def add(x, y, f): return f(x) + f(y) add(-5, 6, abs) #调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs 结果:11 #把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
false
8f931bb230cddf47e94a2cf3be03a41501ae6090
aash-beg/CoderApprentice
/Exercises/Chapter 01-09/Ex 5.3.py
318
4.28125
4
num1 = float(input('1st number: ')) num2 = float(input('2nd number: ')) num3 = float(input('3rd number: ')) large = max(num1, num2, num3) small = min(num1, num2, num3) avg = (num1 + num2 + num3)/3 print('Largest number is {0}\n' 'Smallest number is {1}\n' 'Average is {2:.2f}'.format(large, small, avg))
false