blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
049adad573f0b50f2e86b522a8f347f8a8816d5d
dubeyalok7/problems
/python/exception.py
876
4.125
4
#!/usr/bin/python def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78)) #print KelvinToFahrenheit(-5) try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close() try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data\n" try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can\'t find file or read data"
true
9a70eb3c0f682b08089fcf39d2ba235c5cbf4d94
dIronmanb/DLstudy
/backward_layer.py
1,135
4.15625
4
#역전파(backward propagation) """ 참고로, 지금까지 구현했던 신경망은 순전파(forward propagation)였다. 역전파를 통해 '미분'을 효율적으로 계산할 수 있다. 역전파로 흘러갈 때는 국소적 미분(편미분)을 곱하고 다음 노드로 전달한다. """ class MulLayer: #곱 역전파 (z = xy) def __init__(self): #생성자 - 멤버변수 선언 self.x = None self.y = None def forward(self, x, y): self.x = x self.y = y out = x * y return out def backward(self, dout): #역전파: x,y와 같이 뒤바뀐다. dx = dout*self.y #미분 dx dy = dout*self.x #미분 dy return dx, dy class AddLayer: #합 연산자 (z = x+y) def __init__(self): self.x = None self.y = None def forward(self, x, y): self.x = x self.y = y out = x + y return out def backward(self, dout): #역전파: 각각 편미분을 하면 1이 나온다. dx = dout * 1 dy = dout * 1 return dx, dy
false
92d5b9d0c5987e99af240c86f477d665f99eae83
andrewhvo/PLCExam
/Code/Question_1/test2q1.py
1,805
4.15625
4
import os import sys import re # Parses text file into an empty list r f = open("question1.txt", "r") r = f.read() # converts the list of lists into a lists of strings as list_String list_String = [] list_String = r.split( ) # iterates through the list of strings and assigns a token to every valid string for i in list_String: # Uses regex to find any string that starts with @, $, or % if(re.fullmatch("^(@|\$|%)[a-zA-Z0-9]+_?[a-zA-Z0-9]+", i)): print(i + ": " + "Pearl") # Uses regex to find any string that is within quotations elif(re.fullmatch("^(\").*(\"$)", i)): print(i + ": " + "String") # Uses regex to find just numbers with a minimum of 1 digit char elif(re.fullmatch("[1-9][0-9]*", i)): print(i + ": " + "Decimal") # Uses regex to find numbers starting with 0 and digit chars consisting of 1-7 elif(re.fullmatch("0[0-7]*", i)): print(i + ": " + "Octal") # Uses regex to find a number starting with 0x and ending with an optional suffix elif(re.fullmatch("0[xX][0-9a-fA-F]*", i)): print(i + ": " + "C-Style integer literal hex") # Finds any floating point with optional prefix, minimum of 1 digit and followed by a exponent elif(re.fullmatch("[-+]?([0-9]*[.])?[0-9]+([eE][-+]?\d+)?", i)): print(i + ": " + "C-Style float literal") # Finds any string starting with a alpha, followed by optional underscore. elif(re.fullmatch("[a-zA-Z_][a-zA-Z_0-9]*", i)): print(i + ": " + "C-Style character literal") # Finds any non-alphanumberic char that was listed in the question elif(re.fullmatch("([+]|[=]|[\==]|[-]|[\]|[\\]|[\/]|[*]|[++]|[--]|[%]|[&&]|[||]|[!=]|[(]|[)]|[{]|[}])*", i)): print(i + ": " + "Non-Alphanumeric") else: print(i + ": " + "Invalid")
true
c258eee50d831833b158d4b0775dfc96a30c30e8
longbefer/python_learn
/11_lambda.py
764
4.125
4
# 函数形式 def ds(x): return 2*x + 1 print(ds(5)) # lambda形式 # lambda x : 2 * x + 1 g = lambda x : 2 * x + 1 print(g(5)) g = lambda x,y : x + y print(g(5, 9)) # lambda代码简洁,可读性强 # lambda使用的例子 -- filter print(list(filter(None, [1, 0, True, False, 9, 0, 1]))) # filter(None, []) -- 为None时过滤掉非True的值 f = lambda x : x % 2 == 0 # 判断是否为偶数 (直接 x % 2 就行) print(list(filter(f, [3, 6, 9, 8, 12]))) # 调用过滤器 # map -- 映射 迭代器内容通过前面的函数映射成为一个新的函数 f = lambda x, y : x + y print(list(map(f, [1, 2, 4, 5], [3, 4, 5, 11]))) # 两个list相加(取最短的) f = lambda x : x ** 2 # x的2次幂 print(list(map(f, [3, 6, 9, 12, 13])))
false
b91191ecec2aea74c6a892e4ef78e097477844d0
longbefer/python_learn
/8_string.py
1,224
4.46875
4
# 字符串python 2和 python 3 有所不同 # 字符串也是不可修改的 # 同元组,只能新建了一个修改 str1 = "i love you" print(str1) str1 = str1[:1] + " not" + str1[1:] print(str1) # 首字母大写 str1.capitalize() # 小写以及很多没用的小秘密函数 str1.center(10) str1.casefold() str1.endswith('si') # 已 si 结束 str1.expandtabs() # 空格加Tab str1.find('s') str1.index('l') # 同find,但是找不到就自爆了 str1.replace('l', 'k') str1.split(' ') # 去除所有空格 # 自行查询吧。。。 # 字符的格式化 print("{0} is {1} and {2} is also".format("i", "pig", "me")) print("{a} is {b} and {c} is also".format(a="i", b="pig", c="me")) print("{0:.1f}{1}".format(27.094, "GB")) # 0后面的:属于格式化工具,.1f表示保留1位小鼠 # %c 格式化字符及其ASCII码 print('%c' % 97) print('%c, %c, %c' % (97, 98, 99)) # 注意要使用元组 # %s 格式化字符串 print("%s" % "i is pig") # %o 8进制 # %x 16进制 %X # %f 定点数,指定精度 # %e 科学计数法 %E # %g 根据值的大小决定使用 %f 或 %e %G # 格式化辅助命令 # 见视频吧。。。 # https://www.bilibili.com/video/BV1xs411Q799?p=16
false
68a17b1eb28defdf7bbd9e0546cdd11e013c57be
christengarcia/tut10
/tut10.py
1,578
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Function to calculate multiple order totals and apply any applicable discount """ # Stock prices price = {'book': 10.0, 'magazine': 5.5, 'newspaper': 2.0} # Separate orders order1 = {'book': 10} order2 = {'book': 1, 'magazine': 3} order3 = {'magazine': 5, 'book': 10} # Calculate total price on orders # Add discount to orders if applicable def calculate_price(price, order): order_basket = [] for key, value in price.items(): # Raise KeyError if item does not have a price if price[key] < 0: raise KeyError('item in order does not have price value') # Check if item has a match in stock if key in order: gross = float(price[key]) * float(order[key]) order_basket.append(gross) # Sum total on each iteration gross_total = 0 for sub_total in order_basket: gross_total = gross_total + sub_total # Add discount if applicable if gross_total > 100.00: discount = gross_total * 10 / 100 discounted_price = gross_total - discount return discounted_price elif gross_total > 50.00: discount = gross_total * 5 / 100 discounted_price = gross_total - discount return discounted_price else: return gross_total # Verify calculations are correct assert(95 == calculate_price(price, order1)) assert(26.5 == calculate_price(price, order2)) assert(114.75 == calculate_price(price, order3)) print("Done")
true
3f6a0a6c62eb99ee002ea76900081dd6906e64fb
DongXiangzhi/working
/NewMagic.py
368
4.21875
4
birthday={'Jeremiah':'Apr 1' ,'Salome':'Dec 12' ,'Nehemiah':'Mar 4'} while True: print('Enter a name:(空退出)') name=input() if name=='': break if name in birthday: print(birthday[name] + ' is the birthday of ' + name) else: print("没有生日:"+name) print('What is their birthday?')
false
c48dc599b9ea0e7a99d2c02dd419e9abc5c599af
AlyssaYelle/python_practice
/software_design/misc/binary_maths.py
1,700
4.3125
4
''' (PYTHON 3) This program acts as a calculator that can only use the {+ - * /} operators so we have to use binary search to find the nth root of a number. Saving so I can add functionality to it as I get more free time ''' class ImproperMathTimeError(Exception): def __init__(self,value): self.value = value class ImproperMathTypeError(Exception): def __init__(self, value): self.value = value class ImproperValues(Exception): def __init__(self, value): self.value = value def which_math(): math_type = str(raw_input('Please select the type of math problem you want to solve:\nnth root\nlogn\n')) if math_type != 'nth root': raise ImproperMathTypeError('Not an accepted math type') else: do_math(math_type) def do_math(math_type): if math_type == 'nth root': num = float(raw_input('Select a positive number to compute the nth root of: ')) n = int(raw_input('Now choose an n: ')) hi = num lo = 1 nth_root(num, n, hi, lo) else: # will probably add more math types pass def nth_root(num,n,hi,lo): epsilon = .00000001 mid = float((hi+lo)/2) value = mid root = n while root > 1: value = value*mid root -= 1 if (abs(value - num) < epsilon): print 'The answer is', mid else: if value < num: lo = mid return nth_root(num, n, hi, lo) if value > num: hi = mid return nth_root(num, n, hi, lo) def main(): math_time = raw_input('Would you like to solve a math problem? (y/n)\n') if math_time == 'n' or math_time == 'N': print 'Okay, bye!' elif math_time == 'y' or math_time== 'Y': which_math() else: raise ImproperMathTimeError('Accepted values are: y or n') if __name__ == '__main__': main()
true
584ac7483e73949b29f28f4539375774041a2134
John-L-Jones-IV/6.0001
/ps1/ps1c.py
1,895
4.46875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @title: ps1c.py @author: John Lewis Jones IV @date: 15AUG2019 MIT OCW 6.0001 Introduction to Computer Science and Programing in Python A simple program to calculate how much needs to be saved per month in order to reach a savings goal """ starting_salary = int(input('Enter the starting salary: ')) semi_anual_raise = 0.07 # 7% pay raise every six months r = 0.04 # montly roi on saved investments down_payment_amount = 1000000.0*0.25 min_rate = 0 max_rate = 10000 search_cnt = 0 # make sure it is possible to save for the down payment if (3*starting_salary < down_payment_amount): worth_while = False print('It is not possible to pay the down payment in three years.') else: worth_while = True # if possible and until we have found the correct savings percent while worth_while: search_cnt += 1 # incriment search counter guess = (min_rate + max_rate) // 2 # strategically guess center of possible range percent_saved = guess/10000.0 # float conversion # reset to post-graduation condidtions current_savings = 0.00 anual_salary = starting_salary # simulate 36 months for month in range(1,37): # 1-36 months monthly_salary_saved = anual_salary/12*percent_saved current_savings += monthly_salary_saved + current_savings*r/12 if (month % 6 == 0): # every 6 months after starting anual_salary *= 1+semi_anual_raise # evaluate the 36 months if (min_rate == max_rate): print('resolution too course in bisection search...') break elif current_savings > down_payment_amount + 100: max_rate = guess elif current_savings < down_payment_amount - 100: min_rate = guess else: print('Best savings rate:', percent_saved) print('Steps in bisection search:', search_cnt) break
true
f283f74a23aad41470dbbcf42186972656404c0c
sichkar-valentyn/Find_all_unique_words_from_the_file_and_calculate_frequency
/Unique_words_in_the_file.py
1,881
4.375
4
# File: Find_all_unique_words_from_the_file_and_calculate_frequency.py # Description: Find all unique words from the file and calculate frequency # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Find all unique words from the file and calculate frequency // GitHub platform [Electronic resource]. URL: https://github.com/sichkar-valentyn/Find_all_unique_words_from_the_file_and_calculate_frequency (date of access: XX.XX.XXXX) # Implementing the task - find the all unique words from the file and show their numbers of meeting in it # Showing the result in order it occured in the initial string # Reading the file and putting datato the string string = '' with open('dataset_50_12.txt') as inf: for line in inf: string += line.strip() string += ' ' # It is important to use split() in order to write the words in the string as separate elements but not the letters string_check = string.split() # Extra string for checking string = string.split() print(string) # Checking if the string was created properly # Creating a set and writing in it the string # The repeated elements will not be written s = set(string) # Creating the set with elements from the string but it will not add repeated elements print(s) # Checking if the set was created properly # Going through the elements of the set and creating the dictionary with frequency d = {} for x in s: d[x] = string.count(x) # Showing the result in order it occured in the initial string print(len(s)) # The number of unique elements for i in range(len(string)): if string[i] != ' ': print(string[i], d[string[i]]) for j in range(i, len(string)): if string[j] == string_check[i]: string[j] = ' '
true
646f75e7601e15e74a09c4aab0fc9b9168180112
sylvaus/presentations
/python/code/nice_features/2_strings.py
1,617
4.21875
4
if __name__ == '__main__': # Useful commands # Splitting csv_elements = "a,b,c,d" elements = csv_elements.split(",") print("The elements of", csv_elements, "are:", elements) # Substitution (replacing) text_with_typo = "This is corrrext" text_corrected = text_with_typo.replace("corrrext", "correct") print("Before:", text_with_typo, ", after:", text_corrected) # Checks if sub_string in string sub_string = "abc" string = "1abcdef" print(sub_string, "is in", string, ":", sub_string in string) # Checks if string starts/ends with sub_string sub_string = "abc" string = "abcdef" print(string, "starts with", sub_string, ":", string.startswith(sub_string)) print(string, "ends with", sub_string, ":", string.endswith(sub_string)) # Formatting text print("Today, I learnt about {} version {}.{}".format("Python", 3, "X")) # Removing the leading and trailing whitespace and \n string = " a lot of space before and after " print("Text will be stripped of its leading and trailing space") print("START{}END".format(string.strip())) # Comparison string = "abS" string2 = "ABS" print(string, "equals to", string2, ":", string == string2) # Python 3 print(string, "equals to", string2, "if the case is ignored:", string.casefold() == string2.casefold()) # Python 2 print(string, "equals to", string2, "if the case is ignored:", string.lower() == string2.lower()) # Concatenate strings groceries = ["milk", "bread", "toasts"] print("I need " + " and ".join(groceries))
true
c4c054f44f09a2b998d5cfbe1eef48875911953d
AbdulGhafar666/Python.
/assignment 4..py
2,371
4.4375
4
#Create a function: def my_fellows(): print("Hi") print("How are you") my_fellows() #Call a function: def my_fellows(): print("Hi") print("How are you") my_fellows() #Arguments in functions: def my_fellows(fname): print(fname + " " + "is my fellow") my_fellows("sheraz") my_fellows("Ali") my_fellows("Amir") #Number of Arguments: def my_fellows(fname,lname): print(fname+" "+lname) my_fellows("Sheraz","Rana") my_fellows("Ali","Sharjeel") my_fellows("Amir","nawaz") #pass two arguments and get 1 argument: def my_fellows(fname,lname): print(fname+" "+lname) my_fellows("Sheraz","Rana")# if we get 1or3 arguments in function . then error will be occure. #Arbitrary Arguments, *args: def my_fellows(*fellows): print("my class fellows is="+ " "+ fellows[1]) my_fellows("Sheraz","Ali","Amir") #Keyword Arguments: def my_fellows( fellow1,fellow2,fellow3 ): print("my best fellow is"+fellows[3]) my_fellows(fellow1= "Sheraz", fellow2= "Ali" , fellow3= "Amir") #By passing the Arbitrary Keyword Arguments, **kwargs: def my_friends(**friends): print("Hes last name is " + friends["lname"]) my_friends(fname = "Amir", lname ="Nawaz") #By passing Default Parameter Value: def my_function(country = "Pakistan"): print("I am from " + country) my_function("Sweden") my_function() my_function("india") my_function("pakistan") #By Passing a List as an Argument: def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "grapes","orange"] my_function(fruits) #Return Values: def my_function(x): return 4 * x print(my_function(56)) print(my_function(76)) print(my_function(9)) #The pass Statement: def my_function(): pass # having an empty function definition like this, would raise an error without the pass statement # Recursive FUNCTION: def tri_recursion(j): if(j > 0): result = j + tri_recursion(j - 1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6) # Methods class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc() #Modify Object Properties p1.age = 40 print(p1.age)
false
90880cc4640ba5edce8736215399ace605816bdc
rkenmi/algorithms
/search/int_sq_root.py
559
4.375
4
def int_square_root(n): """ Given an integer n, find the integer square root. i.e. int_square_root(64) => 8, int_square_root(69) => 8, int_square_root(81) => 9 :param n: positive Integer :return: Integer square root """ # left represents minimum interval, right represents max interval. Similar to binary search. left, right = 0, n while left <= right: mid = (left + right) // 2 if mid ** 2 <= n: left = mid + 1 else: # mid ** 2 > n right = mid - 1 return left - 1
true
ef0d005410532ec590b2af5bcc21f6514eefd6c1
siddharththakur26/data-science
/Core/Languages/python/Algorithm/symmetricDiff.py
1,156
4.40625
4
''' Create a function that takes two or more arrays and returns an array of the symmetric difference (△ or ⊕) of the provided arrays. Given two sets (for example set A = {1, 2, 3} and set B = {2, 3, 4}), the mathematical term "symmetric difference" of two sets is the set of elements which are in either of the two sets, but not in both (A △ B = C = {1, 4}). For every additional symmetric difference you take (say on a set D = {2, 3}), you should get the set with elements which are in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} = {1, 2, 3, 4}). The resulting array must contain only unique values (no duplicates). ''' arr = [[1, 2, 3], [5, 2, 1, 4, 5]] #arr=[[1, 2, 3], [5, 2, 1, 4]] list1=list2=result=[] def sd_array(a,b): num = set() for k in a: if k not in b: num.add(k) for k in b: if k not in a: num.add(k) return num for i in range(0,len(arr)-1): if i != len(arr)-1 and len(result) == 0: list1=arr[i] list2=arr[i+1] else: list1 = result list2=arr[i+1] result = sd_array(list1,list2) print(result)
true
dd203a3f298b86e340b3a177ab6b354e8f7ed4a9
siddharththakur26/data-science
/Core/Languages/python/Algorithm/search_algorithms/exponential.py
1,080
4.1875
4
''' The Interpolation Search interpolation search may go to different locations according to the value of the key being searched. For example, if the value of the key is closer to the last element, interpolation search is likely to start search toward the end side. ''' arr = [10, 12, 13, 16, 18, 19, 20, 21,22, 23, 24, 33, 35, 42, 47] size = len(arr) element = 20 def search(arr,size,element): start_index = 0 last_index = size-1 while last_index>=start_index and element>=arr[start_index] and element<=arr[last_index]: if start_index == last_index: if arr[start_index] == element: return start_index return None position = int(start_index + ((element - arr[start_index]) * (last_index-start_index) / (arr[last_index]-arr[start_index]))) if arr[position] == element: return position if arr[position] < element: start_index +=1 else: last_index -=1 return None print(search(arr,size,element))
true
49151d2f6ab79408ff5f31f417f0261374d79b61
pkblanks/MyPythonProgram
/Documents/MyPythonPrograms/my1stcalculator.py
1,350
4.125
4
# Defining Functions name = raw_input("Hello, What is your name?") print "welcome %s" %name, "Enjoy Using!!" def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def devide(x, y): return x / y # Take input from the user print("select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = raw_input("Enter Choice (1/2/3/4):") num1 = int(raw_input("Enter first number: ")) num2 = int(raw_input("Enter second number: ")) if choice == "1": print(num1, "+",num2, "=", add(num1,num2)) elif choice == "2": print(num1, "-", num2, "=", subtract(num1,num2)) elif choice == "3": print(num1, "*",num2,"=", multiply(num1,num2)) elif choice == "4": print(num1,"/", num2,"=", divide(num1,num2)) else: print("Read the rules, Massa!") # import operatorModule # operator_module.add(3, 2) # from operator_module import add # #Luis 22 # print("SIMPLE CALCULATOR! ") # print('Please enter an integer value:') # x = input() # print('Please enter another integer value:') # y = input() # num1 = int(x) # num2 = int(y) # print(num1, '+', num2, '=', num1 + num2) # print(num1, '*', num2, '=', num1 * num2) # print(num1, '/', num2, '=', num1 / num2) # print(num1, '-', num2, '=', num1 - num2)
false
3fa8caf452711ac89fe075de4b9c98899fd55058
digikar99/iitb-cs251-2018-CodeWarriors
/170050018-170050088-170100091-outlab4/P1/prime.py
1,598
4.3125
4
#!/usr/bin/python3 # Reference: https://docs.python.org/3/library/argparse.html # https://docs.python.org/3/howto/argparse.html#id1 import argparse import math parser = argparse.ArgumentParser() parser.add_argument('--check_prime') parser.add_argument('--range', nargs=2) args = parser.parse_args() def checkPrime(n): '''Returns True if n is Prime''' n=int(n) if (n==1): return False # print('n=',n) sqrt_n = math.ceil(math.sqrt(n)); for i in range(2,sqrt_n+1): if n%i==0: return False return True def nPrimesInRange(start,end): ''' Return the number of primes from start to end (both inclusive) ''' count = 0 for i in range(start,end+1): if checkPrime(i): count += 1 return count arg_list = [] if args.check_prime: arg_list.append(int(args.check_prime)) if args.range: arg_list.append( int(parser.parse_args().range[0])) arg_list.append( int(parser.parse_args().range[1])) if (not args.check_prime) and (not args.range): print('At least one of the following arguments are required: --check_prime, --range') exit(0) for arg in arg_list: if (arg < 1 or 1000 < arg): print('Error : Please enter a value between 1 and 1000 only') exit(0) if args.check_prime: if checkPrime(args.check_prime): print('Yes',end=' ') else: print('No', end=' ') if args.range: ini = int(parser.parse_args().range[0]) fin = int(parser.parse_args().range[1]) print(nPrimesInRange(ini,fin), end=' ') print()
true
c6ddd7c73d474849d5867222c4cff8bfa0929f87
cangyunye/OriOfEvery
/TurtlePaint/fractal_tree.py
1,390
4.34375
4
""" 功能:递归函数绘制分形树 日期:2017年12月12日 """ import random import turtle def colorful(): cl = ('red','orange','yellow','green','blue','purple','pink','violet','grey','gold','darkblue') return cl[random.randrange(11)] def draw_branch(branch_length): """ 分形树绘制 """ if branch_length >= 15: turtle.color('orange') #绘制中央树枝 turtle.forward(branch_length) #绘制右侧树枝 turtle.right(20) draw_branch(branch_length*0.8) #绘制左侧树枝 turtle.left(40) draw_branch(branch_length*0.8) #返回中央树枝 turtle.penup() turtle.right(20) turtle.backward(branch_length) turtle.pendown() elif branch_length >= 10 and branch_length < 15: turtle.color('green') #绘制中央树枝 turtle.forward(branch_length) #绘制右侧树枝 turtle.right(20) draw_branch(branch_length*0.8) #绘制左侧树枝 turtle.left(40) draw_branch(branch_length*0.8) #返回中央树枝 turtle.penup() turtle.right(20) turtle.backward(branch_length) turtle.pendown() def main(): turtle.left(90) turtle.pensize(3) draw_branch(40) turtle.exitonclick() if __name__ == '__main__': main()
false
7f0338b6dd1c554502ee779a5f735e55b9db9a33
bruno-novo-it/the-python-mega-course
/python_basics/verify_string_length.py
528
4.25
4
import sys # If we don't use the input function(always give string) and we # need to avoid Int value Types def string_length(mystring): if type(mystring) == int: return "Sorry, integers don't have length" elif type(mystring) == float: return "Sorry, float types don't have length" else: return len(mystring) # def string_length(mystring): # return len(mystring) user_input = input("\nDigite uma palavra: ") print("\nA palavra contém {} letras!\n".format(string_length(user_input)))
true
19c6336bea2458e905a127f82558d7557eceefd5
hbondalo/FinalProject17
/day08.py
795
4.28125
4
def say_hello(): """Prints hello""" print("hello") # Print hello say_hello() def fifty(): """Returns 50""" return 50 # Should print 100 print(fifty() * 2) def add_them_all(n1, n2, n3, n4, n5): """Returns sum of five numbers""" #insert code in here to return the sum of all 5 arguments return 1+3+5+2+100 # Should print 111 print(add_them_all(1, 3, 5, 2, 100)) # Import math to get square root function from math import sqrt # Define sidees a and b a = 5 b = 12 # Define function to find hypotenuse using sides a and b def find_hypotenuse(): """returns the hypotenuse of a triangle with sides a and b""" return sqrt(a**2+b**2) # Print hypotenuse as an integer instead of a float print(int(find_hypotenuse()))
true
d178779913c3777cf564b5f93cf7897249c6cdea
gordonaiken/MCOMD0PRC
/Week 1.py
650
4.125
4
# Hello World print("Hello, World!") # Second Program name = input("What is your name?") print ("Hello " + name) print ("What are we going to learn today") table = int(input("Which times table? ")) if table < 13: for i in range(1,13): print (str(i) + " times " + str(table) + " is " + str(table*i)) else: print("This is too hard for today") # Tip Calculator import math total = float(input("What is the bill (in £)? ")) numPayers = int(input("How many are paying? ")) approx_tip = total /100 * 10 ind_contrib = approx_tip / numPayers ind_tip = math.floor(ind_contrib + 0.5) print ("Each person should tip £"+ str(ind_tip))
false
c808b0b4aeab351f331d448887b7d1163ed2fca9
Jack-Etheredge/Project_Euler_Solutions
/project_euler_problem_1.py
419
4.3125
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. def findmultiplessum (lower, upper): sumval=0 for i in range (lower, upper): if i%3==0 or i%5==0: sumval+=i return(sumval) print(sumval) lower = 1 upper = 1000 sumval=findmultiplessum(lower,upper) print(sumval)
true
4c0c9adb5f397288086f5493b4ea9f54924ac986
Guillermocala/Py_stuff
/practice/Regex.py
1,559
4.21875
4
import re ejemplo1 = re.compile("[a-z]") cadena1 = "ejemplo1" print(f"""\tREGEX FUNCTIONS RE: {ejemplo1} string: {cadena1} """) """match() determine if the RE matches at the beginning of the string""" print("function match() :", ejemplo1.match(cadena1)) """search() sacan through a string looking for any location where the RE matches""" print("function search() : ", ejemplo1.search(cadena1)) """findall() find all substrings where the RE matches, and returns them as a list""" print("function findall() : ", ejemplo1.findall(cadena1)) """finditer() find all substrings where the RE matches and returns them as an iterator""" example_iterator = ejemplo1.finditer(cadena1) print("function finditer() : ", example_iterator) print("iterator:") for item in example_iterator: print(item) ejemplo2 = re.compile("[a-z]+") cadena2 = "esto,es.el{{ejemplo[2" print(f"""\tEJEMPLO2 RE: {ejemplo2} string: {cadena2} """) """group() return the string matched by RE start() return the starting position of the match end() return the ending position of the match span() return a tuple containing the (start, end) positions of the match """ match_group = ejemplo2.match(cadena2) print("group match: ", match_group.group()) print("start match: ", match_group.start()) print("end match: ", match_group.end()) print("span match: ", match_group.span()) print("function findall():", ejemplo2.findall(cadena2)) example_iterator2 = ejemplo2.finditer(cadena2) print("function finditer() : ", example_iterator2) print("iterator:") for item in example_iterator2: print(item)
true
ff248ed34b0d80a5b8855c0187e9c1968340ac69
Swapnali29/sm_python_tasks
/sm10.py
620
4.5625
5
# Task 10 # Assuming that we have some email addresses in the "username@companyname.com" format, # please write program to print the company name of a given email address. Both user names and company names are composed of letters only. # Example: # If the following email address is given as input to the program: # akita@securitybrigade.com # Then, the output of the program should be: # securitybrigade # In case of input data being supplied to the question, it should be assumed to be a console input. import re emailAddress = input() pat2 = "(\w+)@((\w+)+(.com))" r2 = re.match(pat2,emailAddress) print (r2.group(3))
true
b5039f63ddf5a0235e0fecd853c0c088c19248c8
Jeydin/python_basics_labs_1-3
/lab01.py
600
4.125
4
print("Jeydin Pham\t\tSeptember 13, 2021") # Print alternating lines of plus signs and equal signs # Here's a row of pluses print("+++++++++++++++++++++++++") # Now finish the program print("+++++++++++++++++++++++++") print("+++++++++++++++++++++++++") print("=========================") print("=========================") print("+++++++++++++++++++++++++") print("+++++++++++++++++++++++++") print("+++++++++++++++++++++++++") print("=========================") print("=========================") print("+++++++++++++++++++++++++") print("+++++++++++++++++++++++++") print("+++++++++++++++++++++++++")
true
1f5027f52f10515547179959cfcb2b5c08e34af4
emilyzzz/gdi-intro-python
/change_counter.py
1,470
4.4375
4
""" Practice for Lecture 1: 1. create python file change_counter.py from terminal or in PyCharm 2. use 'input()' function to prompt user to input how many quarters, example on python shell: 3. Write code in a text editor, prompt users to input number of: quarters, dimes, nickels, pennies, and save the four numbers in four variables 4. Run code from terminal: python3 change_counter.py 5. Calculate the total amount we have in cents, using arithmetic operators like: +, * 6. Print to screen: "Total amount of money is: xxx cents", please use old style string formatting 7. Print to screen: "Total amount of money is: x.xx dollars", keep 2 decimal places, using old style formatting """ # 'input' built-in function will return string type of number, for example '100', # to get the 'int' type, use 'eval' built-in function, that converts string -> number (int or float) quarters = input('Please input how many quarters: ') quarters = eval(quarters) # having 2 functions (eval, input) on same line, is equivalent as in separate lines above dimes = eval(input('Please input how many dimes: ')) nickels = eval(input('Please input how many nickels: ')) pennies = eval(input('Please input how many pennies: ')) total = quarters * 25 + dimes * 10 + nickels * 5 + pennies * 1 # old style python string formatting print('Total amount of money is: %s cents' % total) # new style python string formatting print('Total amount of money is: {} dollars'.format(total/100))
true
b7c83e0f1541b647715bb457e96a2d775d9d6a54
emilyzzz/gdi-intro-python
/dict_word_count.py
1,975
4.125
4
def pre_process(text): """ this function takes input of a string, return a list of lowercase words with punctuation removed """ # convert all letters to lower case text = text.lower() # replace each punctuation character with a space, use str.replace() or str.strip() methods for ch in '!"#$%&()*+,-./:;<=>?@[3\\]^_\'{|}~': text = text.replace(ch, " ") # convert a string to list of words, plural 'words' implies a list words = text.split() return words def word_count1(words): # check if a word is in the counts first. Returns dict of {word: count_of_word} counts = {} for w in words: if w in counts: counts[w] += 1 # same as: counts[w] = counts[w] + 1 else: counts[w] = 1 return counts def word_count2(words): # use dict.get() method. Returns dict of {word: count_of_word} counts = {} for w in words: counts[w] = counts.get(w, 0) + 1 # if w exists in dict, get the value, if not, get 0 return counts def print_dict(counts): """ print the dict using 'i' and 'max_rows' below is to control we only print 10 lines, instead of many lines for large doc note what gets printed may not be same words each time, since dict is unordered """ i = 0 max_rows = 10 for k, v in counts.items(): print('\tWord: {0:15s} Count: {1:>3}'.format(k+",", v)) # new style formatting with alignment control. ">": align right i += 1 if i == max_rows: break # 'break' will get out of a loop when "if condition" returns True def main(): f = open('zen_of_python.txt', 'r') text = f.read() words = pre_process(text) print('\nPrint Dict using counts from word_count1...') print_dict(word_count1(words)) print('\nPrint Dict using counts from word_count2...') print_dict(word_count2(words)) main()
true
9f455c030217b876fb2f5e418be2f7aff21915eb
Samyak006/samyak_006
/star.py
748
4.125
4
x=int(input("insert the number of rows")) s=x-1 for rows in range(0,x): s=x-rows-1 for emp in range(s,0,-1): print(" ",end=" ") for col in range(0,rows+1): print("*",end=" ") print("\n") y=int(input("enter the number of rows")) for row in range(0,y+1): for col in range(0,row): print("*",end='') print("\n") z=int(input("enter the number of rows")) for row in range(z,0,-1): for col in range(0,row): print("*",end='') print('\n') w=int(input("enter the number of rows")) for row in range(w,0,-1): s = w - row for space in range(0,s): print(" ",end="") for col in range(0,row): print("*",end='') print("\n")
false
aa2a2ef6d5af0236beb6efb3c059ec757d23aa8e
ddmitry80/ds_junior_analytics
/lesson 06/question_13_fibonacchi.py
615
4.46875
4
"""Напишите функцию, которая находит число Фиббоначи по его номеру. В качестве аргумента подается целое положительное число n (число).""" def fibonacci(n): num0 = 0 num1 = 1 num2 = 1 if n == 1: return(0) if n == 2: return(1) for _ in range(3,n): num0, num1, num2 = num1, num2, num1 + num2 return(num2) num = int(input('Укажите номер нужного числа Фибоначчи: ')) print('Нужное Вам число:', fibonacci(num))
false
7dfd2fbe20a70fa7853fe045ba9f7f6b5233e700
ddmitry80/ds_junior_analytics
/lesson 05/question_14_balls.py
992
4.125
4
"""В корзине лежат шары. Если разложить их в кучи по 2, останется один. Если разложить в кучи по 3, останется один. Если разложить в кучи по 4, останется один. Если разложить в кучи по 5, останется один. Если разложить в кучи по 6, останется один. Если разложить в кучи по 7, не будет остатка. Нужно найти минимальное количество шаров, удовлетворяющее условию.""" balls = 0 exit_if = 1 * 10**4 while True: balls += 1 if balls%2==1 and balls%3==1 and balls%4==1 and balls%5==1 and balls%6==1 and balls%7==0: print('Найдено нужное число:', balls) break if balls > exit_if: print('Выполнение слишком долгое, выхожу') break
false
c23a6abcc839541728b30d74ace2262732ba90b9
AnantVijaySingh/linear-algebra-neural-networks
/algebra_4.py
2,151
4.4375
4
""" Currency Conversion with Matrix Multiplication Over the years you have traveled to eight different countries and just happen to have leftover local currency from each of your trips. You are planning to return to one of the eight countries, but you aren't sure which one just yet. You are waiting to find out which will have the cheapest airfare. In preparation, for the trip you will want convert all your local currency into the currency local of the place you will be traveling to. Therefore, to double check the bank's conversion of your currency, you want to compute the total amount of currency you would expect for each of the eight countries. To compute the conversion you first need to import a matrix that contains the currency conversion rates for each of the eight countries. The data we will be use comes from the Overview Matrix of Exchange Rates from Bloomberg Cross-Rates Overall Chart on January, 10 2018. """ import numpy as np import pandas as pd # Creates numpy vector from a list to represent money (inputs) vector. money = np.array([70, 100, 20, 80, 40, 70, 60, 100]) # Creates pandas dataframe with column labels(currency_label) from the numpy vector for printing. currency_label = ["USD", "EUR", "JPY", "GBP", "CHF", "CAD", "AUD", "HKD"] money_df = pd.DataFrame(data=money, index=currency_label, columns=["Amounts"]) print("Inputs Vector:") print(money_df.T) # Imports conversion rates(weights) matrix as a pandas dataframe. conversion_rates_df = pd.read_csv("currencyConversionMatrix.csv", header=0, index_col=0) # Creates numpy matrix from a pandas dataframe to create the conversion rates(weights) matrix. conversion_rates = conversion_rates_df.values # Prints conversion rates matrix. print("Weights Matrix:") print(conversion_rates_df) # TODO 1.: Calculates the money totals(outputs) vector using matrix multiplication in numpy. money_totals = np.matmul(money, conversion_rates) # Converts the resulting money totals vector into a dataframe for printing. money_totals_df = pd.DataFrame(data = money_totals, index = currency_label, columns = ["Money Totals"]) print("Outputs Vector:") print(money_totals_df.T)
true
51ae29e9a042ab36d6ed972318ef5414353d956c
tashakim/puzzles_python
/polymorphism.py
811
4.3125
4
class Bird: def intro(self): print("Hello I'm a bird") def fly(self): print("Bird flies") class Albatross(Bird): # Inherits from Bird class def fly(self): # Polymorphism of Bird's method print("Albatross soars") class Sparrow(Bird): # Inherits from Bird class def fly(self): # Polymorphism of Bird's method print("Sparrow flies") class Penguin(Bird): # Inherits from Bird classvv def fly(self): # Polymorphism of Bird's method print("Penguin could not fly") if __name__ == "__main__": bird = Bird() albatross = Albatross() sparrow = Sparrow() penguin = Penguin() my_birds = [albatross, sparrow, penguin] # Create collection of my birds bird.intro() # "Hello I'm a bird" bird.fly() # "Bird flies" for bird in my_birds: bird.intro() bird.fly() # Each bird flies its own way
true
982670f0bcaa7610c6ebffd3dd9c3caac0b5cf94
tashakim/puzzles_python
/bubble_sort.py
707
4.1875
4
class InvalidInputException: """Purpose: Exception will be thrown when input array is invalid. """ pass def bubbleSort(arr): """Purpose: Python implementation of a bubble sorting algorithm. """ if(arr == None or arr == []): raise InvalidInputException("Input is invalid") for i in range(len(arr) -1): for j in range(len(arr)-i -1): if(arr[j] > arr[j+1]): arr[j], arr[j+1] = arr[j+1], arr[j] return arr if __name__ == "__main__": a = [32,30,0,1,2] a2 = [0,0,0,1,0] a3 = [-1,4,-5,9,11] assert(bubbleSort(a) == [0,1,2,30,32]), "Wrong order" assert(bubbleSort(a2) == [0,0,0,0,1]), "Wrong order" assert(bubbleSort(a3) == [-5,-1,4,9,11]), "Wrong order" print("All tests passed!")
true
1be33b574c3ce667b82fecde3bf3047527af998e
tashakim/puzzles_python
/mergesort.py
1,284
4.21875
4
def mergeSortAscend(array): # sorts array in ascending order. if len(array) > 1: left = array[:len(array)//2] right = array[len(array)//2:] mergeSortAscend(left) mergeSortAscend(right) iter1 = iter2 = k = 0 while iter1 < len(left) and iter2 < len(right): if left[iter1] < right[iter2]: array[k] = left[iter1] iter1 += 1 else: array[k] = right[iter2] iter2 += 1 k += 1 while iter1 < len(left): array[k] = left[iter1] iter1 += 1 k += 1 while iter2 < len(right): iter2 += 1 k += 1 return array def mergeSortDescend(array): # sorts array in descending order. if len(array) > 1: right = array[: len(array)//2] left = array[len(array)//2 :] mergeSortDescend(left) mergeSortDescend(right) iter1 = iter2 = k = 0 while iter1 < len(left) and iter2 < len(right): if left[iter1] > right[iter2]: array[k] = left[iter1] iter1 += 1 else: array[k] = right[iter2] iter2 += 1 k += 1 while iter1 < len(left): array[k] = left[iter1] iter1 += 1 k += 1 while iter2 < len(right): iter2 += 1 k += 1 return array if __name__ == "__main__": array = [4,3,6,2,2,1,10] print("Ascending order: ", mergeSortAscend(array)) print("Descending order: ", mergeSortDescend(array))
false
97f48bd51ce8d35c720f65ac08bade8e9a78a63e
tashakim/puzzles_python
/xor.py
473
4.28125
4
def xor(n): """Purpose: Computes the xor of all integers up to n. Note: uses special property of xor'ing consecutive integers. """ if n%4 == 0: return 0 elif n%4 == 1: return 1 elif n%4 == 2: return n+1 return n def rangeXor(left, right): """Purpose: Computes the xor of all integers between 'left' and 'right'. Note: uses property that xor'ing twice negates the effect. """ return xor(right)^xor(left - 1) if __name__ == "__main__": print(xor(3))
true
675fb84298bb43eaa944f784b17de3ed7aefd7c8
tashakim/puzzles_python
/is_prime.py
496
4.125
4
def add(x,y): return x+y def is_prime(n): if n<2: print("n must be greater than 1") return if n == 2: return True for i in range(2, n//2+1): if (n%i) == 0: return False return True def test_is_prime(n): assert is_prime(2) == True, "Test failed: 2 is prime number" assert is_prime(19) == True, "Test failed: 19 is prime number" if __name__ == "__main__": assert add(2,3) == 5, "Arithmetic failure! Try again" print(is_prime(3)) print(is_prime(4)) print(is_prime(6))
true
01a5f4ab750ba94320f86e5d9b9e2c6e16d7ff54
tashakim/puzzles_python
/linkedlistDel.py
1,571
4.28125
4
#!usr/bin/python3 class LinkedList: def __init__(self): self._head = None def __repr__(self): node = self._head nodes = [] while node is not None: nodes.append(node._value) node = node._next nodes.append("None") return "->".join(nodes) class Node: def __init__(self, value): self._value = value self._next = None def __repr__(self): return self._value def linkedlistDel1(n): """Purpose: Takes in a node n, and deletes the node after node n. Runtime complexity: O(1) """ # Here we assume that a pointer to node n is already known. n._next = None # deletes 'next' node. n._next = n._next._next # resets pointer to node after next. return def linkedlistDel2(n, head): """Purpose: Takes in a node n, and a node head, and removes n from the list, where head is the first node in the list. Runtime complexity: O(k) """ # Here we traverse through linked list and remove node n from it. s = head for i in range(len(L)): if(s == n): s._value = None s = s._next return def smartDel(n): """Purpose: Removes a node n from the list. Runtime complexity: O(1) """ # We use ._value and ._next fields. # n._value = None (resets value of node n. We don't even need this.) n._next = n._next._next return def test(): l = LinkedList() firstnode = Node("1") l._head = firstnode secondnode = Node("2") firstnode._next = secondnode thirdnode = Node("3") secondnode._next = thirdnode print(l) pass if __name__ == "__main__": L = LinkedList() firstnode = Node("A") L._head = firstnode print(L) test()
true
e5963128868ec1e7b4aa48996d4eb13f4316e8ef
tashakim/puzzles_python
/is_mirror_tree.py
1,115
4.25
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: """Purpose: Returns whether or not binary tree is symmetric around its root. """ def isMirror(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return t1.val == t2.val and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right) return isMirror(root.left, root.right) def isSymmetric1(self, root): """Returns same as above. Note: Cuts out unnecessary duplicate computation on root node. """ def isMirror(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return t1.val == t2.val and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right) return isMirror(root.left, root.right)
true
dee41107fb9d44cd8210144822840b7c9c51a1aa
maheshwarisatyam/pricing_excercise
/share_price.py
1,684
4.5625
5
import csv """ Created a function that will return a dictionary. In the dictionary company name will be a key and value will the a string, containing year and month, in which share price was maximum for that particular company. """ def return_max(): """ opening csv file having share prices data. """ f = open("share_prices.csv", "rb") csv_reader = csv.reader(f) """ taking header in comp_names """ comp_names = csv_reader.next() complete_data = {} """ company names start from third column so starting from 2(indexing) created a blank dictionary corresponding to each company name in complete_data dictionary """ for i in range(2, len(comp_names)): complete_data[comp_names[i]] = {} """ for rest of the rows, having price data, added each price value to a key key is concatenated form of year(r[0]) and month(r[1])"" """ for r in csv_reader: values = r for i in range(2, len(values)): complete_data[comp_names[i]][r[0]+" "+r[1]] = values[i] max_values ={} """ iterating over the complete_data dictionary items and finding max value using max function provided by python and passing key argument as every key of every company dictionary i.e. complete_data['comapny A'] = {'1990 Jan':.., '1990 Feb':.., '1990 Mar':..} Iterating over '1990 Jan', '1990 Feb' and so on and taking its value and finding max of it. """ for key, values in complete_data.iteritems(): max_value = max(values.iterkeys(), key= (lambda key: float(values[key]))) max_values[key] = max_value return max_values """ to run this script stand alone """ if __name__ == "__main__": print return_max()
true
49018234d7a1ce4f1a04279c4627b8c73f00d2c3
guen0610/6001x
/python/checkpal.py
657
4.34375
4
def semordnilap(str1, str2): ''' str1: a string str2: a string returns: True if str1 and str2 are semordnilap; False otherwise. ''' print("str1: ", str1) print("str2: ", str2) raw_input("Press key continue") # Your code here if len(str1) != len(str2): print(1) return False if str == '': print(2) return True if len(str1) == 1: print(3) return True if len(str1) == 2: print(4) return str1[0] == str2[1] and str[1] == str2[0] if str1[0] != str2[-1]: print(5) return False else: return semordnilap(str1[1:-1],str2[1:-1])
true
165a6d283866b7a8cd152bdb5536ca8d850b9b12
solanyn/cs-courses
/intro-cs/intro-to-programming/exercises/ex_12_02.py
871
4.15625
4
""" Exercise 2: Change your socket program so that it counts the number of characters it has received and stops displaying any text after it has shown 3000 characters. The program should retrieve the entire document and count the total number of characters and display the count of the number of characters at the end of the document. """ import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) url = input('Enter URL: ') host = url.split('//')[1].split('/')[0] try: mysock.connect((host, 80)) cmd = 'GET {} HTTP/1.0\r\n\r\n'.format(url).encode() mysock.send(cmd) count = 0 text = '' while True: data = mysock.recv(5120) if len(data) < 1: break text += data.decode() count += len(data) mysock.close() print(text[:3000]) print(count) except: print('Invalid URL!')
true
3e1bc76ca1aa8704af0e0aae93f02f6854ccebb7
solanyn/cs-courses
/intro-cs/intro-to-programming/exercises/ex_04_06.py
513
4.21875
4
""" Exercise 6: Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters (hours and rate). """ def computepay(hours, rate): if hours < 40: return hours * rate else: return (hours - 40) * rate * 1.5 + 40 * rate try: hours = float(input("Enter Hours: ")) except: print('Invalid hours') try: rate = float(input("Enter Rate: ")) except: print('Invalid rate') print(computepay(hours, rate))
true
bf5924ccbc77b778ff208fdcdec1c12d511d41e0
solanyn/cs-courses
/intro-cs/intro-to-programming/exercises/ex_05_02.py
535
4.1875
4
""" Exercise 2: Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average. """ min = float('inf') max = float('-inf') done = False while not done: x = input('Enter a number: ') if x == 'done': done = True else: try: x = float(x) if x > max: max = x if x < min: min = x except: print('Invalid input') print(max, min)
true
d717719031e07b504d852cfe86db9ae368f97961
jovesterchai/AppDev
/PycharmProjects/Practical6a/List.py
389
4.21875
4
num_list = [] number = int(input("How many numbers to capture: ")) for i in range(number): msg = "Enter number #" + str(i+1) num = int(input(msg)) num_list.append(num) print("The lowest number is :", min(num_list)) print("The highest number is :", max(num_list)) print("The total is :", sum(num_list)) average = sum(num_list)/len(num_list) print("The average is ", average)
true
76e968635e8e91b386e3981e583ee352d74e218d
olhanotolga/python-challenges
/validate_pin/valid_pin.py
760
4.25
4
__doc__ import re """ The function checks the input against a set of conditions and returns a boolean. Input value: string. Output: boolean. Exception: if the input is not of the type string, the returned value is "Must be a string." """ def valid(pin): if not isinstance(pin, str): return "Must be a string" pattern = r"^(\d{4})$|^(\d{6})$" result = re.match(pattern, pin) if result: return True else: return False def main(): answer0 = valid("123045") answer1 = valid("12345") answer2 = valid("") answer3 = valid("abc456") answer4 = valid(123456) print(answer0) print(answer1) print(answer2) print(answer3) print(answer4) if __name__ == "__main__": main()
true
b0dd9e29c66717c7b0f187dbe8f974c9dddc046d
olhanotolga/python-challenges
/positive_negative/positive_negative.py
1,443
4.25
4
__doc__ import re def neutralize(str1, str2): """ Function neutralize takes two eqal-length input strings. It returns one string of the same length where each character is the result of interaction between the character in string 1 and string 2 at the same index. - When "+" and "+" interact, they remain "+". - When "-" and "-" interact, they remain "-". - But when "-" and "+" interact, they become "0". Arguments: 2 strings containing of exclusively "+" and/or "-" characters. Output: 1 string containing of exclusively "+", "-", or "0" characters. """ # type check if not isinstance(str1, str) or not isinstance(str2, str): return "Must be a string" # input strings should be of the equal length if not len(str1) == len(str2): return "Lengths don't match" # check for valid characters (only '+' and '-' are accepted) pattern = "^[+-]+$" if not re.match(pattern, str1) or not re.match(pattern, str2): return "Invalid pattern" output = "" # instead of writing a series of "if" statements, I used a dictionary rules = {"++": "+", "--": "-", "+-": "0", "-+": "0"} for i in range(len(str1)): output += rules[str1[i] + str2[i]] return output def main(): answer1 = neutralize("+-+", "+--") answer2 = neutralize("--++--", "++--++") print(answer1) print(answer2) if __name__ == "__main__": main()
true
0c725ad9a14a9edf1dbebb8de8043eb2935c3c37
will-twosticks/ICTPRG-Python
/python exercises/week03/week3.py
1,441
4.1875
4
#question 1 """ name = input("what is your name? ") if (name == "frank") or (name == "george"): print("welcome " + name) """ #question 2 """ currentYear = 2020 drinkingAge = 18 askedYear = int(input("what year were you born? ")) if currentYear - askedYear >= drinkingAge: print("Come in and drink") else: print("go away child") """ #question 3 """ username = input("what is your username? ") dpassword = int(input("what is your password? ")) if (username == "bob") and (password == "1234"): print("access granted") else: print("access denied") """ #question 4 """ username = input("what is your username? ") password = input("what is your password? ") if (username == "bob") and (password == "password1234"): print("access granted") elif (username == "fred") and (password == "happypass122"): print("access granted") elif (username == "lock") and (password == "passwithlock44"): print("access granted") else: print("access denied") """ #question 5 """ High Distinction 100 - 90 Distinction 89- 80 Credit 79 - 70 Pass 69 - 50 """ highdistinction = 90 distinction = 80 credit = 70 passed = 50 score = int(input("what is your score? ")) if score >= highdistinction: print("you got a high distinction") elif score >= distinction: print("you got a distinction") elif score >= credit: print("you got a credit") elif score >= passed: print("you got a pass") else: print("you failed")
false
75f22f7e7bb0227f33d47ec05a6f34e8ccaefa60
Hem1700/python-codes
/secondlargest.py
213
4.28125
4
lst = [] n = int(input("Enter the size of the list: ")) print("Enter the numbers!:") for i in range(n): numbers = int(input()) lst.append(numbers) lst.sort() print("Second largest element is:", lst[-2])
true
891e36b5ea1fb27263e0e81c350401e785645b43
Hem1700/python-codes
/vowel.py
210
4.125
4
str = input("Enter a word:") for i in str: if 'a' in str or 'e' in str or 'i' in str or 'o' in str or 'u' in str: print("Yes it has vowels") else: print("It doesnt have any vowels")
true
4e194d6c03d782309d1276be35a94ece32c06a61
Jon-Dionson/cp1404_practicals
/prac_03/password_check.py
494
4.28125
4
MIN_LENGTH = 3 MAX_LENGTH = 10 def main(): """run""" password = get_password() check_password(password) def get_password(): """get the user's password""" password = input("Enter a password: ") return password def check_password(password): """check the user's password""" while len(password) > MAX_LENGTH or len(password) < MIN_LENGTH: print("Invalid Password") password = input("Enter a password: ") print(len(password) * "*") main()
false
29349f02475067b4a92ce2f38160a3670ec86b33
mmspaced/Miscellaneous-HF-Python-files
/vsearch.py
611
4.3125
4
def search_for_characters(phrase:str, characters:str) -> set: """ Function to search for the characters in a phrase, both passed as function arguments. Return the characters found in the phrase. This is considered a docstring, which can span muliple lines Note the use of annotations, which are documentation standards, not enforcement mechanisms. The type of data being passed back and forth is not considered by the interpreter. """ return set(characters).intersection(set(phrase)) # word = input('Provide a word to search for vowels: ') # search_for_vowels(word)
true
1ef354bff22c4000b5127cf248c57029a0d72a34
Apokalipsis113/Python
/udemy/python/run2.py
1,837
4.21875
4
########################### ## PART 10: Simple Game ### ### --- CODEBREAKER --- ### ## --Nope--Close--Match-- ## ########################### # It's time to actually make a simple command line game so put together everything # you've learned so far about Python. The game goes like this: # 1. The computer will think of 3 digit number that has no repeating digits. # 2. You will then guess a 3 digit number # 3. The computer will then give back clues, the possible clues are: # # Close: You've guessed a correct number but in the wrong position # Match: You've guessed a correct number in the correct position # Nope: You haven't guess any of the numbers correctly # # 4. Based on these clues you will guess again until you break the code with a # perfect match! # There are a few things you will have to discover for yourself for this game! # Here are some useful hints: # Try to figure out what this code is doing and how it might be useful to you import random import math digits = list(range(10)) random.shuffle(digits) print(digits[:3]) # Another hint: guess = input("What is your guess? 3 digist separated by space") print(guess) tmp_guess = guess.split() print(tmp_guess) tmp = [] for i in tmp_guess: tmp.append(int(i)) print(tmp) def check(guess, source): MATCH = "Match" CLOSE = "Close" FAR = "Far" result = str() for i in range(len(guess)): if guess[i] == source[i]: result = result + MATCH + " " elif abs( guess[i] - source[i]) == 1: result = result + CLOSE + " " else: result = result + FAR + " " return result print(check(tmp, digits[:3])) # Think about how you will compare the input to the random number, what format # should they be in? Maybe some sort of sequence? Watch the Lecture video for more hints!
true
746659eb70137c971deb5f9112b7d927b509e865
LucasDonato333/CursoEmVideo
/Python/Exercicios/ex037.py
644
4.125
4
print(''' Escreva um programa que leia um número inteiro qualquer e peça o usuário escolher qual será a base de conversão: -1 para binário -2 para octal -3 para hexadecimal''') print(25 * '-=-') n = int(input('Digite um valor: ')) print('''\nEscolha uma opção \033[32m[ 1 ] BINÁRIO [ 2 ] OCTAL [ 3 ] HEXADECIMAL\033[m''') o = int(input('Opção : ')) print('O número {} convertido para'.format(n)) if o == 1: print('BINÁRIO = {}'.format(bin(n)[2])) elif o == 2: print('OCTAL = {}'.format(oct(n)[2])) elif o == 3: print('HEXADECIMAL = {}'.format(hex(n)[2])) else: print('Opção incorreta.')
false
acfc94fbaeeb993da45a25f4fa6c6875a03ccce8
LucasDonato333/CursoEmVideo
/Python/Exercicios/ex042.py
827
4.15625
4
print('Refaça o DESAFIO 035 dos triangulos, acrescentando o recurso de\n' 'mostrar que tipo de triângulo será formado:\n' '- [\003EQUILÁTERO: Todos os lados iguais\n' '- ISÓSCELES: Dois lados iguais\n' '- ESCALENO: Todos os lados diferentes\n') l1 = int(input('PRIMEIRO SEGMENTO | ')) l2 = int(input('SEGUNDO SEGMENTO | ')) l3 = int(input('TERCEIRO SEGMENTO | ')) if l1 < l2 + l3 and l2 < l1 +l3 and l3 < l1 + l2: print('Podem formar um triangulo ', end='')#end='' vai eliminar o enter e trazer a palavra a baixo, seguida da frase if l1 == l2 == l3: print('EQUILÁTERO.') elif l1 == l2 or l1 == l3 or l2 == l3: print('ISÓSCELES.') else: print('ESCALENO.') else: print('Não podem formar um Triângulo.')
false
8cf061edb2913cba8e0da294e716cd280ba4ff61
LucasDonato333/CursoEmVideo
/Python/Exercicios/ex041.py
817
4.25
4
from datetime import date print('A Confederação Nacional de Natação precisa de um programa que leia\n' 'o ano de nascimento de um atleta e mostre sua categoria, de acordo\n' 'com a idade:\n' '- Até 9 anos: MIRIM\n' '- Até 14 anos: INFANTIL\n' '- Até 19 anos: JUNIOR \n' '- Até 25 anos: SÊNIOR\n' '- Acima: MASTER\n') print(30*'-=-') print('\n') n = int(input('Digite o ano de nascimento do atleta: ')) print('\n') atual = date.today().year idade = atual - n print('O atleta tem {} anos.'.format(idade)) if idade <= 9: print('CATEGORIA MIRIM') elif idade <= 14: print('CATEGORIA INFANTIL') elif idade <= 19: print('CATEGORIA JUNIOR') elif idade <= 25: print('CATEGORIA SÊNIOR') else: print('CATEGORIA MASTER')
false
4be5952204b817763e5838e0470642282959a9ef
MauryPi/OOP-Activity
/OOP.py
1,977
4.1875
4
Employee = [] company = True class Employeess: def __init__(self, Name, Department, Position, Rate): self.Name = Name self.Department = Department self.Position = Position self.Rate = Rate def compute(self, Hourly): return Hourly * self.Rate while company: print(""" ------------------------------------------------------------------ "CHOOSE YOUR OPTION BELOW: " (1.) Add An Employee: (2.) Enter The Hourly Of Employee: (3.) Show The Employees Informations: (4.) EXIT: ------------------------------------------------------------------ """) print("Enter The Option:", end="") user = int(input()) if user == 1: print("Type The Name: ", end="") Name = (input()) print("Type The Department: ", end="") Department = input() print("Type The Position: ", end="") Position = input() print("Type The Rate: ", end="") Rate = int(input()) Employee.append(Employeess(Name, Department, Position, Rate)) continue elif user == 2: e1m = Employeess(Name, Department, Position, Rate) print("Type The Index Of The Employee: ", end="") e = int(input()) print(Employee[e].Name, "HAS BEEN SELECTED") print("Enter The Hourly Of Employee: ", end="") l = int(input()) print(Employee[e].Rate * l) continue elif user == 3: for ex in Employee: print("\nName:", ex.Name, "\nDepartment:", ex.Department, "\nPosition:", ex.Position, "\nRate:", ex.Rate,"\n") continue elif user == 4: running = False else: print("WRONG!!! PLEASE TRY AGAIN LATER:") continue break
true
798022bb646925f14060de376fb503634883a90a
darrencheng0817/AlgorithmLearning
/Python/leetcode/minimumHeightTrees.py
1,785
4.21875
4
''' Created on 2015年12月12日 https://leetcode.com/problems/minimum-height-trees/ @author: Darren ''' ''' For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels. Format The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels). You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. Example 1: Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] 0 | 1 / \ 2 3 return [1] Example 2: Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 0 1 2 \ | / 3 | 4 | 5 return [3, 4] ''' def findMinHeightTrees(n, edges): """ :type n: int :type edges: List[List[int]] :rtype: List[int] """ if not edges or n==1: return [0] adj=[set() for i in range(n)] for i,j in edges: adj[i].add(j) adj[j].add(i) leaves=[nodeIndex for nodeIndex in range(n) if len(adj[nodeIndex])==1] while n>2: n-=len(leaves) newLeaves=[] for leaf in leaves: adjLeaf=adj[leaf].pop() adj[adjLeaf].remove(leaf) if len(adj[adjLeaf])==1: newLeaves.append(adjLeaf) leaves=newLeaves return leaves n = 6 edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] print(findMinHeightTrees(n, edges))
true
fa0a07ceca707fc10b311088bb8ab3704973a8c0
nandabhushan597/Data-Structures-Algorithms-
/reverse_nanda_bhushan.py
1,999
4.6875
5
""" Reverse a simple list using just "empty", "head", and "rest" and other functions written here Examples: INCLUDE AT LEAST TWO TEST CASES FOR append(l, x) >>> print reverse(my_list()) [] >>> print reverse(my_list().prepend(5)) [5] >>> print reverse(my_list().prepend(5).prepend(3)) [5, 3] >>> print reverse(my_list().prepend(5).prepend(3).prepend(16)) [5, 3, 16] >>> print append(my_list(), 8) [8] >>> print append(my_list().prepend(7).prepend(2), 10) [2,7,10] """ import sys sys.path.append('/home/courses/python') from logic import * from my_list import * # append method # AXIOMS HERE # append(my_list(),x) === x # append(my_list(h,r), x) === my_list(h,append(r, x)) #Complexity: linear in number of items in a list and uses prepend function def append(l, x): precondition(type(my_list()) == type(l)) #precondition that data type of my_list and l are the same if l == my_list(): return my_list().prepend(x) else: return append(l.rest(), x).prepend(l.head()) #reverse method #AXIOMS HERE # reverse(my_list()) === my_list() # reverse(my_list(h,r) === my_list append(reverse(r),h)) #Complexity: linear because depends on the length or number of items in a list and accesses append function def reverse(l): """ replace this with your "reverse" function """ precondition(type(my_list()) == type(l)) #precondition that data type of my_list and l are the same if l == my_list(): #if the list is empty return the list return l else: return append(reverse(l.rest()), l.head()) #otherwise append the head to the reverse of the rest # The following gets the "doctest" system to check test cases in the documentation comments def _test(): import doctest return doctest.testmod() if __name__ == "__main__": if _test()[0] == 0: print "Congratulations! You have passed all the tests"
true
1f26b5a80bd37578e2632036084fcecff136c003
Monojit-Saha333/SensorFaultDetection
/log.py
771
4.1875
4
from datetime import datetime class logger: """ created by:monoit Saha description:this class is used for writting the logs in the log files version:1.0 revision :none """ def __init__(self): pass def writelog(self,fileobject,messages): """ created by:Monojit Saha description:this method is used to write a message along with date and time in a text file :param fileobject: :param messages: version:1.0 revision:none :return: """ self.date=datetime.now().date() self.current_time=datetime.now().time().strftime("%HH-%MM-%SS") self.message=str(self.date)+"\t"+str(self.current_time)+"\t\t"+messages+"\n" fileobject.write(self.message)
true
6f23c603e559519bb87579791e05047533fad74a
saranyab9064/leetcode-geeks
/Array/47_Sort_Colors.py
2,047
4.34375
4
# ============================================================================ # Name : 47_Sort_Colors.py # Author : Saranya Balakrishnan # Mail Id : saranyab0925@gmail.com # ========================================================================== """ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with a one-pass algorithm using only constant space? """ class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ # initialise red ,white as zero and blue as last element in array red = 0 white = 0 blue = len(nums) - 1 while white <= blue: current_ele = nums[white] # check is curr is 0, then assign the red and white element & incr both if current_ele == 0: nums[white] = nums[red] nums[red] = 0 red = red + 1 white = white + 1 # if curr ele is 1 then simply incr white elif current_ele == 1: white = white + 1 # if curr ele is 2 then assign the value and decr the blue else: nums[white] = nums[blue] nums[blue] = 2 blue = blue - 1 print(nums) if __name__ == '__main__': n = [2,0,2,1,1,0] test = Solution() test.sortColors(n)
true
a5a9b646324355240128608af25bd10d9c930b28
saranyab9064/leetcode-geeks
/Strings/29_Reverse_Words_in_a_String.py
1,597
4.46875
4
# ============================================================================ # Name : 29_Reverse_Words_in_a_String.py # Author : Saranya Balakrishnan # Mail Id : saranyab0925@gmail.com # ========================================================================== """ Given an input string, reverse the string word by word. Example 1: Input: "the sky is blue" Output: "blue is sky the" Example 2: Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. Note: A word is defined as a sequence of non-space characters. Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. You need to reduce multiple spaces between two words to a single space in the reversed string. Follow up: For C programmers, try to solve it in-place in O(1) extra space. """ class Solution: def reverseWords(self, s: str) -> str: """ first solution s = s.split(' ') print(s) list1 = [] for i in s: list1.insert(0,i) print(list1) return (" ".join(list1)) """ # optimised one s = s.split() l = s[::-1] out = ' '.join(l) print(out) return out if __name__ == "__main__": test = Solution() Input = "the sky is blue" res = test.reverseWords(Input) print(res)
true
ebe969255e83685b3ba8a54bfc997fd3320f5bcf
saranyab9064/leetcode-geeks
/Strings/21_Length_of_Last_word.py
1,032
4.15625
4
# ============================================================================ # Name : 21_Length_of_Last_word.py # Author : Saranya Balakrishnan # Mail Id : saranyab0925@gmail.com # ============================================================================ """ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word is defined as a maximal substring consisting of non-space characters only. Example: Input: "Hello World" Output: 5 """ class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ a = s.split() if len(a) != 0: b = a[len(a) - 1] return len(b) else: return 0 if __name__ == '__main__': s = " a " integer = Solution() res = integer.lengthOfLastWord(s) print(res)
true
6524fd1265705ef78405f42773cacb3cc551285b
saranyab9064/leetcode-geeks
/challenges/04_merge_linked_lists.py
1,320
4.21875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # initialise two pointers p1 = l1 p2 = l2 head=p3 = ListNode(0) while True: if p1 is None: p3.next = p2 break if p2 is None: p3.next = p1 break if p1.val >= p2.val: p3.next = p2 p2 = p2.next else: p3.next = p1 p1 = p1.next p3 = p3.next return(head.next) def print_recursive(l): if l is None: return '' return str(l.val) + '->' + print_recursive(l.next) if __name__ == "__main__": l1 = Solution() l2 = Solution() l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) print(print_recursive(l1)) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(5) print(print_recursive(l2)) test = Solution() l3 = test.mergeTwoLists(l1,l2) print(print_recursive(l3))
false
f0188bcf2607add5c3b33ecf07aa6037068f98ee
janeqqrul/Git_begin
/encrypting.py
1,663
4.21875
4
""" Code to decript and encrypt a given string """ import math from itertools import zip_longest as zl def encrypt(txt, n_times): """ This function enrypts the string puted as an argument to string with chars mixed up ---> [::2]. It mixes the elements in a string n times """ if n_times<= 0: out_text = txt else: loop = 0 l_txt = list(txt) end = l_txt[::2] beg = l_txt[1::2] new_string = beg + end while loop < (n_times - 1) and n_times>1: end = new_string[::2] #every secound char beg = new_string[1::2] #every secound char, starting from secound char new_string = beg+end #creating new string for a loop loop = loop + 1 out_text = "".join(new_string) return out_text def decrypt(encrypted_text, n_times): """ This function decrypt string puted as an argument. It restore the oryginal array and to do so it iter itself n times through while loop """ if n_times<=0: l_enc = encrypted_text else: loop = 0 j_list_tuple = [] l_enc = list(encrypted_text) while loop<n_times: len_enc = len(l_enc) beg = l_enc[math.floor((len_enc/2)):] end = l_enc[:math.floor((len_enc/2))] zip_enc = tuple(zl(beg,end,fillvalue="")) loop += 1 for elem in zip_enc: j_tuple = "".join(elem) j_list_tuple.append(j_tuple) l_enc = "".join(list("".join(j_list_tuple))) j_list_tuple = [] return l_enc
true
a675b4c59be540f9aa71b40bd283f4c86ea4d599
khimacademy/c104
/solution/ch8/8_5_a.py
723
4.15625
4
''' 8-5. 도시 도시 이름과 나라 이름을 받는 describe_city() 함수를 만드세요. 이 함수는 "레이캬비크는 아이슬랜드에 있습니다." 같은 단순한 문장을 출력해야 합니다. 나라 이름 매개변수에 기본값을 지정하세요. 세 개의 도시에 대해 함수를 호출하되, 최소한 하나는 기본값인 나라에 있지 않은 도시를 써야 합니다. Output: santiago is in chile. reykjavik is in iceland. punta arenas is in chile. ''' def describe_city(city, country='chile'): """Describe a city.""" msg = city + ' is in ' + country + '.' print(msg) describe_city('santiago') describe_city('reykjavik', 'iceland') describe_city('punta arenas')
false
c3bf183e548981492733ee9095e4043ab070496f
chadlimedamine/Coding-Challenges
/letter_capitalize.py
379
4.21875
4
def LetterCapitalize(text): # code goes here words = text.split() new_text = "" words_size = len(words) for i, w in enumerate(words, 1): if i != words_size: new_text += w.capitalize() + " " else: new_text += w.capitalize() return new_text # keep this function call here print LetterCapitalize(raw_input())
false
29c53d3f675f8927f29d7a7bb09074d6602279ed
kevvolz/kevpy
/3pythonAccessWebData.py
1,868
4.4375
4
#Extracting Data with Regular Expressions (Chapter 11): Extract all numbers from file using regex and print sum import re #imports regular expressions file = raw_input("Enter file name: ") #prompt user for filename if len(file) < 1 : file = "regex_sum_211577.txt" #default file if no entry fhand = open(file) #designate file handle, open and read numlist = list() #define list add = list() #define list for line in fhand: #for each line in file handle... line = line.rstrip() #removes \n; new line stuff = re.findall('[0-9]+', line) #finds completely, all integers -- in line if len(stuff) == 0: continue #if length of int = 0, keep going numlist.append(stuff) #append all found integers to numlist for x in stuff: #for items in numlist x = int(x) # convert to integer add.append(x) #append to list called add print sum(add) #print sum of add (list of integers) list #Regex Lessons import re #imports regular expressions file = raw_input("Enter file name: ") #prompt user for filename if len(file) < 1 : file = "regex_sum_42.txt" #default file if no entry fhand = open(file) #designate file handle nums = list() #empty list for line in fhand: #for each line in file handle... line = line.rstrip() #removes \n #if line.find('E') >= 0: #find lines with XXXX #if line.startswith('W') : #find lines starting with 'W' #if re.search('vocabulary', line): #searches for lines with XXXX #if re.search('^I', line): #searches for lines that start with XXXX #print line if re.search('[0-9]+', line) : x = re.findall('[0-9]+', line) nums.append(x) print nums # Accessing web data import urllib fhand = urllib.urlopen('http://www.dr-chuck.com/page1.htm') for line in fhand: print line.strip() #Compile all other notes and add here -KV 9/20/2016
true
18977bcc85f8f90871b816cdfa47287074ef6ce8
lcnodc/codes
/09-revisao/practice_python/reverse_word_order.py
611
4.59375
5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 15: Reverse Word Order Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: My name is Michele Then I would see the string: Michele is name My shown back to me. """ def reverse_word_order(word: str): return " ".join(word.split(" ")[::-1]) long_string = input("Write a long string: ") print("The string in backwards order: %s" % reverse_word_order(long_string))
true
566ebe33c700900859589e7b88db18a495aa03c9
lcnodc/codes
/09-revisao/practice_python/cows_and_bulls.py
2,299
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 18: Cows And Bulls Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout teh game and tell the user at the end. Say the number generated by the computer is 1038. An example interaction could look like this: Welcome to the Cows and Bulls Game! Enter a number: >>> 1234 2 cows, 0 bulls >>> 1256 1 cow, 1 bull Until the user guesses the number. """ import random def get_secret_number(): """ Define the secret number and write it to a file. """ secret_number = str(random.randint(1000, 9999)) with open("secret_number.txt", "w") as file: print(secret_number, file=file) return secret_number def get_cows_and_bulls(secret, user): """Calculate the amount of cows and bulls. """ cows = bulls = 0 secret_chars = secret for i in range(len(secret)): if user[i] == secret[i]: cows += 1 if user[i] in secret_chars: bulls += 1 secret_chars = remove_char(secret_chars, user[i]) return cows, bulls def remove_char(s, c): """Remove a char of the string. When a user character exist in a secret_chars, add 1 to bulls and remove it of secret_chars to don't duplicate the count """ list_chars = list(s) list_chars.remove(c) return "".join(list_chars) if __name__ == "__main__": guessed = False attempts = 0 secret = get_secret_number() while not guessed: user = input("Guess a 4-digit number: ") attempts += 1 if user == secret: guessed = True print("%i cows, %i bulls" % (get_cows_and_bulls(secret, user))) print( "Congrats! The number is %s. You did %s attempts." % (secret, attempts))
true
b701bcc852ec0377bbc2a5c7379365506ed7ad05
lcnodc/codes
/09-revisao/practice_python/list_remove_duplicates.py
833
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 14: List Remove Duplicates Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. Extras: Write two different functions to do this - one using a loop and constructing a list, and another using sets. Go back and do Exercise 5 using sets, and write the solution for that in a different function. """ def remove_duplicates(l: list) -> list: new_list = list() [new_list.append(i) for i in l if i not in new_list] return new_list def remove_duplicates2(l: list) -> list: return list(set(l)) a = [1, 1, 1, 2, 2, 3, 4, 5, 7, 7, 8, ] print("Lista sem duplicados: %s" % remove_duplicates(a)) print("Lista sem duplicados 2: %s" % remove_duplicates2(a))
true
70eb1cbd3f7ae923e00edd0b34c527ea8da5c3a8
homa7/algorithm
/py/2.py
323
4.15625
4
# Find all prime factors of a number? def primeFactors(n): factors = [] divider = 2 while n > 2: if n%divider == 0: factors.append(divider) n = n / divider else: divider+=1 return factors n = int(input('enter a integer number:')) print(primeFactors(n))
false
869aae264bc11cf1b3086fcf51d4ab3a52c2d927
edeckrow/CSE231
/Lab 08/presentation/L8-1.py
392
4.125
4
# Note that we have to check if the key exists already. # If we try adding 1 to the value of letter_frequency[char] # without checking if it exists, we would get KeyError letter_frequency = {} example_string = "mirror" for char in example_string: if char in letter_frequency: letter_frequency[char] += 1 else: letter_frequency[char] = 1 print(letter_frequency)
true
7de4f7882da4329d0d2ae5f1dec0b90b1562208f
edeckrow/CSE231
/Lab 02/presentation/L2-2.py
404
4.21875
4
user_input = input("Type 'yes': ") user_score = int(input("Input a score greater than/equal to 50: ")) if user_input == 'yes' and user_score >= 50: print("Thank you!") elif user_input == 'yes' and user_score < 50: print("Your score was below 50") elif user_input != 'yes' and user_score >= 50: print("Your input wasn't 'yes'") else: print("Both your input and score were invalid :(")
true
a3ca4e8a60d986afdb6113511e8d38dc1aaf21ef
edeckrow/CSE231
/Lab 06/presentation/L6-2.py
2,288
4.15625
4
# Source: ourworldindata.org # Retrieved: 8/3/2020 # *.csv files w/ lists import csv # import the csv module! def open_file(): while True: try: fp = open(input('Enter file name: '), 'r') return csv.reader(fp) # pass a file pointer to csv.reader() to obtain a "reader" object except FileNotFoundError: print('File not found, try again.') def print_data(data): # (only extracting certain countries for sake of brevity) header = "{:<16s}{:<16s}{:<16s}{:<16s}{:<16s}{:<16s}".format('Date', 'World', 'Canada', 'South Korea', 'United States', 'US%') body = "{:<16}{:<16}{:<16}{:<16}{:<16}{:<16.2%}" us_percents = [] # we'll create a list to store the column of US percents print(header) for line_list in data: # iterate through the list of lists print(body.format(line_list[0], line_list[1], line_list[2], line_list[6], line_list[7], line_list[8])) us_percents.append(line_list[8]) # continually add with each row value print('\nMax US%: {:.2%}'.format(max(us_percents))) # extract the max with the max() function def parse_data(reader): next(reader) # skips header line data = [] # we'll store all of our interpreted data here for line_list in reader: # rows are already broken up into lists! world_cases = int(line_list[1]) # extract the world cases, us_cases = int(line_list[-1]) # and the US cases -- ensuring they're of proper type try: us_percent = us_cases / world_cases except ZeroDivisionError: # error catch in case world_cases is 0 us_percent = 0.0 # defaults to 0 if true line_list.append(us_percent) # we'll add the data we discovered to the existing list data.append(line_list) # and model the entire file by making a list-of-lists return data def main(): fp = open_file() data = parse_data(fp) print_data(data) # (always import at the top of your program, I just put it down here for ease of demonstration) from plot_data import plot_data; plot_data(data) if __name__ == "__main__": main()
true
e1fab66e3fb2f96f1bee0fa173ab42c086d562b0
BaomingRose/Python-Learning
/Learning/01-type.py
437
4.15625
4
# 类型转换 当字符串内容为浮点型要转换为整型时,无法直接用 int() 转换 a = "1.1" print(float(a)) # 1.1 print(int(float(a))) # 1 x = y = z = 0 o, p, q = 0, 2, "rose" print("o =", o) print("p =", p) print("q = " + q) a, b, c, d = 20, 5.5, True, 4+3j print(type(a), type(b), type(c), type(d)) # <class 'int'> <class 'float'> <class 'bool'> <class 'complex'> print(isinstance(b, float)) # True
false
28be021f35b03c8161f52d19db575de0447f5f0b
BomberDim/Python-practice
/examples№2/task2/pr2.py
1,090
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mounth = input("Введите название месяца ") if mounth == "январь": print("В январе 31 день") elif mounth == "февраль": print("Если год високосный - 28 дней, если обычный год - 29 дней") elif mounth == "март": print("В марте 31 день") elif mounth == "апрель": print("В апреле 30 дней") elif mounth == "май": print("В мае 31 день") elif mounth == "июнь": print("В июне 30 дней") elif mounth == "июль": print("В июле 31 день") elif mounth == "август": print("В августе 31 день") elif mounth == "сентябрь": print("В сентябре 30 дней") elif mounth == "октябрь": print("В октябре 31 день") elif mounth == "Ноябрь": print("В ноябре 30 дней") elif mounth == "декабрь": print("В декабре 31 день") else: print("Вы не указали месяц")
false
027e8a1de7a0285f1ae985bfe5655f58feb09163
KhauTu/C4E15---Khau-Tu
/Labs/lab3/Homework/07_remove_dollar.py
210
4.3125
4
def remove_dollar_sign(s): s = str(s).replace('$','') return s # s = input("the string is: ") # the agrument $ in this function $ is s$$$ remove_dollar_sign("the agrument $ in this function $ is s$$$")
true
afd64a3fdc0446a03013c38a75dd8bb726912193
KhauTu/C4E15---Khau-Tu
/Fundamentals/session04/jumble_game_template.py
670
4.125
4
# The Word Jumble Game import random WORDS = ["python", "jumble", "game", "word"] word = random.choice(WORDS) correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # Start the game print(''' WELCOME TO WORD JUMBLE ---------------------- ''') print("The jumble is: ", jumble) guess = input("Your guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") guess = input("Your guess: ") if guess == correct: print("That's it! you guessed it") print("Thanks for playing") input("Press the ENTER key to exit")
true
c1db92135872231db28dec2ef6c3a1754cbcfca0
KhauTu/C4E15---Khau-Tu
/Fundamentals/session03/skip_odd_numbers.py
226
4.15625
4
x = 10 while x: x = x - 1 # or x -= 1 if x % 2 != 0: continue # Odd? --skip print print(x, end =' ') y = 10 while y: y = y - 1 # or y -= 1 if y % 2 == 0: # Odd? --skip print print(y, end =' ')
false
058106a460bde6534f4fa804c3eeefb468bf5448
mairandomness/Advent-of-code
/advent_of_code_2017/day12/part-a.py
2,378
4.15625
4
"""--- Day 12: Digital Plumber --- Walking along the memory banks of the stream, you find a small village that is experiencing a little confusion: some programs can't communicate with each other. Programs in this village communicate using a fixed system of pipes. Messages are passed between programs using these pipes, but most programs aren't connected to each other directly. Instead, programs pass messages between each other until the message reaches the intended recipient. For some reason, though, some of these messages aren't ever reaching their intended recipient, and the programs suspect that some pipes are missing. They would like you to investigate. You walk through the village and record the ID of each program and the IDs with which it can communicate directly (your puzzle input). Each program has one or more programs with which it can communicate, and these pipes are bidirectional; if 8 says it can communicate with 11, then 11 will say it can communicate with 8. You need to figure out how many programs are in the group that contains program ID 0. For example, suppose you go door-to-door like a travelling salesman and record the following list: 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5 In this example, the following programs are in the group that contains program ID 0: Program 0 by definition. Program 2, directly connected to program 0. Program 3 via program 2. Program 4 via program 2. Program 5 via programs 6, then 4, then 2. Program 6 via programs 4, then 2. Therefore, a total of 6 programs are in this group; all but program 1, which has a pipe that connects it to itself. How many programs are in the group that contains program ID 0?""" def main(): f = open("input", "r") text = f.read()[:-1] line_lst = text.split("\n") input_lst=[] for line in line_lst: input_lst.append(line.split(" <-> ")) child_lst = [] for line in input_lst: child_lst.append([int(elem) for elem in line[1].split(", ")]) to_check = [0] checked = [] while len(to_check) > 0: for elem in child_lst[to_check[0]]: if elem not in checked: to_check.append(elem) if to_check[0] not in checked: checked.append(to_check[0]) to_check = to_check[1:] print(len(checked)) if __name__=="__main__": main()
true
52b3918b60f4158f035d9243219262746b6f8bb1
omkar-sharmamn/py-practice
/gen_prime_n.py
752
4.1875
4
#!/usr/bin/python prime = [] def gen_prime(n): for item in range(0, n): is_prime(item) def is_prime(num): if num <= 0 or num == 1: print "%s : Numbers below 2 are not prime numbers" % num else: for item in range(2, num): if num % item == 0: #print "%s : Not a prime Number" % num return False else: #print "%s : is a prime Number" % num prime.append(num) return True, prime if __name__ == '__main__': limit = int(raw_input("Enter the limit of prime numbers to be generated : ")) print gen_prime(limit) print print "Prime Numbers : " for item in prime: print item
true
893765a68d8911343d4a1fd5c8acfc72d5eea102
quanwen20006/PythonLearn
/chapter03/magic_func.py
1,567
4.40625
4
''' python 魔法函数--指的是双下划线开头、双下划线结尾的函数 ''' class Company(object): def __init__(self, employ_list): self.employee = employ_list def __getitem__(self, item): # 循环对象的时候会执行该方法,执行到抛异常截至 # print("开始执行__getitem__") return self.employee[item] def __len__(self): # 执行类实例对象的len方法会执行该方法,如未定义即报错 return len(self.employee) def __str__(self): return ".".join(self.employee) def __repr__(self): return "__repr__" employee = Company(["Jack", "Jones", "Lily"]) # 下面这一行其实调用的就是__str__ print("employee---", employee) # employee 和employee.__repr__() 意义是一样的 employee employee.__repr__() # 执行该方法需要company实现__len__方法 print( ("employee的类型是%s 长度是%d") % (type(employee), len(employee))) for em in employee: print(em) # __add__ 数学运算使用 class Vector(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other_instance): vec = Vector(self.x + other_instance.x, self.y + other_instance.y) return vec def __str__(self): return 'x is %s y is %s' % (self.x, self.y) vector1 = Vector(1, 2) vector2 = Vector(11, 12) print(vector1+vector2) class Num(object): def __init__(self, x): self.x = x def __abs__(self): return abs(self.x) num1 = Num(-99) print(abs(num1))
false
f2f5adc6afdf7b8532f78499fc83cc1c55625840
HackSek/learning-python-programs
/16_martial_arts.py
600
4.125
4
martial_arts_dictionary = dict() while True: martial_art = input('What martial art would you like to add? ') origin = input('Where has it originated from? ') martial_arts_dictionary[martial_art] = origin prompt = input('Would you like to add another martial art? (y/n) ') if prompt == 'n': break else: continue def count_countries(variable): origins = list(variable.values()) for origin in set(origins): count = origins.count(origin) print(f'{origin} has been mentioned {count} times') count_countries(martial_arts_dictionary)
false
0de7ff1beff6bad0f9f9d5d23f18fec7906c0793
davjohnst/fundamentals
/fundamentals/stacks/sort_using_stack.py
1,184
4.46875
4
#!/usr/bin/env python class StackSort(object): """ Write a program to sort a stack in ascending order with the biggest items on top. You may use additional stacks to hold items, but can't use other data structures. Your api: push, pop, peek, isEmpty ex: bottom of stack ----> top of stack [3, 4, 1, 5, 2] sorts to [1, 2, 3, 4, 5] """ @staticmethod def sortStack(input_stack): output_stack = [] tmp = [] while input_stack: next = input_stack.pop() if len(output_stack) == 0 or output_stack[-1] <= next: output_stack.append(next) else: while len(output_stack) > 0: if output_stack[-1] > next: t = output_stack.pop() tmp.append(t) else: break output_stack.append(next) while len(tmp) > 0: output_stack.append(tmp.pop()) return output_stack def main(): stack = [3, 4, 1, 5, 2] print StackSort.sortStack(stack) if __name__ == "__main__": main()
true
d09f170822ba743da05ee42739b4adab2ad289d4
dmitriyanishchenko/tms-z15-pub
/src/hw/hw06/task_02.py
318
4.125
4
# Дано число. Найти сумму и произведение его цифр. summ = 0 multi = 1 number = input('number: ') if number.isdigit(): for digit in number: int_digit = int(digit) summ += int_digit multi *= int_digit print(f'sum is {summ}') print(f'multi is {multi}')
false
84eec65236aacecedee2e484356e05d89e9a8a1b
kuroiiie/pythonstuff
/Vector.py
1,733
4.3125
4
#------------------------------------------------------------------------------ # Chloe Jiang # cfjiang@ucsc.edu # programming assignment 7 """ This module provides functions to perform standard vector operations. Vectors are represented as lists of numbers (floats or ints). Functions that take two vector arguments may give arbitrary output if the vectors are not compatible, i.e. of the same dimension. """ #------------------------------------------------------------------------------ # import standard library modules #------------------------------------------------------------------------------ # function definitions #------------------------------------------------------------------------------ import math import random rand = random.Random() def tester(u, v): if (len(u) == len(v)): return True return False def add(u, v): if (tester(u, v) == True): x = [0]*len(v) for i in range(len(v)): x[i] = u[i] + v[i] return x def negate(u): x = u[:] for i in range(len(u)): x[i] *= -1 return x; def sub(u, v): if (tester(u, v) == True): return add(u, negate(v)) def scalarMult(c, u): x = u[:] for i in range(len(u)): x[i] *= c return x def zip(u, v): if (tester(u, v) == True): x = [0]*len(v) for i in range(len(v)): x[i] = u[i]*v[i] return x def dot(u, v): if (tester(u, v) == True): dot = 0 x = zip(u, v) for i in range(len(x)): dot += x[i] return dot def length(u): return math.sqrt(dot(u, u)) def unit(v): x = v[:] for i in range(len(v)): x[i] /= length(v) return x def angle(u, v): if (tester(u, v) == True): return math.degrees(math.acos(dot(unit(u),unit(v)))) def randVector(n, a, b): v = [0]*n for i in range(len(v)): v[i] = rand.uniform(a, b) return v
true
36b8d1f3f3426986df68f6e988b3644588984136
IliaGavrilov/Introduction_to_Computer_Science_and_Programming_Using_Python_3.5
/Function/Keyword_arguments_and_default_values_passing.py
1,569
4.375
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 19 13:24:10 2017 @author: Gavrilov """ def printName (firstName, lastName, reverse): if reverse: print(lastName+", "+firstName) else: print(firstName, lastName) printName('Eric', 'Grimson', True) printName('Eric', 'Grimson', reverse = False) #I could say explicitly #give the binding to the parameter reverse #the value False. printName(firstName = 'Eric', lastName = 'Grimson', reverse = True) #I could similarly for any of the parameters in the invocation #literally say the parameter followed by an equal sign #and the value that I want. def printName (firstName, lastName, reverse = False): #I can change the definition of my function #to give a default value to one of the parameter if reverse: print(lastName+", "+firstName) else: print(firstName, lastName) printName('Eric', 'Grimson') #if I call the function without an explicit parameter passed in, #the default holds true #In this case, I'm going to assume that reverse is false printName('Eric', 'Grimson', True) #if I want to change the value of that, #I need to give it an explicit value #to overwrite the default value.
true
0d2cfe6e9a6230bda80a489624e8481c939434b5
IliaGavrilov/Introduction_to_Computer_Science_and_Programming_Using_Python_3.5
/Integer_Odd_Even_check.py
262
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 5 13:40:21 2017 @author: Gavrilov """ x = int(input('Enter an integer: ' )) if x % 2 == 0: print ('') print ('Even') else: print ('') print ('Odd') print ('Done with conditional')
false
2fb642257b52c5e102acd2af04fab416dbf1c45d
IliaGavrilov/Introduction_to_Computer_Science_and_Programming_Using_Python_3.5
/Object_oriented_programming/Class_definition_Coordinate_example.py
2,195
4.15625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 18 22:28:27 2017 @author: Gavrilov """ class Coordinate(object): #keyword class is going to tell us we're about to create the definition of a new class #Coordinate is a name each class definition is going to take one argument, #which is the parent class. #Object as argument tells that class inherit from the underlying object class of Python def __init__(self, x, y): #data attributes #immediately below that, I'm going to define the attributes of this class. #first thing is define how I actually create instances of this object. #special method to create an instance is keyword __init__ #self is first parameter of an argument self is going to refer to an instance of the class #x, y parameters going to create instances the initial data. self.x = x #And the way we glue them together is we're going to actually create bindings for the names #x and y to the values passed in. self.y = y #when we actually invoke the creation of an instance #this will bind the variables x and y within that instance to the supplied values. #This is typically the first method that we have inside of a class definition. #Because we have to say, how am I going to create instances of this class? c = Coordinate(3,4) #I can now create an instance. #creates a new object of type Coordinate and pass in 3 and 4 to the __init__ method origin = Coordinate(0,0) #each time I invoke coordinate, the name of a class, it's creating a new instance. #it's calling that init method, and using that to create local bindings. print(c.x) #print out the x-value value associated with c. C dot x is then interpreted as saying the following. #Get the value of c. Oh, that's a frame. And then inside of that frame, look up the value associated with x. print(origin.x)
true
701863a506d4337cf6d5ec1a93ff06e7abf7111b
IliaGavrilov/Introduction_to_Computer_Science_and_Programming_Using_Python_3.5
/Object_oriented_programming/Getters_and_setters_Integers_example.py
2,656
4.40625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 8 14:50:11 2017 @author: Gavrilov """ #we don't want to directly manipulate the internal representation of an object. #We'd like to separate the use of the object from what's inside of it. #And those getters and setters nicely do that. It says any time I want to access something #inside an object, let me use the method that gets that part of the object out. #representational invariant example #I need two pieces. Data representation (class?) and I need an interface (methods? frame?). class intSet(object): def __init__(self): self.vals = [] #initially the set is empty #I don't want to have to go and check, do I have more than one instance inside the object? #I want it to be the case that as I add elements to this set, I'm always making sure #that there's never more than one particular version of that integer inside of that set. def insert(self, e): #I can insert things into the set. #And here's where I'm going to enforce the representational invariant. if not e in self.vals: #when I want to insert a particular element into an instance of an IntegerSet, #I'm going to first say, is that element inside the list? self.vals.append(e) def member(self, e): #I want to check if something's inside the list. #I can simply say, return e in self.vals. return e in self.vals def remove(self, e): #I need to be able to remove an element from a set. try: self.vals.remove(e) except: #can use exseption to catch attempt to remove nonexistent element raise ValueError(str(e) + " element not found") def __str__(self): self.vals.sort() result="" for e in self.vals: result = result + str(e) + "," return "{" + result[:-1] + "}" s = intSet() print(s) s.insert(3) s.insert(4) s.insert(3) #I'm going to insert 3 again, because I have a short memory #and I've forgotten I've already done that. print(s) print(s.member(3)) # I could check to see if something is in the list. print(s.member(6)) s.remove(3) #I can remove something. #this is a example of a method we defined #which is similar to operation 'lst.remove(val)', but difference is that #we created our method by ourselves and use it as primitive s.insert(6) #I'm simply using those built in methods to manipulate that set. print(s) #s.remove(7)
true
05e9309ba2b5990781a3c004ce9ee4d1c5ee9388
JohnKearney2020/june2021Cohort
/Python/to_do_json.py
1,663
4.15625
4
import json # todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] # load existing value(s) from the json file into a variable called 'todos' with open('todos.json', 'r') as to_do_list: todos = json.load(to_do_list) def print_todos(): count = 1 for todo in todos: print(f"{count}: {todo}") count += 1 while True: print(""" Choose an option: 1. Print to-dos 2. Add to-dos 3. Remove to-dos 0. Quit """) user_choice = input('') if user_choice == '1': # print current to dos count = 1 for todo in todos: print(f"{count}: {todo}") count += 1 elif user_choice == '2': # add new item new_item = input('What do you want to add?: ') todos.append(new_item) # update the json file with the new to-do list with the new item with open('todos.json', 'w') as to_do_list: # dump the contents of our todos list into to_do_list json.dump(todos, to_do_list) # # if we wanted to print what we just added to our json file # with open('todos.json', 'r') as to_do_list: # data = json.load(to_do_list) # print(data) elif user_choice == '3': # remove an item from our to-do list delete_index = int(input('which item would you like to remove?: ')) print_todos() #print out our current to do list del todos[delete_index - 1] # - 1 b/c our list is zero indexed # update the json file with the new to-do list that no longer has the item we just deleted with open('todos.json', 'w') as to_do_list: json.dump(todos, to_do_list) # exit the program loop elif user_choice == '0': break
true
b0a90c855b78e69508c4049cf70c10b0433bbf9f
JohnKearney2020/june2021Cohort
/Python/mod_lists.py
968
4.28125
4
todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] def print_todos(): print('------ Todos ------') count = 1 for todo in todos: print(f"{count}: {todo}") count += 1 print('-------------------') while True: print(""" Choose an option: 1. Print Todos 2. Add Todo 3. Remove Todo 0. Quit """) user_choice = input('') # print current todos if user_choice == '1': print_todos() # add new item elif user_choice == '2': new_item = input('What do you want to add? ') todos.append(new_item) # delete a todo elif user_choice == '3': print_todos() # ask user which item to delete delete_index = int(input('Which item would you like to delete? ')) # delete item from list by user provided index del todos[delete_index - 1] # exit the program loop elif user_choice == '0': break
true
5eebac182e50cf470d562ad113dcdfd661ffb631
himanshu98-git/python_notes
/nstd clss SIR.py
2,640
4.84375
5
#Today we start with Nested class and its all functioning... #We can declare a class inside the another class,such type of classes are called Inner class. #If without existing one type of object there is no chance of existing another type of object. """ class Outer: def __init__(self): print("Hello I am Constructor and belong to outer class") def out(self): print("I am method from outer class") class Inner(): def __init__(self): print("Hello I am From Inner Class Constructor") def inn(self): print("Inner class Method") o = Outer() #Here o is a reference variable o.out() Outer().out() #Outer.out() #it is not possible print("=====================inner class Calling========================") f = Outer.Inner() f.inn() Outer().Inner().inn() """ """ #Examples related to nested class....... class Human: def __init__(self): self.n = "NIshant" self.DOB =self.Dob() def disp(self): print("Name===",self.n) class Dob: def __init__(self): self.dd = 1 self.mm = 3 self.yy = 2015 def disp(self): print("Date of birth==={}/{}/{}".format(self.dd,self.mm,self.yy)) H = Human() H.disp() x = H.DOB x.disp() """ class Outer: def __init__(self,name,age): self.name = name self.age = age def data(self,x,y): #In stance method print("The value of x and y") print("x==",x,"\nY==",y) def data1(): print("Name==",self.name,"\nAge==",self.age) data1() class Inner(): def __init__(self,name,age): self.n= name self.a = age def disp(self,x,y): print("The value of x and y") print("x==",x,"\nY==",y) def disp1(): print("Innerr classs nested method===",self.n,self.a) disp1() #for outer z = Outer("NIshant",78) z.data(45,65) print("******************Innerr************") t = Outer("Nishant",25).Inner("Rahul",15).disp(45,65) Outer.Inner("Ram",12).disp(14,63) """ z.Inner("Himanshu",22).disp(45,65) """
true
77edbac23617f4f4415c15a68728f09ea52b9f1e
himanshu98-git/python_notes
/lcl vrIABLE.py
1,024
4.15625
4
#todays topic is local variable...... #Sometimes to fullfill a temporary of a programmer, we can declare variable.These type of variable consider as a local variable #local varibale create at a time of method execution and destroy once the method will be completed. #local var cant be access from the outside of method. """class Abc: def m1(self): a="local" print("here a is ",a) def m2(self): b="local" print("here bb is ",b) c=Abc() print(c) print(c.m1) print(c.m1())""" #=======================================Methods================= #instance method #static method #class method #Instance mthod--- if we are using instance variable then such type of method are consider as instance method.it can be one or more than one.when we see self than it is instance emthod class Test: def m1(self): self.a=12 self.b=78 def m2(self): print(self.a) print(self.b) t=Test() print(t.__dict__) t.m1() print(t.m2())
true
e85a8184ce4b51c69c9ec60217106b6ce98e48bf
himanshu98-git/python_notes
/cls_objct_cnstrctr.py
2,768
4.65625
5
# Today we discuss about class,object and consturctor # how constructor help class to create an object """ class My: def hello(self,name): print("Good Morning",name) My().hello("Himanshu") #if we want to create an object from the class then constructor to help us. #a constructor is a special type of method ewhci is used to intialize the instance member of the class #constructor use to initializing the valuue to the data member and member function #constuctor use to provide memory to data #construtor name is same as class name #it automatically called when an object of any class is created #consturctor is optional and if we not create it then PVM(python virtual machine)called it by default. #EX: class add: def sum(self,a,b): #self connect the constructor(constructor level variable) print("sum====",a+b) add().sum(6,7)#there is 3 arguments ,constructor is bydefault thats y we use self to connect the constructor #why we use self? it means it holds itself we can use anything instead of self class add1: def __init__(self,a,b): print(a+b) add1(12,32) #Constructor and method(function)---->>> #method>> any function which is present in the class consider as a mthod #name of method will be anythiing #per object method can be call any number of time #inside method we write require logic. #constructor--->>> #constructor is a special type of method #its name always be __init__ #it called itself automATICALLY when class convert into object #constructor always be execute once per object #inside con. we declare data requirement """ class test: def __init__(self,a,b): #these are temporary variable # we can use anythind insted of self even name also. self.a1=a self.b1=b #constructor level variable print(self.a1,self.b1) def sum(self): print("sum=====",(self.a1+self.b1)) test(5,9).sum() """s #__init__ is a constructor #here we see using class we create different location class My: def __init__(self): print("Consturctor working") def my(self): print("member") t=My() #t is reference variable t1=My() t2=My() t.my() My.my("Himanshu") print(id(t)) print(id(t1)) #there is different object in each class thats why id is different """ #now we see the working of self in each object. class My: def __init__(self): print("Consturctor working") print("self====",id(self)) def my(self): print("member") t=My() #they are efrence var. also object t1=My() t2=My() print(id(t)) print(id(t1)) print(id(t2)) t.my() #instance variable and instance method........ read((())))))
true
3142cb73bba228dd23e4266539f8cc688df77430
Hathawam3812/CTI110
/M6T2_FeetToInches_Hathaway.py
871
4.40625
4
# CTI110 # M6T2 Feet To Inches # Hathaway # 10 Nov 2017 # This defines the function to convert feet to inches. def feet_to_inches(): # This asks the user to input a distance in feet to be converted to inches. feet = int(input('Enter distance in feet. ')) # We will now multiply the integer input by 12 to assign to inches. inches = feet * 12 # The returned values will be in inches and in feet return inches, feet # The main function will call on the feet_to_inches function def main(): # This line will call distance and feet from the feet_to_inches function distance, feet = feet_to_inches() # The distance of feet will be printed, as will the distance in inches. print('The distance of ', feet, ' foot/feet is ', distance, ' inches.') # Calls the main() function to execute. main()
true
0fa2a37532c8f67b23b0e44ec5b45cd6f53ad57e
skytreader/pydagogical
/clrs_3e/c8_linear_sorting/bucket_sort.py
2,785
4.1875
4
#! /usr/bin/env python3 import math import unittest """ Implementation of bucket sort from CORMEN. Algorithm self-description: The input is assumed to be numbers in the half-open interval [0, 1). They are assumed to be uniformly-distributed. Bucket sort works by creating n buckets where n is the number of input items. This will equally divide the range [0, 1) into smaller ranges. By the assumption that the input is uniformly distributed, we place each number into their respective bucket. We sort each bucket (shouldn't contain too many items) individually and then concatenate their results. Note that if the uniform distribution assumption does not hold, the algorithm degenerates to the runtime of the sorting algorithm we use to sort each bucket. Interesting note from [CORMEN3], p204: T(n) = \Theta(n) + \sum_{i=0}^{n-1}O(n_i^2) Equation 8.1: E[T(n)] = \Theta(n) + \sum_{i=0}^{n - 1}O(E[n_i^2]) Even if the input is not drawn from a uniform distribution, bucket sort may still run in linear time. As long as the input has the property that the sum of the squares of the bucket sizes is linear in the total number of elements, equation (8.1) tells us that bucket sort will run in linear time. """ def insertion_sort(numlist): """ Sorts the list using insertion sort. Needed as an auxiliary procedure in bucket_sort. """ for i in range(1, len(numlist)): insert(numlist, i) return numlist def insert(numlist, sorted_limit): """ sorted_limit is the first index of the unsorted part of the list. So if sorted_limit == len(numlist), the whole list is assumed to be sorted. """ if sorted_limit < len(numlist): for i in range(sorted_limit): if numlist[sorted_limit] < numlist[i]: for j in range(i, sorted_limit): numlist[j], numlist[sorted_limit] = numlist[sorted_limit], numlist[j] return numlist def bucket_sort(numlist): """ Implementation of bucket sort. """ limit = len(numlist) buckets = [[] for i in range(limit)] for val in numlist: buckets[math.floor(limit * val)].append(val) ordered_list = [] for b in buckets: insertion_sort(b) ordered_list.extend(b) return ordered_list class FunctionsTest(unittest.TestCase): def test_bucket_sort(self): diagram_example = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] self.assertEqual(bucket_sort(diagram_example), insertion_sort(diagram_example)) exercise_example = [0.79, 0.13, 0.16, 0.64, 0.39, 0.20, 0.89, 0.53, 0.71, 0.42] self.assertEqual(bucket_sort(exercise_example), insertion_sort(exercise_example)) if __name__ == "__main__": unittest.main()
true
d0fdf0bde7081deebc94df0696748c002c558a60
tommoralesmorin/third_travis_example
/fibonacci.py
608
4.25
4
import sys def fibonacci(n): """ Calculate the Fibonacci number of the given integer. @param n If n <= 0 then 0 is assumed. @return fibonacci number. """ if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def print_usage(): """ Print usage information. """ print("Usage: python fibonacci.py N") print(" where N >= 0") if __name__ == '__main__': if (len(sys.argv) < 2): print_usage() exit(1) n = int(sys.argv[1]) if (n < 0): print_usage() exit(2) fib = fibonacci(n) print("fibonacci(%d) = %d" % (n, fib))
true
24307b578a73b8b6116d8826a04c91615eb376b3
hari819/python_related_courses
/00.FullSpeedPython/06.Classes/02.getterMethods.py
452
4.125
4
class Rectangle: def __init__(self, x1, y1, x2, y2): # class constructor if x1 < x2 and y1 > y2: self.x1 = x1 # class variable self.y1 = y1 # class variable self.x2 = x2 # class variable self.y2 = y2 # class variable else: print("Incorrect coordinates of the rectangle!") # write your code here def width(self): return abs(self.x2 - self.x1) def height(self): return abs(self.y2 - self.y1)
true
fca92a9c1bd0bd61f2a53766dd2dfc79c4414c78
bikash1212000/Python-homework
/Assingement 2/Q7.py
482
4.3125
4
# WAP to input 3 numbers and find the second smallest. import re x, y, z = input("Enter three numbers: ").split() if (re.match('^[+-]?([0-9]*[.])?[0-9]+$',x) and re.match('^[+-]?([0-9]*[.])?[0-9]+$',y) and re.match('^[+-]?([0-9]*[.])?[0-9]+$',z)): if x<y<z or z<y<x: print(y,"is the second smallest") elif y<z<x or x<z<y: print(z,"is the second smallest") else: print(x,"is the second smallest") else: print("please enter valid input")
false