blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
d13de094d5bf439de91ef83cc78e2c1fc750a1d8
sanjidahw/python-bootcamp
/Week 1/Day 2/lists.py
959
4.1875
4
my_first_list = [2, 4, 6, 8] print(my_first_list[2]) length = len(my_first_list) print("the length of this is: ", length) for index in range(0, len(my_first_list)): element = my_first_list[index] print(element) print("Original List: ", my_first_list) my_first_list.append(10) print("List after Append: ", my_first_list) # To-do: make a list of even numbers up to 12 (inclusive) evens_list = [] for num in range(1,13): if num % 2 == 0: evens_list.append(num) print("List if even numbers up to 12: ", evens_list) evens_list.clear() print("List after clearing: ", evens_list) #Using pop print("list before popping an element: ",evens_list) for i in range(0,len(evens_list)-1): if evens_list[i] == 10: index_of_ten = i ten = evens_list.pop(i) print("List after popping an element", evens_list) print("The value of ten = ", ten) evens_list.insert(index_of_ten, ten) print("Using insert, to put the 10 back: ", evens_list) print(sorted(evens_list))
false
4a6caafad025f117dcde3d67da1e8da181b102d1
sanjidahw/python-bootcamp
/Week 1/Day 1/loops.py
312
4.125
4
counter = 0 while counter <= 10: print(counter) counter += 1 # range(start, stop, increment) # includes the start, does not include the stopping number print("using the inputs to range()") for number in range(0,5,1): print(number) print("using one input to range()") for number in range(5): print(number)
true
a8ab0e47061f2c9f26a3577ab2f613b9d66cd2d3
RemonComputer/hacker_rank_problems
/python/designer_door_mat.py
910
4.21875
4
# Link: https://www.hackerrank.com/challenges/designer-door-mat/problem def draw_upper_part_lock_line(m, line_idx): number_of_or_sign = 1 + 2 * line_idx intermidiate_or_signs = '..'.join(['|'] * number_of_or_sign) middle_locks = '.' + intermidiate_or_signs + '.' lock_line = middle_locks.center(m, '-') print(lock_line) def draw_lock_map(n, m): upper_lock_map_height = n // 2 # drawing upper lock map lines for line_idx in range(upper_lock_map_height): draw_upper_part_lock_line(m, line_idx) # drawing the Welcome message print('WELCOME'.center(m, '-')) for line_idx in range(upper_lock_map_height - 1, -1, -1): draw_upper_part_lock_line(m, line_idx) # Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == '__main__': tokens = input().split() n = int(tokens[0]) m = int(tokens[1]) draw_lock_map(n, m)
false
341e1ef288d4cc92e435399d224d2a7ada282f9c
Innocent2240/calculations
/calculation_Operation.py
905
4.25
4
print("Choose your calculation operator") print("1: ADDITION") print("2: SUBTRACTION") print("3: MULTIPLICATION") print("4: DIVISION") calculation = input() if calculation == "1": value1=input("Enter first value: ") value2 = input("Enter second value: ") print("The sum is " + str(int(value1) + int(value2))) elif calculation == "2": value1=input("Enter first value: ") value2 = input("Enter second value: ") print("The difference is " + str(int(value1) - int(value2))) elif calculation == "3": value1 = input("Enter first value: ") value2 = input("Enter second value: ") print("The product is " + str(int(value1) * int(value2))) elif calculation == "4": value1 = input("Enter first value: ") value2 = input("Enter second value: ") print("The results is " + str(int(value1) / int(value2))) else: print ("Error Invalid inputs")
true
5136c6d0b4a0fb45df849944d475d673e406a0b3
qetennyson/CThink2018-LessonPlans
/tuples_ex.py
1,323
4.65625
5
''' Lists are great for storing items we may want to change throughout the life of a program. We can also modify lists, they are mutable! However, there are situations where we may want a data structure that cannot be modified. An immutable data structure! Hello tuples.''' # here's a basic tuple that we might use for coordinates coordinate = (7,4) # we use parentheses to declare a tuple, however we can use the familiar # brackets to access the tuple values at their index. print(coordinate[0]) print(coordinate[1]) # if we attempt this: # coordinate[0] = 9 # we will most definitely receive a "tuple" object does not support item assignment error. # to circumvent this, you can declare a new tuple. coordinate = (10,12) # let's create a quick exotic car rental program that exemplifies tuples, and use a for loop, just as we can with a list, to iterate over these tuples. exotic_cars = ('Ferrari', 'Lotus', 'Aston Martin', 'Maserati', 'Porsche') car_rental_cost = (120, 70, 120, 70, 90) for car in exotic_cars: print(car) print ("A " + exotic_cars[0] + " is $" + str(car_rental_cost[0]) + " per day") # we decide that we are no longer going to rent Maseratis exotic_cars = ('Ferrari', 'Lotus', 'Aston Marton', 'Porsche') car_rental_cost = (120, 70, 120, 90) for car in exotic_cars: print(car)
true
f008853f6a2f3491a93297874181c1bf59a21506
rybread32/cmpt120straub
/calc_functions.py
1,696
4.34375
4
#calculator.py #Acts as a Working Calculator for basic arithmetic and PEMDAS #Created by Ryan Straub #3/5/19 #def main() #Where you insert a formula. #equation = input("Insert Problem: ").split(" ") #Is what you inserted just a number or not? #if len(equation)<=2: #print("This is not a formula.") #else: #print(pemdas(equation)) def hasPrdDv(equation): # Checks for addition and subtraction in list then puts them in a list. if "*" in equation or "/" in equation: return True return False def process(equation,i): # Checks for addition and subtraction in list then puts them in a list. if equation[i]== '*': result = float(equation[i-1]) * float(equation[i+1]) elif equation[i]== '/': result = float(equation[i-1]) / float(equation[i+1]) elif equation[i]== '+': result = float(equation[i-1]) + float(equation[i+1]) elif equation[i]== '-': result = float(equation[i-1]) - float(equation[i+1]) del equation[i-1:i+2] equation.insert(i-1,str(result)) #Prints Result #print(result) def pemdas(equation): i = 0 result=0; #Checks if there is division or multiplication. while hasPrdDv(equation): if equation[i]=='*' or equation[i] == '/': process(equation,i) else: i = i + 1 i=0 #Checks if there is addition or subtraction. while len(equation)>1: if equation[i]=='+' or equation[i]== '-': process(equation, i) else: i = i + 1 return float(equation[0])
true
b4eae0dc93b5f8d007c550727cdd8e210eafaa36
ilanasufrin/dsa
/dynamicProgramming/uniquePaths.py
1,153
4.28125
4
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. How many possible unique paths are there? """ class Solution(object): def unique_paths(self, m, n): """ :type m: int :type n: int :rtype: int """ return self.helper(0, 0, m, n, {}) def helper(self, i, j, m, n, cache): if (i,j) in cache: return cache[(i,j)] # If we have reached the bottom, there is only 1 path if i == m-1: return 1 # If we have reached the right side, there is only 1 path if j == n-1: return 1 num_paths = 0 num_paths += (self.helper(i+1, j, m, n, cache)) + (self.helper(i, j+1, m, n, cache)) cache[(i,j)] = num_paths return num_paths if __name__ == '__main__': solution = Solution() print(solution.unique_paths(100,100)) #should be 22750883079422934966181954039568885395604168260154104734000
true
b95a94ded927b4cbc3cd1e0ab8da0e63ff5dac12
Ayamin0x539/Python-Homework
/Exercise_1.7_rockpaperscissors.py
1,212
4.375
4
#Exercise 1.7 - Rock, Paper, Scissors ''' In this exercise, you are going to practice using conditionals (if, elif, else). You will write a small program that will determine the result of a rock, paper, scissors game, given Player 1 and Player 2s choices. Your program will print out the result. ''' #constants to print p1win = "Player 1 wins." p2win = "Player 2 wins." while 1: print "Let's play rock, paper, scissors." p1 = raw_input("Player 1 chooses... ") p2 = raw_input("Player 2 chooses... ") if (p1 == p2 and (p1 == "rock" or p1 == "paper" or p1 == "scissors")): print "Tie." elif (p1 == "rock"): if (p2 == "scissors"): print p1win elif (p2 == "paper"): print p2win else: print "Invalid input." elif (p1 == "scissors"): if (p2 == "paper"): print p1win elif (p2 == "rock"): print p2win else: print "Invalid input." elif (p1 == "paper"): if (p2 == "rock"): print p1win elif (p2 == "scissors"): print p2win else: print "Invalid input." else: print "Invalid input." print
true
602382747b1729970edc2e18b17fcdcfacc3b4ac
pshimanshu/AdvPython
/day_5/classes/special_methods.py
903
4.21875
4
# special methods or magic methods or dunder methods # __init__ -> constructor -> to initialize all intance attributes # __str__ -> string representation of the class # class Employee: # def __init__(self, first, last, address, phone, salary): # self.first = first # self.last = last # self.address = address # self.phone = phone # self.salary = salary # def fullName(self): # return "{} {}".format(self.first, self.last) # def __str__(self): # return "{} - {}".format(self.fullName(), self.phone) # def __add__(self, other): # return self.salary + other.salary # def __len__(self): # return len(self.fullName()) # emp1 = Employee("sam", "white", "delhi", 789678, 100000) # emp2 = Employee("john", "wick", "us", 567345, 200000) # print(emp1.fullName()) # print(emp1) # print(emp1+emp2) # print(len(emp1))
true
cbe63efe5bbf50c149dba5bfbf2d8f52ece79179
pshimanshu/AdvPython
/day_4/db_programming/file1.py
941
4.15625
4
# Python with SQL database def takeInput(): arr = [] arr.append(input("Enter name: ")) arr.append(input("Enter phone number: ")) arr.append(input("Enter address: ")) return arr import sqlite3 # create a datbase object, if doesnt exist, else access it db = sqlite3.connect("DB1.sqlite") # create a table try: db.execute("create table student (name text, phone text, address text)") except: pass # insert rows db.execute("insert into student values('sam', '998877', 'delhi')") db.execute("insert into student values('john', '786453', 'pune')") # list1 = takeInput() # db.execute("insert into student values (?,?,?)",list1) db.commit() # -> saves data # extract data from database cursor = db.cursor() cursor.execute("select * from student") # name = input("Whose data do you want to get: ") # cursor.execute("select * from student where name = ?", [name]) print(cursor.fetchall()) cursor.close() db.close()
true
9d7914e8b2225e21359fdd62217e1fc93be08b58
satishp962/40-example-python-scripts
/14.py
306
4.3125
4
file = open('file_write.txt', 'r') print("File contents: ") for i in file: print(i) file = open('file_write.txt', 'a') str = input("Enter the text to append to the file: ") file.writelines(str) file = open('file_write.txt', 'r') print('File contents after appending: ') for i in file: print(i);
true
0ba01a37bde108aca0775579b2e7cfe1711624f8
satishp962/40-example-python-scripts
/4.py
274
4.15625
4
num = int(input("Enter an integer: ")) root = None for i in range(num): if i*i == num: root = i if root is not None: pwr = None for i in range(1, 6): if root**i == num: pwr = i print("Root:", str(root) + ", Power:", str(pwr))
false
704a722c87fc658cc6cd3d406a3eea15acf10176
satishp962/40-example-python-scripts
/22.py
1,021
4.21875
4
import abc class Car: def __init__(self, make, model, price): self.make = make self.model = model self.price = price def __str__(self): return "Make: " + self.make + ", Model: " + self.model + ", Price: " + str(self.price) @abc.abstractmethod def show_details(self): print("This calls the base class") class Maruti(Car): def __init__(self, model, price): Car.__init__(self, "Maruti", model, price) def __str__(self): return super(Maruti, self).__str__() def show_details(self) : print ("You are in Sub Class - 1 ") class Santro(Car): def __init__(self, model, price): Car.__init__(self, "Hyundai", model, price) def __str__(self): return super(Santro, self).__str__() def show_details(self) : print ("You are in Sub Class - 2") maruti = Maruti("WagonR", 4500000) santro = Santro("Santro", 3500000) print(maruti) print(santro) maruti.show_details() santro.show_details()
false
ee71aeb05da5e440703ea42b3bdf311568fc9560
Jaden5672/Python_Coding
/leap.py
319
4.1875
4
year=input("Type in any year!") year=int(year) if year%4==0: if year%100==0: if year%400==0: print("This year is a leap year!") else: print("This year is not a leap year!") else: print("This is a leap year!") else: print("This is not a leap year!")
false
cd39cce6b84c9126bd0c3635ac9aee4819a2bd10
Jaden5672/Python_Coding
/Miles_Km.py
485
4.1875
4
pick=input("Type in A to convert miles to kilometers,or type in B to convert kilometers to miles:") pick=pick.upper() if pick=="A": miles=input("Enter any number of miles to convert to kilometers") miles=float(miles) km=miles*1.609 print(km) elif pick=="B": kilometers=input("Enter any number of kilometers to convert to miles") kilometers=float(kilometers) mile1=kilometers/1.609 print(mile1) else: print("Invalid operation!Try again")
true
91da38c68e062f26de4ec2190ee625134461b18c
module6create2020/tutorial08template
/exercises/example.py
482
4.28125
4
"""An example illustrating a few aspects of inheritance""" class Alice: def __init__(self, n): self.value = n def yell(self): return "Hei" def get_value(self): return self.value class Bob(Alice): def __init__(self, n): Alice.__init__(self, n) def yell(self): return "Ho" if __name__ == "__main__": a = Alice(4) b = Bob(3) a_list = [a, b] for p in a_list: print(p.yell(), p.get_value())
false
90a3020ea45bd4d51164bdaff21813ae02bb6099
mmore21/ds_algo
/python/lib/bubble_sort.py
703
4.1875
4
""" Topic: Bubble Sort Category: Algorithm Author: Mason Moreland Runtime: O(n^2) """ def bubble_sort(arr): """ Passes over a list comparing two elements and repeats with a smaller, sliced off end of the list each iteration until sorted. """ for i in range(len(arr)): for j in range(len(arr) - i - 1): # swap if left element is greater than right element if (arr[j] > arr[j+1]): tmp = arr[j] arr[j] = arr[j+1] arr[j+1] = tmp return arr def main(): """ Driver function of an example bubble sort. """ print(bubble_sort([5,3,2,6,1,8])) if __name__=="__main__": main()
true
1610d166715de41a88683656df02011d3ac7453e
thommms/python-projects
/check if a number is in a given range.py
313
4.21875
4
#to check if a number is in a given range start=int(input("enter the beginning of the range: ")) end=int(input("enter the end of the range:")) number=int(input("enter the number to check: ")) if number not in range (start,end): print ("\n",number," not in range") else: print ("\nnumber is in the range")
true
77f444f9992ef92db3d961768d6109343c7afa2f
santifinland/CursoTecnicasAnaliticasConSpark
/python/circle/circle_while.py
701
4.25
4
# -*- coding: utf-8 -*- # Programa de cálculo de circunferencia de un círculo from math import pi def calcula_circunferencia(r): return 2 * pi * float(r) def is_numeric(x): try: float(x) return True except: return False print("Programa de cálculo de la circunferencia de un círculo dado su radio") radio = raw_input("¿Radio del círculo? ") print(radio) if is_numeric(radio) == True: i = 0 while i < int(float(radio)): # while <boolean>: circunferencia = calcula_circunferencia(i) print("Circunferencia para el círculo de radio {}: {}".format(i, circunferencia)) i = i + 1 else: print("Ese radio no es un número")
false
a906b608b4bb453d19950b0ac63605d0f0d5c3f1
santifinland/CursoTecnicasAnaliticasConSpark
/python/circle/circle_fun.py
535
4.21875
4
# -*- coding: utf-8 -*- # Programa de cálculo de circunferencia de un círculo from math import pi def calcula_circunferencia(r): # Definición de una función con parámetros return 2 * pi * r # Uso de sentencia return print("Programa de cálculo de la circunferencia de un círculo dado su radio") radio = input("¿Radio del círculo? ") circunferencia = calcula_circunferencia(radio) # Llamada a función con parámetros print("Circunferencia para el círculo de radio {}: {}\n".format(radio, circunferencia))
false
933940c1f977d198dc54044ee709280c088e5b34
hfyblnh/WorkSpaces
/JetProjects/PyCharm/learn-python3/samples/advance/do_iter.py
2,428
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import Iterable from collections import Iterator d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for k in d: print(k) for v in d.values(): print(v) for k, v in d.items(): print(k, v) for ch in "2ez4rtz": print(ch) print(isinstance('abc', Iterable)) print(isinstance(1234, Iterable)) print(isinstance([1, 2, 3, 4], Iterable)) for i, value in enumerate(['A', 'B', 'C']): print(i, value) it = iter([1, 2, 3, 4, 5]) print(next(it)) print(next(it)) print(next(it)) print(next(it)) print(next(it)) # Iterable and Iterator print(isinstance([], Iterable)) print(isinstance({}, Iterable)) print(isinstance((), Iterable)) print(isinstance([], Iterator)) print(isinstance({}, Iterator)) print(isinstance((), Iterator)) # 生成器都是Iterator对象 print(isinstance((x for x in range(1, 11)), Iterator)) # iter()函数把Iterable变成Iterator print(isinstance(iter([]), Iterator)) print(isinstance(iter({}), Iterator)) print(isinstance(iter(()), Iterator)) # 这是因为Python的Iterator对象表示的是一个数据流, # Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。 # 可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据, # 所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。 # Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。 # 小结 # 凡是可作用于for循环的对象都是Iterable类型; # 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列; # 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。 # Python的for循环本质上就是通过不断调用next()函数实现的,例如: for x in [1, 2, 3, 4, 5]: print(x) # 实际上完全等价于: # 首先获得Iterator对象: it = iter([1, 2, 3, 4, 5]) # 循环: while True: try: # 获得下一个值: x = next(it) print(x) except StopIteration: # 遇到StopIteration就退出循环 break
false
d770deaf2335fb6a54a6205e74fe37c1e350afc9
shirazh7/caesarCipher
/cipher.py
2,153
4.25
4
# This is my Ceaser Cipher encryption program # Written in python def encryption(): print("******** Encryption ********") msg = input("Enter message: ") key = int(input("Enter cipher key (0-25): ")) encrypted_text = "" for i in range(len(msg)): if ord(msg[i]) == 32: # ord() will give the ASCII of the space, which is 32 # chr() will convert the ASCII back to characters encrypted_text += chr(ord(msg[i])) elif ord(msg[i]) + key > 122: # after the Uppercase letters Lowercase end at 122 # subtracting to get a lower integer then adding 96 temp = (ord(msg[i]) + key) - 122 encrypted_text += chr(96+temp) elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96): temp = ord(msg[i]) + key - 90 encrypted_text += chr(64+temp) else: encrypted_text += chr(ord(msg[i]) + key) print("Your Encrypted Message is: " + encrypted_text) main() def decryption(): print("******** Decryption ********") encypt_msg = input("Enter message: ") decrypt_key = int(input("Enter cipher key (0-25): ")) decrpted_message = "" for i in range(len(encypt_msg)): if ord(encypt_msg[i]) == 32: decrpted_message += chr(ord(encypt_msg[i])) elif ((ord(encypt_msg[i]) - decrypt_key) < 97) and ((ord(encypt_msg[i]) - decrypt_key) > 90): # subtract the key from ASCII and add 26 temp = ord(encypt_msg[i])-decrypt_key+26 decrpted_message += chr(temp) elif (ord(encypt_msg[i]) - decrypt_key) < 65: temp = (ord(encypt_msg[i]) - decrypt_key) - 26 decrpted_message += chr(temp) else: decrpted_message += chr(ord(encypt_msg[i]) - decrypt_key) print("Your Decrypted Message is: " + decrpted_message) main() def main(): choice = int(input("1. Encryption\n2. Decrepytion\n3. Quit3\n Pick: ")) if choice == 1: encryption() elif choice == 2: decryption() elif choice == 3: quit else: print("Invalid Input ") main() main()
true
89a5b8dd71ea1b785b4581ec2530047c1e4167ef
brommista/Login_credentials_creator
/login_credentials_creator.py
1,288
4.25
4
import random import string #Ask for User's First name first_name = input("Please enter user's first name: ") #Ask for User's last name last_name = input("Please enter user's last name: ") #defining a function to create username using firstname and lastname def username(fisrt_name, last_name): #Username will consist of first character of first name and complete last name user_name = first_name[0]+last_name return("User's LoginID is " + user_name) print(username(first_name,last_name)) #defining function to generate a random password def password(): #storing lowercase, uppercase, number and symbols in respective variables lowercase_letters = string.ascii_lowercase uppercase_letters = string.ascii_uppercase numbers = string.digits symbols = string.punctuation #storing 8 random charcaters consisting of 2 of each lowercase, uppercase, numbers, symbols password_unshuffled = random.sample(lowercase_letters,2)+random.sample(uppercase_letters,2)+random.sample(numbers,2)+random.sample(symbols,2) #randomly shuffling stored characters random.shuffle(password_unshuffled) #creating a string from list password = "".join(password_unshuffled) return "User's temporary password is: " + password print(password())
true
c09ca07feef647ee737f255e3afd88af685957e6
michaelrbull/weathermantask
/runweathercheck.py
2,838
4.1875
4
### # Import both the list of sunny cities and the corresponding flight numbers # from both the flight and weather program. from weather_services import sunny_cities from flight_services import sunny_flight_num # Prints both lists but tidied up with string concentation. print("Sunny Cities: " + str(sunny_cities)) print("Flight Numbers: " + str(sunny_flight_num)) # Below is User Input Code and Specific City Options. # Currently not being used as it made testing and exception handling awkward. ############################################################################# # Function to ask user which specific city they want to fly to instead of all sunny cities. Runs for loop based on user input and print flight numbers # for that city. '''def specific_city(): print("Ok, what specific city would you like us to check instead?") usercity = input("") print("Great, checking for flight numbers for " + usercity + ".") # An empty list is created to then more the user input data into # (the city they want to travel to)''' '''user_city_list = [] user_city_list.append(usercity) user_flight_number = []''' # This For Loop checks all the cities the user has requested flight data # for, sees if there is a match in the flight fixtures API. If so, it # pulls the flight information through and stores the flight number into # user_flight_number variable. '''try: for city in user_city_list: flight_pull = requests.get("http://localhost:5002/" + city.lower()) flight_info = json.loads(flight_pull.text) for flight in flight_info: user_flight_number.append(flight["flight"]) print("Flight Name: " + str(user_city_list)) print("Flight Numbers: " + str(user_flight_number)) except json.decoder.JSONDecodeError: print('No flights found for ' + usercity + ". Please enter another city.")''' # Function to ask user their name and store in a variable to be used when referencing the user. '''def enter_name(): print("Enter name: ") global newname newname = str(input(""))''' # Function which asks user if they want to see all currently sunny cities and corresponding flight numbers. # runs specific_city function if user says no. '''def flight_num_questions(): print("Hi, " + newname + " do you want to see all currently sunny cities and flight numbers?") global user_input user_input = input()''' # Runs function to ask user their name and to ask what flights do they need. '''enter_name() flight_num_questions()''' # Runs functions based on user input. If user wants sunny cities, it runs sunny cities function. '''if user_input == str("y"): sunnycities_sunnyweather()''' # If user wants wants a specific city, it runs specific_city function. '''elif user_input == str("n"): specific_city()'''
true
51b146b590d9ee041588aa69e8dd0305d69056f1
kimjane93/udemy-python-100-days-coding-challenges
/day-5-password-generator/even-nums.py
708
4.28125
4
# using range function # use for loops with the rnage funciton # good for genrating a range of numbers to loop through # for number in range(a, b): # print(number) # DOES NOT INCLUDE END OF THE RANGE # for number in range(1, 10): # print(number) # out puts 1-9 # if wanted all, would have to make it 1-11 # will default incrment by, otherwise add a third argument determining step number # for number in range(1, 11, 3): # out puts 1, 4, 7, 10 # total = 0 # for number in range(1, 101): # total += number sum_evens = 0 for num in range(2, 101, 2): sum_evens += num print(sum_evens) # or # total2 = 0 # for num in range(1, 101): # if number % 2 == 0; # total2 += number
true
55928cf794e01fbb58df8535557703841224712e
kimjane93/udemy-python-100-days-coding-challenges
/day-2-tip-calc/main.py
2,281
4.28125
4
print("Welcome To The Tip Calculator!") total_bill = input("What was the total of your meal? \n$") number_of_payers = input("How many of you will be splitting the cost? \n") tip_percentage = input("What percentage would you like to tip? \n15, 18, or 20: \n") total_bill_int = int(total_bill) number_of_payers_int = int(number_of_payers) tip_percentage_int = int(tip_percentage) tip = total_bill_int * (tip_percentage_int/100) final_amount = total_bill_int + tip per_person = round(final_amount/number_of_payers_int, 2) print(f"Subtotal: {total_bill_int}, \n Tip: {tip} \n Total: {final_amount} \n Cost Per Person: {per_person}") # integers # particular element from a string is a subscript # with integers, numbers in python, rather than commas, we can put underscores, and it will be interrpeted by the computer as if the underscores weren't there # float # a floating point number, has a decimal in it, after it, a float data type # Boolean # True # False # no quotations # len(input()) # length of something # type() give you the type of data something is within the paratheses # can use str() to conver an integer into a string so you cna concacetenate with a string etc # can turn an integer or a string into a float with float() # int() # number = input("Number: \n") # new_num = int(number[0]) + int(number[1]) # print(f"{new_num}") # () ** to the power of # order of priority - PEMDAS # paranths, power of, multi/divid, +, - # BMI Calculator # height = input("enter your height in m: ") # weight = input("enter your height in kg: ") # result = float(weight)/(float(height)**2) # result_as_int = int(result) # print(f"{result_as_int}") # rounding numbers # round(8/3, 2) rounds into a whole number, OR can use second arg to specify number of decimal places to round too # floor division # ( // ) a shortcut to get a whole number without have to convert to an integer # Your Life in Weeks # age = input("What is your current age?") # age_as_int = int(age) # time_in_years = 100 - age_as_int # time_in_months = time_in_years * 12 # time_in_weeks = time_in_months * 4 # time_in_days = time_in_weeks * 7 # message = f"You have {time_in_years} years, {time_in_months} months, {time_in_weeks} weeks, {time_in_days} days left" # print(message)
true
590f45f9a3071788b36c25d130dfb82cb498ca89
kimjane93/udemy-python-100-days-coding-challenges
/day-8-create-caesar-ciper-inputs/prime_number_checker.py
383
4.125
4
# check if number is prime # can only divided by one and itself without decimals def prime_checker(number): for n in range(2, number): if number % n == 0: print(f"{number} is not a prime number") break else: print(f"{number} is a prime number") break n = int(input("Check this number: ")) prime_checker(number=n)
true
52682fbd4fe8d676fc6ddcd274470a006db87193
DushyantVermaCS/Python-Tuts
/practice quiz1.py
525
4.21875
4
#Practice Quiz: '''In this scenario, two friends are eating dinner at a restaurant. The bill comes in the amount of 47.28 dollars. The friends decide to split the bill evenly between them, after adding 15% tip for the service. Calculate the tip, the total amount to pay, and each friend's share,then output a message saying "Each person needs to pay: " followed by the resulting number''' #Ans: bill = 47.28 tip = bill * (15/100) total = bill + tip share = total/2 print("Each person needs to pay:",share)
true
bfd80edb5aa331477c537b233e77d6f832e47fe5
DushyantVermaCS/Python-Tuts
/7.1.py
403
4.5
4
'''7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. You can download the sample data at''' #http://www.py4e.com/code3/words.txt #Ans: fname = input("Enter file name: ") fh = open(fname) fr=fh.read() fu=fr.upper() fs=fu.strip() print(fs)
true
fb1c90346864aabef133791cf080b3a30c3fcbdd
blackwer/sciware-testing-python
/sciware_testing_python/main.py
1,192
4.40625
4
# -*- coding: utf-8 -*- """Main module template with example functions.""" def sum_numbers(number_list): """Example function. Sums a list of numbers using a for loop. Parameters ---------- number_list : list List of ints or floats Returns ------- int or float Sum of list Notes ----- This is NOT good Python, just an example function for tests. Example ------- >>> sum_numbers([1, 2, 3]) 6 """ sum_val = 0 for n in number_list: if not isinstance(n, (float, int)): raise ValueError('sum_numbers sums a list containing only ints and floats.') sum_val += n return sum_val def add_vectors(vector_1, vector_2): """Example function. Sums the same index elements of two list of numbers. Parameters ---------- v1 : list List of ints or floats v2 : list List of ints or floats Returns ------- list Sum of lists Notes ----- This is NOT good Python, just an example function for tests. """ sum_vec = [] for a, b in zip(vector_1, vector_2): sum_vec.append(a + b) return sum_vec
true
e4b5ef9fe4a88ccc92e043d808dfbab567c315ea
KunalKokate/Python-Workshop
/ExceptionHandling.py
1,250
4.40625
4
# #Exception Handling # try: #put that code in it which you think is a error # except <Exception>: #put the posssible exception here # print("Some error") # else # print("All went well") #ex1-IOError try: fh = open("example_23.txt","w") fh.write("This is my test file for exception handling") except IOError: print("It's a File Error") else: print("All went well") # ex2- KeyError dict1={"jan":31,"march":30,"april":31} try: print(dict1["march"]) except KeyError: #if you put any other error for example IndexError then it will crash. print("Key could be wrong") else: print("All went well") #ex3 - ValueError try: a = int("dog") print(a) except ValueError: print("Value error is there") else: print("Sab thik hai") #ex4-TypeError try: print("3"+3) except TypeError: print("Its a Type error") else: print("All is well") #ex4-ZeroDivisionError = raised when division by zero takes place for all numeric types. try: val = 5/0 except ZeroDivisionError: print("Its a Zero Division Error") else: print("All is well") #ex5 - IndexError try: list1 = [1,2,3,4,5] print(list1[12]) except IndexError: print("Error Caught") else: print("All is welll")
true
e3910278e81f810231b33c4557d0ebf4af9abfef
asaini/algo-py
/algos/max_diff_two.py
519
4.28125
4
def maximum_diff(array): """ Given an array array of integers, find out the difference between any two elements such that larger element appears after the smaller number in array """ max_diff = array[1] - array[0] min_element = array[0] n = len(array) for i in range(1, n): if array[i] - min_element > max_diff: max_diff = array[i] - min_element if array[i] < min_element: min_element = array[i] return max_diff if __name__ == '__main__': array = [1, 2, 6, 80, 100] print maximum_diff(array)
true
a0c69c20ff2e64a4facb5ae0ffe72bd970d090e8
asaini/algo-py
/algos/triangles.py
459
4.1875
4
def number_of_triangles(array): """ Given an array find the number of triangular pairs in it """ array = sorted(array) n = len(array) count = 0 for i in range(n-2): k = i+2 for j in range(i+1, n): print count while k < n and array[i] + array[j] < array[k]: k += 1 count += k - j - 1 return count if __name__ == '__main__': array = [10, 21, 22, 100, 101, 200, 300] print "Number of triangles = %s" % number_of_triangles(array)
true
966da861bcf16b3aef9480350356641b0e1679d8
asaini/algo-py
/algos/word_break.py
2,523
4.15625
4
""" Given an input string and a dictionary of words, segment the input string into a space-separated sequence of dictionary words if possible. For example, if the input string is "applepie" and dictionary contains a standard set of English words, then we would return the string "apple pie" as output. See : http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem """ def segment_string_into_two(input_string, dictionary): """ Simple solution Assumes that a string can only be broken into 2 words """ n = len(input_string) for i in range(1, n): prefix = input_string[:i] if prefix in dictionary: suffix = input_string[i:] if suffix in dictionary: return prefix + " " + suffix def segment_string_recursive(input_string, dictionary): """ Recursive solution Exponential complexity, eg. Consider a pathological dictionary containing the words "a", "aa", "aaa", ... """ print "Input String = %s" % input_string if input_string in dictionary: return input_string n = len(input_string) for i in range(1, n): prefix = input_string[:i] if prefix in dictionary: suffix = input_string[i:] segmented_suffix = segment_string_recursive(suffix, dictionary) if segmented_suffix: return prefix + " " + segmented_suffix return None def segment_string(input_string, dictionary, memo): print 'Input String = %s' % input_string if input_string in dictionary: return input_string if input_string in memo: return memo[input_string] n = len(input_string) for i in range(1, n): prefix = input_string[:i] if prefix in dictionary: suffix = input_string[i:] segmented_suffix = segment_string(suffix, dictionary, memo) #memo[suffix] = segmented_suffix print 'Memo = %s' % memo if segmented_suffix: return prefix + " " + segmented_suffix memo[input_string] = None return None def segment_string_memoized(input_string, dictionary): """ Dynamic programming solution with memoization. """ memo = {} out = segment_string(input_string, dictionary, memo) return out if __name__ == '__main__': input_string = 'aaaaaab' # dictionary containing vocabulary dictionary = { 'aaa': 1, 'aaaa': 1, 'aaaaa': 1, 'aaaaa': 1, 'ab': 1 } print "Simple Segmentation into two = %s" % segment_string_into_two(input_string, dictionary) print "Recursive Segmentation = %s" % segment_string_recursive(input_string, dictionary) print "Memoized Segmentation = %s" % segment_string_memoized(input_string, dictionary)
true
114c8f6f3c901362a6bfd60eab2b9687132b7631
Hayasak-a/E02a-Control-Structures
/main10.py
2,103
4.34375
4
#!/usr/bin/env python3 import sys, random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" print('Greetings!') # The program greets the user. colors = ['red','orange','yellow','green','blue','violet','purple'] # The program initializes an array of colors. play_again = '' # the variable play_again is set to an empty string best_count = sys.maxsize # the biggest number while (play_again != 'n' and play_again != 'no'): #this loop continues until the user asks not to play again. match_color = random.choice(colors) # a random color is selected from the seven options count = 0 # the number of guesses is initialized to 0 color = '' # the input color from the user is set to an empty string while (color != match_color): #the game loops until the user guesses correctly. color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line color = color.lower().strip() #any spaces the user puts in the color are removed count += 1 # The count storing the number of guesses increments 1 if (color == match_color): # The program checks if the user guessed right print('Correct!') # and prints correct if they have else: # but if they haven't print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #prints "Sorry, try again." and your number of guesses print('\nYou guessed it in {} tries!'.format(count)) # After this victory, it prints how many tries it took the user if (count < best_count): # If this was the lowest number of tries they'd gotten: print('This was your best guess so far!') #It tells them it's a record. best_count = count #And sets a new record for them. play_again = input("\nWould you like to play again (yes or no)? ").lower().strip() #It asks the user if they want to play again.. (the while loop for earlier means that inputs of "no" or "n" witha ny capitalization will end the loop) print('Thanks for playing!') # And once they're done, it thanks the user for playing.
true
14b7d57641e5ce1c727a4f7f36968ab417d270b2
avi527/Decorator
/MultipleDecoratorstoaSingleFunction.py
591
4.28125
4
'''the decorators will be applied in the order that we've called them. Below we'll define another decorator that splits the sentence into a list. We'll then apply the uppercase_decorator and split_string decorator to a single function.''' def splitString(function): def wrapper(): fun=function() funSplit=fun.split() return funSplit return wrapper def UpperCase(function): def wrapper(): f=function() uppCaseF=f.upper() return uppCaseF return wrapper @splitString @UpperCase def saySomthing(): return "hello how are you" print(saySomthing())
true
b80defe74fc40a470982bbbac629e1ea78b05195
vaibhavmathur91/GeeksForGeeks
/Arrays/15_print-missing-elements-that-lie-in-range-0-99.py
1,316
4.25
4
""" Print missing elements that lie in range 0 – 99 Given an array of integers print the missing elements that lie in range 0-99. If there are more than one missing, collate them, otherwise just print the number. Note that the input array may not be sorted and may contain numbers outside the range [0-99], but only this range is to be considered for printing missing elements. Examples : Input: {88, 105, 3, 2, 200, 0, 10} Output: 1 4-9 11-87 89-99 Input: {9, 6, 900, 850, 5, 90, 100, 99} Output: 0-4 7-8 10-89 91-98 """ LIMIT = 100 def get_pythagorean_triplet(arr, n): seen = {i: False for i in range(LIMIT)} for i in arr: seen[i] = True i = 0 while i < LIMIT: if seen[i] is False: j = i+1 while j < LIMIT and seen[j] is False: j += 1 if i+1 == j: print(i) else: print(i, j-1) i = j else: i += 1 array = [88, 105, 3, 2, 200, 0, 10] get_pythagorean_triplet(array, len(array)) print() array = [5, 7, 24, 56, 77, 90] get_pythagorean_triplet(array, len(array)) print() array = [9, 6, 900, 850, 5, 90, 100, 99] get_pythagorean_triplet(array, len(array)) print()
true
d59fdcf6ea0c733d27962abefcb1cd87074b55f5
Daransoto/holbertonschool-machine_learning
/math/0x05-advanced_linear_algebra/2-cofactor.py
2,811
4.15625
4
#!/usr/bin/env python3 """ This module contains the functions determinant, minor and cofactor. """ def determinant(matrix): """ Calculates the determinant of a matrix. matrix is a list of lists whose determinant will be calculated. If matrix is not a list of lists, raises a TypeError with the message matrix must be a list of lists. If matrix is not square, raises a ValueError with the message matrix must be a square matrix. The list [[]] represents a 0x0 matrix. Returns: the determinant of matrix. """ if (type(matrix) is not list or matrix == [] or any([type(el) != list for el in matrix])): raise TypeError('matrix must be a list of lists') if matrix == [[]]: return 1 if len(matrix) != len(matrix[0]): raise ValueError('matrix must be a square matrix') if len(matrix) == 1: return matrix[0][0] if len(matrix) == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] det = 0 for i, n in enumerate(matrix[0]): m = matrix[1:] filt = [[num for idx, num in enumerate(col) if idx != i] for col in m] det += (n * (-1) ** i * determinant(filt)) return det def minor(matrix): """ Calculates the minor matrix of a matrix. matrix is a list of lists whose minor matrix will be calculated. If matrix is not a list of lists, raises a TypeError with the message matrix must be a list of lists. If matrix is not square or is empty, raises a ValueError with the message matrix must be a non-empty square matrix. Returns: the minor matrix of matrix. """ if (type(matrix) is not list or matrix == [] or any([type(el) != list for el in matrix])): raise TypeError('matrix must be a list of lists') lm = len(matrix) if any([lm != len(row) for row in matrix]): raise ValueError('matrix must be a non-empty square matrix') if lm == 1: return [[1]] ans = [] for i in range(lm): row = [] for j in range(lm): f = [[n for k, n in enumerate(c) if k != j] for idx, c in enumerate(matrix) if idx != i] row.append(determinant(f)) ans.append(row) return ans def cofactor(matrix): """ Calculates the cofactor matrix of a matrix. matrix is a list of lists whose cofactor matrix will be calculated. If matrix is not a list of lists, raises a TypeError with the message matrix must be a list of lists. If matrix is not square or is empty, raises a ValueError with the message matrix must be a non-empty square matrix. Returns: the cofactor matrix of matrix. """ return [[(-1) ** (i + j) * n for j, n in enumerate(row)] for i, row in enumerate(minor(matrix))]
true
d4017458ff2330ae832679fd0779d14daecf3bb1
Daransoto/holbertonschool-machine_learning
/math/0x03-probability/poisson.py
2,052
4.28125
4
#!/usr/bin/env python3 """ This module contains the Poisson class. """ class Poisson: """ Class that represents a poisson distribution. """ e = 2.7182818285 def __init__(self, data=None, lambtha=1.): """ Constructor of the class. Sets the instance attribute lambtha as float. data is a list of the data to be used to estimate the distribution. lambtha is the expected number of occurences in a given time frame. """ if data is not None: if type(data) != list: raise TypeError("data must be a list") if len(data) < 2: raise ValueError("data must contain multiple values") mean = 0. count = 0 for element in data: if type(element) not in {int, float}: raise TypeError("Each element in data must be a number") count += 1 mean += element self.lambtha = mean / count else: if lambtha <= 0: raise ValueError("lambtha must be a positive value") self.lambtha = float(lambtha) def pmf(self, k): """ Calculates the value of the PMF for a given number of successes (k). """ k = int(k) if k < 0: return 0 return Poisson.e ** -self.lambtha * self.lambtha ** k / Poisson.fact(k) def cdf(self, k): """ Calculates the value of the CDF for a given number of successes (k). """ k = int(k) if k < 0: return 0 summation = 0 for i in range(0, k + 1): summation += (self.lambtha ** i / Poisson.fact(i)) return Poisson.e ** -self.lambtha * summation @staticmethod def fact(n): """ Calculates the factorial of a number. """ if type(n) != int or n < 0: raise ValueError('n must be a positive integer or 0.') ans = 1 for i in range(2, n + 1): ans *= i return ans
true
0e644a3a1fefbc155515718c3c673db1492e0ac6
Daransoto/holbertonschool-machine_learning
/supervised_learning/0x07-cnn/0-conv_forward.py
2,266
4.15625
4
#!/usr/bin/env python3 """ This module contains the function conv_forward. """ import numpy as np def conv_forward(A_prev, W, b, activation, padding="same", stride=(1, 1)): """ Performs forward propagation over a convolutional layer of a neural network. A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer. m is the number of examples. h_prev is the height of the previous layer. w_prev is the width of the previous layer. c_prev is the number of channels in the previous layer. W is a numpy.ndarray of shape (kh, kw, c_prev, c_new) containing the kernels for the convolution. kh is the filter height. kw is the filter width. c_prev is the number of channels in the previous layer. c_new is the number of channels in the output. b is a numpy.ndarray of shape (1, 1, 1, c_new) containing the biases applied to the convolution. activation is an activation function applied to the convolution. padding is a string that is either same or valid, indicating the type of padding used. stride is a tuple of (sh, sw) containing the strides for the convolution. sh is the stride for the height. sw is the stride for the width. Returns: the output of the convolutional layer. """ kh, kw, _, c_new = W.shape m, h_prev, w_prev, c_prev = A_prev.shape sh, sw = stride if padding == 'same': ph = int(((h_prev - 1) * sh - h_prev + kh) / 2) pw = int(((w_prev - 1) * sw - w_prev + kw) / 2) else: ph = pw = 0 padded = np.pad(A_prev, ((0,), (ph,), (pw,), (0,)), mode='constant', constant_values=0) ansh = int((h_prev + 2 * ph - kh) / sh + 1) answ = int((w_prev + 2 * pw - kw) / sw + 1) ans = np.zeros((m, ansh, answ, c_new)) for i in range(ansh): for j in range(answ): for k in range(c_new): x = i * sh y = j * sw ans[:, i, j, k] = (padded[:, x: x + kh, y: y + kw, :] * W[:, :, :, k]).sum(axis=(1, 2, 3)) ans[:, i, j, k] = activation(ans[:, i, j, k] + b[0, 0, 0, k]) return ans
true
e0215726de40d2dd12c713a53114c0520ff19c5e
prince002021/College-Assignments
/Big Data/Python/Ex/ex1/mapper.py
616
4.125
4
import sys #input comes from STDIN (standard input), i.e type file.txt brings the content of the file to the terminal, and we read it for line in sys.stdin: #remove leading and trailing whitespaces.(\n) line = line.strip() #split the line into words. words = line.split() #increase counter. for word in words: #write the result to stdout #what we output here will be the input to the reduce step, i.e input to reducer.py #tab-delimited; the trivial wordcount is 1 #Note mapper is not computing the word occurrences sum. print('%s\t%s' %(word, 1))
true
cfb0b17e9dc8cbcb5dab580c07632b14666129b3
lvrbanec/100DaysOfCode_Python
/Project09, Beginner, Calculator/main.py
1,395
4.375
4
# 03.02.21, Frollo # Level: beginner # Project: Easy calculator from art import logo print(logo) # Operations # Add def add(n1, n2): return n1 + n2 # Substract def substract(n1, n2): return n1 - n2 # Multipy def multipy(n1, n2): return n1 * n2 # Divide def divide(n1, n2): return n1 / n2 operations = { "+" : add, "-" : substract, "*" : multipy, "/" : divide } def call_again(): # to restart the code upon conditional switch = True while switch: # pick a first number num1 = float(input("What's the first number?: ")) # pick a second number and an operation, and if wanted claculate with a previous result while switch: print("Pick one of the following operation:") for key in operations: print(key) operation_symbol= input() chosen_function = operations[operation_symbol] num2 = float(input("What's the next number?: ")) result = chosen_function(num1, num2) print(f"{num1} {operation_symbol} {num2} = {result}") should_continue = input(f"Type 'y' to continue calculating with {result}, type 'n' to start a new calculation, or type 'esc' to exit.\n") if should_continue == "esc": switch = False print("Thank you for using our calculator.") elif should_continue == 'y': num1 = result elif should_continue == 'n': call_again() call_again()
true
d97018c87c0ef051616f1b15fa102759167061ab
lvrbanec/100DaysOfCode_Python
/Project16, Intermediate, TurtleRace using turtle module/main.py
1,238
4.34375
4
# 08.02.2021, Frollo # Level: Intermediate # Project: Make a turtle race betting game from turtle import Turtle, Screen import random is_race_on = False screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ") colors = ["red", "green", "purple", "blue", "yellow", "black"] all_turtles = [] y_position = -100 for turtle_index in range(6): new_turtle = Turtle("turtle") new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.goto(x=-230, y=y_position) y_position += 40 all_turtles.append(new_turtle) if user_bet: # of variable exists (wait for the input of the user) is_race_on = True while is_race_on: for turtle in all_turtles: if turtle.xcor() > 230: is_race_on = False # stop the race winning_color = turtle.pencolor() if winning_color == user_bet: print(f"You've won! The {winning_color} turtle is the winner!") else: print(f"You've lost! The {winning_color} turtle is the winner!") rand_distance = random.randint(0, 20) turtle.forward(rand_distance) screen.exitonclick()
true
5c9696e2093d8ccf15a5da2705c6da6886a95df4
andrescanovas/programacion
/Programacion 3/ejercicio02.py
1,335
4.21875
4
# ___________CONSULTAR NO DEJA RESPUESTA EN CADA NOMBRE___________ # for i in range (0, 3): # nombre = input("ingrese su nombre :").capitalize() # anio_nacimiento = int(input("ingrese año de nacimiento :")) # edad = 2021 - anio_nacimiento # if(edad >= 18): # print(nombre,"ES MAYOR DE EDAD") # else: # print(nombre,'ES MENOR DE EDAD') #------------------------------------ ALMACENA DATOS forma 1------------------------- # datos = [] # datos2 = [] # for i in range (0,3): # nombre = input("ingrese su nombre :").capitalize() # anio_nacimiento = int(input("ingrese año de nacimiento :")) # edad = 2021 - anio_nacimiento # datos.append(datos) # datos.append(datos2) # if(edad >= 18): # print(nombre,"ES MAYOR DE EDAD") # else: # print(nombre,'ES MENOR DE EDAD') # print(datos) # print(datos2) # -----------------------ALMACENA DATOS 2------------- datos = [] for i in range (0,3): nombre = input("ingrese su nombre :").capitalize() anio_nacimiento = int(input("ingrese año de nacimiento :")) edad = 2021 - anio_nacimiento datos.append([nombre, edad]) if(edad >= 18): print(nombre,"ES MAYOR DE EDAD") else: print(nombre,'ES MENOR DE EDAD') for persona in datos: print(datos)
false
23fa9655019a2fff8a661ef1e275f2df9d18cd5a
anhnguyendepocen/Python-for-Research
/Part5/Linear Regression.py
1,898
4.28125
4
# Introduction to Statistical Learning # Generating Example Regression Data import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt n = 100 beta_0 = 5 beta_1 = 2 np.random.seed(1) x = 10 * ss.uniform.rvs(size=n) y = beta_0 + beta_1 * x + ss.norm.rvs(loc=0,scale=1,size=n) plt.figure() plt.plot(x,y,"o",ms=5) xx = np.array([0,10]) plt.plot(xx,beta_0 + beta_1 * xx) plt.xlabel("x") plt.ylabel("y") # Least Squares Estimation in Code def compute_rss(y_estimate, y): return sum(np.power(y-y_estimate, 2)) def estimate_y(x, b_0, b_1): return b_0 + b_1 * x rss = compute_rss(estimate_y(x, beta_0, beta_1), y) rss = [] slopes = np.arange(-10,15,0.01) for slope in slopes: rss.append(np.sum((y - beta_0 - slope * x)**2)) print(rss) ind_min = np.argmin(rss) print(ind_min) print("Estimate for the slope:",slopes[ind_min]) # Plot the figure plt.figure() plt.plot(slopes,rss) plt.xlabel("Slope") plt.ylabel("RSS") # Simple Linear Regression import statsmodels.api as sm mod = sm.OLS(y,x) est = mod.fit() print(est.summary()) # Lets add coefficient X = sm.add_constant(x) mod = sm.OLS(y,X) est = mod.fit() print(est.summary()) # Scikit-learn for Linear Regression n = 500 beta_0 = 5 beta_1 = 2 beta_2 = -1 np.random.seed(1) x_1 = 10 * ss.uniform.rvs(size=n) x_2 = 10 * ss.uniform.rvs(size=n) y = beta_0 + beta_1* x_1 + beta_2 * x_2 + ss.norm.rvs(loc=0,scale=1,size=n) X = np.stack([x_1,x_2],axis=1) from sklearn.linear_model import LinearRegression lm = LinearRegression(fit_intercept=True) lm.fit(X,y) lm.intercept_ lm.coef_ x_0 = np.array([2,4]) lm.predict(x_0.reshape(1, -1)) lm.score(X,y) # Assessing Model Accuracy from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,y,train_size=0.5,random_state=1) lm = LinearRegression(fit_intercept=True) lm.fit(X_train,y_train) lm.score(X_test,y_test)
false
8912bd0934d08ba0573043e92ca11925324928c3
anhnguyendepocen/Python-for-Research
/Part1/exercise 2c.py
490
4.125
4
#EXERCISE 2C """ The distance between two points x and y is the square root of the sum of s quared differences along each dimension of x and y. Create a function distance(x, y) that takes two vectors and outputs the distance between them. Use your function to find the distance between x=(0,0) and y=(1,1). Print your answer. """ import math def distance(x, y): # define your function here! return math.sqrt((y[1]-x[1])**2 + (y[0]-x[0])**2) print(distance((0,0),(1,1)))
true
87219f5f93f82ed8a9eaecccb2e894f73b6b6c98
ankolaver/ALevel_Computing_Material
/Algorithms/sorting/bubblesort_iter.py
815
4.1875
4
'''Bubble sort has a worst-case and average complexity of О(n2), where n is the number of items being sorted. Most practical sorting algorithms have substantially better worst-case or average complexity, often O(n log n). The function below always runs O(n^2) time even if the array is sorted. It can be optimized by stopping the algorithm if inner loop didn’t cause any swap.''' def bubblesort(arr): lenarr = len(arr) for i in range(lenarr): swapmulti = False for k in range(0, lenarr-i-1): if arr[k]>arr[k+1]: arr[k],arr[k+1] = arr[k+1], arr[k] swapmulti = True #do not need to go through loop again (efficient) if swapmulti == False: break print(arr1) arr1 = [12,2,34,29,4,6,6,7] bubblesort(arr1)
true
b8b08895fdf9703474a24e97e1fa0bda7a78ffed
shubhra2/PythonC
/lab2.py
2,015
4.25
4
def readnum() : nm = float(input("Enter Number(s) : ")) return nm def add() : numarr = [] for i in range(2) : n1 = readnum() numarr.append(n1) print("{} + {} = {}".format(numarr[0], numarr[1], numarr[0] + numarr[1])) def maxmin() : maxminnumary = [] for i in range(3) : n2 = readnum() maxminnumary.append(n2) print("The Maximum and minimun of {} numbers are : {}, {} respectively." .format(maxminnumary, max(maxminnumary), min(maxminnumary))) def palindrome(): str = input("Enter a string : ") strrev = ''.join(reversed(str)) if(str == strrev): print("{} is a palindrome.".format(str)) else: print("{} is not a palindrome.".format(str)) def factorialnonfunc(): import math num = int(readnum()) print("The factorial of {} is : {}".format(num, math.factorial(num))) def factorialfunc(): def factorial(num1): if num1 == 1: return 1 else: return (num1 * factorial(num1-1)) print(factorial(int(readnum()))) def selection(): sel = int(input(''' choose from the following : 1. Addition of two numbers. 2. Maximum and minimum from three numbers 3. Check wether a given string is a palindrome or not 4. Factorial of a number without using a function 5. Factorial of a number using a function 6. Exit ''')) while sel < 7: if(sel == 1): add() selection() break elif(sel == 2): maxmin() selection() break elif(sel == 3): palindrome() selection() break elif(sel == 4): factorialnonfunc() selection() break elif(sel == 5): factorialfunc() selection() break elif(sel == 6): break else: print("\n\nPlease choose from 1 to 6.") selection() # selection()
false
263e4a8e66f719ad1c39d97b68f8f5a75a51112f
Widdershin/CodeEval
/challenges/007-lowercase.py
818
4.3125
4
""" https://www.codeeval.com/browse/20/ Lowercase Challenge Description: Given a string write a program to convert it into lowercase. Input Sample: The first argument will be a text file containing sentences, one per line. You can assume all characters are from the english language. E.g. HELLO CODEEVAL This is some text Output Sample: Print to stdout, the lowercase version of the sentence, each on a new line. E.g. hello codeeval this is some text """ import sys if len(sys.argv) < 2: input_file_name = "7-lowercase-in.txt" else: input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_data = input_file.read() def main(): for line in input_data.split('\n'): print line.lower() if __name__ == '__main__': main()
true
36517dd0165ff7a251258d7a26795d6cf1d5a1b0
Widdershin/CodeEval
/challenges/011-sumofintegersfromfile.py
801
4.125
4
""" https://www.codeeval.com/browse/24/ Sum of Integers from File Challenge Description: Print out the sum of integers read from a file. Input Sample: The first argument to the program will be a text file containing a positive integer, one per line. E.g. 5 12 Output Sample: Print out the sum of all the integers read from the file. E.g. 17 """ ###### IO Boilerplate ###### import sys if len(sys.argv) < 2: input_file_name = "11-sumofintegersfromfile-in.txt" else: input_file_name = sys.argv[1] with open(input_file_name) as input_file: input_lines = map(lambda x: x.strip(), filter(lambda x: x != '', input_file.readlines())) ###### IO Boilerplate ###### def main(): print sum(map(int, input_lines)) if __name__ == '__main__': main()
true
b83a41143117339fe319f2b5654dfdca97bcbf6a
Nafisa-tabassum2046/my-pycharm-project
/if elif sestetment anisul.py
1,600
4.1875
4
# # # a = 78 # if (a>33): # print("pass") # # else: # print("fail") # # # greater then less than number print # # a = 20 # b= 10 # if (a>b): # print("a is greater then b") # # else: # print("b is greater then a") # # # odd even number check: # # a = 10 # # if(a%2==0): # print("even") # # else: # print("odd") # # 3 ta number ar maje ckeck # a= 90 # # if(a>80): # print("A+") # elif(a>70): # print("A") # elif(a>60): # print("A-") # elif(a>50): # print("B") # elif(a>40): # print("C") # else: # print("fail") # # 3 ta number ar maje greater middle less check a = int(input("Enter the 1st number: ")) b = int(input("Enter the 2nd number: ")) c = int(input("Enter the 3rd number: ")) if(a>b and a>c): if(b>c): print("a is greater number") print("b is middle number") print("c is small number") else: print("a is greater number") print("c is middle number") print("b is small number") elif(b>c and b>a): if(a>c): print("b is greater number") print("a is middle number") print("c is small number") else: print("b is greater number") print("c is middle number") print("a is small number") else: if(a>b): print("c is greater number") print("a is middle number") print("b is small number") else: print("c is greater number") print("b is middle number") print("a is small number")
false
6e166497b93e4630729d919dd692231c67497830
xeroxzen/Coding-Challenges
/Minimum Waiting Time.py
2,672
4.15625
4
# O(nlogn) - time | O(1) - space : where n is the number of queries def minimumWaitingTime(queries): ## Understand: ''' - executing the shortest query first is what will lead to the minimum waiting time - because all queries after it will also have to wait a short/minimum time - if we execute the query with the largest amount of time first, it means that - all the queries after it will have to wait a minimum of that amount of time - therefore, the idea is that we need to start with the query with the minimum amount of time ''' ## Algorithm #example of a greedy algorithm ''' - sort the array in place O(nlogn) - time - keep track of the total waiting time, waitingTime = 0 - loop through the sorted array of queries - update the waitingTime - multiply the number of queries left by the duration of the current query - and add that to the total waiting time ''' # if queries only has one entry if len(queries) == 1: return 0 # sort the queries in place # queries arranged from the smallest to the largest queries.sort() # initialize the waiting time to 0 waitingTime = 0 n = len(queries) - 1 # loop through the array for i in range(n): # n - 1 gives the number of queries left excluding the current query waitingTime += queries[i] * (n - i) return waitingTime """ Minimum Waiting Time -------------------- # Source: https://www.algoexpert.io/questions/Minimum%20Waiting%20Time - You're given a non-empty array of positive integers representing the amounts of time that specic - queries take to execute. Only one query can be executed at a time, but the queries can be executed in any order. - A query's waiting time is dened as the amount of time that it must wait before its execution starts. - In other words, if a query is executed second, then its waiting time is the duration of the rst query; if - a query is executed third, then its waiting time is the sum of the durations of the rst two queries. - Write a function that returns the minimum amount of total waiting time for all of the queries. For - example, if you're given the queries of durations [1, 4, 5] , then the total waiting time if the - queries were executed in the order of [5, 1, 4] would be (0) + (5) + (5 + 1) = 11 . - The first query of duration 5 would be executed immediately, so its waiting time would be 0 , the - second query of duration 1 would have to wait 5 seconds (the duration of the rst query) to be - executed, and the last query would have to wait the duration of the rst two queries before being executed. # Note: you're allowed to mutate the input array. # Sample Input >>> queries = [3, 2, 1, 2, 6] # Sample Output >>> 17 """
true
bc1c7608fe9408b6831c288476894cb7d3ab4213
MattPaul25/PythonPatterns
/DesignPatterns/Creational/AbstractFactory.py
1,476
4.375
4
class Dog: def speak(self): return "Woof!" def __str__(self): return "Dog" class Cat: def speak(self): return "Meow!" def __str__(self): return "Cat" class DogFactory: def get_pet(self): #returns dog object return Dog() def get_food(self): #returns dog food return "Dog Food!" class CatFactory: def get_pet(self): #returns dog object return Cat() def get_food(self): #returns dog food return "Cat Food!" class PetStore: #petstore houses our abstract factory def __init__ (self, pet_factory = None): """ pet_factory is our abstract factory """ self._pet_factory = pet_factory def show_pet(self): """ utility method to display the details of the objects returned by the dog factory """ pet = self._pet_factory.get_pet() pet_food = self._pet_factory.get_food() print("Our pet is '{}'!".format(pet)) print("Our pet says hello '{}'!".format(pet.speak())) print("The pets food is '{}'!".format(pet_food)) ######### ~~~~~~~~~~~~~~~ RUNNING THE PATTERN ~~~~~~~~~~~~~~~ ######### #create a concrete factory factory = DogFactory() #Create a pet store housing our abstract factory shop = PetStore(factory) #invoke the utility to show the details of our pet shop.show_pet() #same thing useing the cat object c_factory = CatFactory() c_shop = PetStore(c_factory) c_shop.show_pet()
true
41c984b50c251479bbb32e5fa4e672e52994ce4d
MattPaul25/PythonPatterns
/DesignPatterns/Behavorial/Visitor.py
1,823
4.1875
4
#visitor allows adding new features to existing class heirarchy without changing it #scenario: house class, HVAC specialist is a vistor, #Electrician is visitor 2 -- new actions to be performed on an existing class heirarchy. class House(object): #the class being visited """this is the object that gets visited""" def accept(self, visitor): """interface to accept a visitor""" #Triggers the visitng operation visitor.visit(self) def work_on_hvac(self, hvac_specialist): print(self.__str__() + " worked on by " + hvac_specialist.__class__.__name__) #note that we now have a reference to hvac specailist object in the house object def work_on_electricity(self, electrician): print(self.__str__() + " worked on by " + electrician.__class__.__name__)#Not that we now have a reference to the electrician object in the house object def __str__(self): """simply return the class name when the house object is printed""" return self.__class__.__name__ + '\n' + self.__class__.__doc__ class Visitor(object): """abstract visitor""" def __str__(self): """simply return the class name when the visitor object is printed""" return self.__class__.__name__ class HvacSpecialist(Visitor): """concrete visitor: hvac""" def visit(self, house): house.work_on_hvac(self) #visitor has a reference to the house object class Electrician(Visitor): """concrete visitor: electrician""" def visit(self, house): house.work_on_electricity(self) #visitor has a reference to the house object ######### ~~~~~~~~~~~~~~~ RUNNING THE PATTERN ~~~~~~~~~~~~~~~ ######### #create an hvac specialist hv = HvacSpecialist() elec = Electrician() home = House() home.accept(hv) home.accept(elec) print(home)
true
8ffa476ccd0cdfcdb2078b610448cd45c7e54f28
anitrajpurohit28/PythonPractice
/python_practice/String_programs/10_remove_duplicates.py
1,485
4.15625
4
# 10 Remove all duplicates from a given string in Python input1 = 'aabbcccddekll12@aaeebbbb' print(input1) # by using set; unordered print("----unordered set------") def remove_duplicates_set(string): unique_chars = set(string) print(''.join(unique_chars)) remove_duplicates_set(input1) print("----OrderedDict------") # by using set; ordered dictionary from collections import OrderedDict def remove_duplicates_orderedDict(string): unique_chars = OrderedDict.fromkeys(string) print(''.join(unique_chars)) remove_duplicates_orderedDict(input1) print("---new string---") def remove_duplicate_naive(string): result_str = "" for char in string: if char in result_str: pass else: result_str +=char print(result_str) remove_duplicate_naive(input1) print("----new list ------") def remove_duplicate_list(string): unique_list = [] for i in string: if i not in unique_list: unique_list.append(i) print("".join(unique_list)) remove_duplicate_list(input1) print("----overwrite string ------") def remove_duplicate_no_extra_space(string): r, w = 0, 0 while r < len(string): if string[r] not in string[:r]: string[w] = string[r] r += 1 w += 1 else: string[w] = string[r] r += 1 string = string[:w] # OR # del string[w:] print("".join(string)) remove_duplicate_no_extra_space(list(input1))
true
1fcdf7077619788f8df2cece109e92bd49a4af58
anitrajpurohit28/PythonPractice
/python_practice/List_programs/2_swap_2_elements_of_given_positions.py
1,041
4.25
4
# 2 Python program to swap two elements in a input_list given_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] p1 = 2 p2 = 5 def swap_positions_comma_assignment(input_list, pos1, pos2): input_list[pos1], input_list[pos2] = input_list[pos2], input_list[pos1] print(given_list) swap_positions_comma_assignment(given_list, p1, p2) print(given_list) print("--------------") def swap_positions_pop_insert(input_list, pos1, pos2): first_element = input_list.pop(pos1) # pop 'pos2-1' because one element is already popped # position changed second_element = input_list.pop(pos2-1) input_list.insert(pos1, second_element) input_list.insert(pos2, first_element) print(given_list) swap_positions_pop_insert(given_list, p1, p2) print(given_list) print("--------------") def swap_position_using_tuple(input_list, pos1, pos2): get = input_list[pos1], input_list[pos2] input_list[pos2], input_list[pos1] = get print(given_list) swap_position_using_tuple(given_list, p1, p2) print(given_list) print("--------------")
false
bfad97f35cee5bbd84fb0133555872db1695a97c
anitrajpurohit28/PythonPractice
/python_practice/List_programs/1_interchange_first_last_elements.py
2,372
4.46875
4
# 1 Python program to interchange first and last elements in a list print("-----1------") def swap_list_using_temp1(input_list): temp = input_list[0] input_list[0] = input_list[-1] input_list[-1] = temp my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_temp1(my_list) print(my_list) print("-----2------") def swap_list_using_temp_len(input_list): length_of_list = len(input_list) temp = input_list[0] input_list[0] = input_list[length_of_list - 1] input_list[length_of_list - 1] = temp my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_temp_len(my_list) print(my_list) print("-----3------") def swap_list_using_tuple_variable(input_list): # Storing the first and last element # as a pair in a tuple variable get get = input_list[0], input_list[-1] # unpacking tuple elements input_list[-1], input_list[0] = get my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_tuple_variable(my_list) print(my_list) print("-----4------") def swap_list_using_push_pop(input_list): curr_element = input_list.pop() input_list.insert(0, curr_element) my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_push_pop(my_list) print(my_list) print("-----5------") def swap_list_using_star_oper_tuple(input_list): # In this function, input arg is modified but not reflected # into calling function hence we are returning the value # to calling function start, *mid, last = input_list # print(start, mid, last) # 1 [2, 3, 4, 5, 6] 7 # By copying the variable directly into variable input_list, # input_list will turn into tuple # Now, input_list is a tuple; its not a list anymore input_list = last, *mid, start # print(input_list) # calling function will get the right value only if # this function returns and calling function will receive it return input_list # list property will be lost by this method my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_star_oper_tuple(my_list) print(my_list) my_list = swap_list_using_star_oper_tuple(my_list) print(my_list) print("-----6------") def swap_list_using_star_oper_list(input_list): start, *middle, end = input_list input_list = [end, *middle, start] return input_list my_list = [1, 2, 3, 4, 5, 6, 7] swap_list_using_star_oper_list(my_list) print(my_list) my_list = swap_list_using_star_oper_list(my_list) print(my_list)
false
8c4e3d0b18fac03abaf0ca86b1841ae0d5432d1f
anitrajpurohit28/PythonPractice
/python_practice/String_programs/14_remove_ith_char_from_string.py
248
4.28125
4
# 14 Python program for removing i-th character from a string import string ### already covered in "3_remove_i_th_character.py" string1 = "input string, input variable" string2 = string1.replace("input", "abcdefg") print(string1) print(string2)
true
2f5085943ab773cdf407bb7d65f76cd4c5f63117
anitrajpurohit28/PythonPractice
/python_practice/String_programs/11_check_for_special_char.py
1,217
4.375
4
# 11 Python | Program to check if a string contains any special character txt1 = "CompanyA12" txt2 = "andfa322ABGFDASVF" txt3 = "!@asdesad fx" print(txt1.isalnum()) print(txt2.isalnum()) print(txt3.isalnum()) print("-----my_isalnum------") def my_isalnum(string): special_char = """'[@_!#$%^"&*()<>?/\\|}{~:]""" for char in string: if char in special_char: return False else: continue return True print(my_isalnum(txt1)) print(my_isalnum(txt2)) print(my_isalnum(txt3)) print("------search in string.punctuation-----") from string import punctuation def my_is_str_alpha_numeric(input_string): for char in input_string: if char in punctuation: return False else: return True print(my_is_str_alpha_numeric(txt1)) print(my_is_str_alpha_numeric(txt2)) print(my_is_str_alpha_numeric(txt3)) print("------re module; regex----") import re def is_alpha_numeric_regex(input_string): regex = re.compile(punctuation) if regex.search(input_string): return False else: return True print(my_is_str_alpha_numeric(txt1)) print(my_is_str_alpha_numeric(txt2)) print(my_is_str_alpha_numeric(txt3))
false
fa9b36a68ec5c3bedecabeeafd69e9f4050bcd26
anitrajpurohit28/PythonPractice
/python_practice/String_programs/1_is_palindrome.py
1,943
4.5
4
# 1 Python program to check if a string is palindrome or not input1 = "malayalam" input2 = "geeks" input3 = "12345678987654321" print("---reversing string---") def is_palindrome_reverse(input_str): rev_str = input_str[::-1] if rev_str == input_str: return True else: return False print(f"input1: {input1} is_palindrome: {is_palindrome_reverse(input1)}") print(f"input1: {input2} is_palindrome: {is_palindrome_reverse(input2)}") print(f"input1: {input3} is_palindrome: {is_palindrome_reverse(input3)}") print("---Iterative string---") def is_palindrome_iterative(input_str): for i in range((len(input_str))//2): if input_str[i] != input_str[len(input_str)-1-i]: return False return True print(f"input1: {input1} is_palindrome: {is_palindrome_iterative(input1)}") print(f"input1: {input2} is_palindrome: {is_palindrome_iterative(input2)}") print(f"input1: {input3} is_palindrome: {is_palindrome_iterative(input3)}") print("---built-in string---") def is_palindrome_builtin_reversed(input_str): rev_str = ''.join(reversed(input_str)) if rev_str == input_str: return True else: return False print(f"input1: {input1} is_palindrome: {is_palindrome_builtin_reversed(input1)}") print(f"input1: {input2} is_palindrome: {is_palindrome_builtin_reversed(input2)}") print(f"input1: {input3} is_palindrome: {is_palindrome_builtin_reversed(input3)}") print("---manually build string and compare---") def is_palindrome_build_and_compare(input_str): rev_str = '' for char in input_str: rev_str = char + rev_str if rev_str == input_str: return True else: return False print(f"input1: {input1} is_palindrome: {is_palindrome_build_and_compare(input1)}") print(f"input1: {input2} is_palindrome: {is_palindrome_build_and_compare(input2)}") print(f"input1: {input3} is_palindrome: {is_palindrome_build_and_compare(input3)}")
false
085617c6a15fb5100aeda22ffcca64eb89e8bb62
zuping-qin/SDET-QA
/docker/app/cambia.py
1,339
4.21875
4
# This function tokenlizes the CSV content line by line # into an array of list of words after stripping off the # whitespace, including new line characters. It then # sorts the line word list in an ascending order. Finally, # it writes out the word lists into csv lines in the output # file. import sys def sortCSVContents(input_file, output_file): # Read in the file content line by line try: with open(input_file) as file_input: lines = file_input.readlines() except FileNotFoundError: print(f'FileNotFoundError: {input_file} not present') return # Assuming the file content is in csv format, # Removes the preceding and trailing whitespaces. # Then, we split, sort the words ascendingly DELIMITER = ',' lines_out = [] for line in lines: line = line.strip() line = line.split(DELIMITER) line.sort(reverse=True) lines_out.append(line) # Then, we rejoin the words with the comma delimiter # and write out to the output file. with open(output_file, 'w') as file_out: for list in lines_out: file_out.write(DELIMITER.join(list)) file_out.write('\n') if __name__ == '__main__': if len(sys.argv) < 3: raise ArgumentError _, input_file, output_file = sys.argv sortCSVContents(input_file, output_file)
true
fd0b5eb9c303335168e4ed3ec8b76ee5b24369fe
yinhaiquan/python_basic
/demo/hq/com/function.py
1,262
4.1875
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # 函数 # 无返回值函数 void def showName(name): print name showName("fuck") # 有返回值函数 return def getName(name,age): return str(age)+name print getName("fuck",12) # 缺省参数 最少得赋值一个参数,且缺省参数必须初始化,否则抛异常 def getParamters(var1,var2=12): print var1,var2 getParamters(var1="sdf") getParamters(var2=123,var1="666") # 不定长参数 """ 你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数, 和上述2种参数不同,声明时不会命名。基本语法如下: def functionname([formal_args,] *var_args_tuple ): "函数_文档字符串" function_suite return [expression] """ def printInfo(arg0,*args): print "输出:" print arg0 for item in args: print item return; printInfo(10) printInfo(10,11,12,13) # 匿名函数 """ lambda函数的语法只包含一个语句,如下: lambda [arg1 [,arg2,.....argn]]:expression """ sum = lambda arg0,arg1:arg0+arg1; print sum(10,10) print sum(20,20) # 全局变量 index = 0; def setIndex(): global index index = 1 def getIndex(): return index; setIndex() print getIndex()
false
84b5c7618e98c8d1e3b62ab8dfc6c2ec49c9b304
ManuelPPonce/Programacion-Visual
/Examen/diccionario.py
692
4.25
4
""" 5.- Escribir un programa llamado diccionario.py que pregunte al usuario su nombre, edad, dirección y teléfono y lo guarde en un diccionario. Después debe mostrar por pantalla el mensaje <nombre> tiene <edad> años, vive en <dirección> y su número de teléfono es <teléfono>. """ Nombre = input ("Nombre : ") Edad = int(input ("Edad : ")) Direccion = input("Ingresa tu dirección :") Telefono = input("Telefono: ") diccionario = { "Nombre" : Nombre, "Edad":Edad, "Direccion": Direccion, "Telefono":Telefono, } print(diccionario["Nombre"],"Tiene ",diccionario["Edad"],"años, vive en ",diccionario["Direccion"] ,"y su numero de telefono es : " ,diccionario["Telefono"])
false
a30beff7fc2b6b70debd39071ee3d92ea233a959
cdhop/headfirstprogramming
/greeter.py
628
4.15625
4
#!/usr/bin/python3 def get_formatted_name(first_name, last_name): """Return a full name, neatly formatted.""" full_name = first_name + " " + last_name return full_name.title() done = False while done != True: print("\nPlease tell me your name:") print("enter 'q' at any time to quit") first_name = input("First name: ") if first_name == 'q': done = True continue last_name = input("Last name: ") if last_name == 'q': done = True continue formatted_name = get_formatted_name(first_name, last_name) print("\nHello, " + formatted_name + "!")
true
f49bba91c297b11bbbd857045055ad3baa13840f
gwcahill/CodeEval
/capitalize_words/capitalize_words.py
1,129
4.125
4
''' Created on Feb 24, 2015 https://www.codeeval.com/open_challenges/93/ Write a program which capitalizes the first letter of each word in a sentence. Input sample: Your program should accept as its first argument a path to a filename. Input example is the following: Hello world javaScript language a letter 1st thing Output sample: Print capitalized words in the following way. Hello World JavaScript Language A Letter 1st Thing @author: Grant Cahill ''' import sys if __name__ == '__main__': file_obj = open(sys.argv[1], 'r') for line in file_obj: line_list = list() upper_list = list() # remove white space line = line.strip() # only proceed if line has content if len(line) > 0: line_list = line.split(' ') for word in line_list: if word[0].isdigit(): upper_list.append(word) else: upper_list.append(word[0].upper() + word[1:]) print ' '.join(upper_list) file_obj.close()
true
50f472879fddad1453a99649717e688b23c02bc2
gwcahill/CodeEval
/calculate_distance/calculate_distance.py
2,334
4.15625
4
''' Created on Mar 27, 2015 https://www.codeeval.com/open_challenges/99/ You have coordinates of 2 points and need to find the distance between them. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Input example is the following (25, 4) (1, -6) (47, 43) (-25, -11) All numbers in input are integers between -100 and 100. OUTPUT SAMPLE: Print results in the following way. 26 90 You don't need to round the results you receive. They must be integer numbers. @author: Grant Cahill ''' import sys from math import sqrt def two_point_distance(x_one, y_one, x_two, y_two): ''' Distance between two points on a 2D plane is as follows: sqrt((delta_x)^2 + (delta_y)^2) ''' delta_x = x_two - x_one delta_y = y_two - y_one x_sqr = delta_x * delta_x y_sqr = delta_y * delta_y distance = sqrt(x_sqr + y_sqr) return int(distance) def create_num_list(line): ''' Expect line in format of: (25, 4) (1, -6) ''' num_list = list() first_left_paren = -1 second_left_paren = -1 first_right_paren = -1 second_right_paren = len(line)-1 first_left_not_found = True first_right_not_found = True for index, value in enumerate(line): if value == "(" and first_left_not_found: first_left_paren = index first_left_not_found = False if value == "(": second_left_paren = index if value == ")" and first_right_not_found: first_right_paren = index first_right_not_found = False first_pair = line[first_left_paren+1:first_right_paren] second_pair = line[second_left_paren+1:second_right_paren] first_pair_list = first_pair.split(",") second_pair_list = second_pair.split(",") num_list.append(int(first_pair_list[0].strip())) num_list.append(int(first_pair_list[1].strip())) num_list.append(int(second_pair_list[0].strip())) num_list.append(int(second_pair_list[1].strip())) return num_list if __name__ == '__main__': file_obj = open(sys.argv[1], 'r') for line in file_obj: line = line.strip() num_list = create_num_list(line) print two_point_distance(num_list[0], num_list[1], num_list[2], num_list[3]) file_obj.close()
true
311cca70160671252efd6d2116f633249ef315ea
gwcahill/CodeEval
/n_mod_m/n_mod_m.py
943
4.125
4
''' Created on Mar 11, 2015 https://www.codeeval.com/open_challenges/62/ Given two integers N and M, calculate N Mod M (without using any inbuilt modulus operator). Input sample: Your program should accept as its first argument a path to a filename. Each line in this file contains two comma separated positive integers. E.g. 20,6 2,3 You may assume M will never be zero. Output sample: 2 2 2 0 7 1 3 Print out the value of N Mod M @author: Grant Cahill ''' import sys, math def find_mod(value, divider): div = math.trunc(value/divider) rem = value - (divider * div) return rem if __name__ == '__main__': file_obj = open(sys.argv[1], 'r') for line in file_obj: line = line.strip() line_list = line.split(',') value = int(line_list[0]) divider = int(line_list[1]) print find_mod(value, divider) file_obj.close()
true
3f3f9758332bbbbd05e2c3b42f3b1baadcf83fc4
linhnvfpt/homework
/python/practice_python/exer6.py
511
4.5
4
# Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) import math string = input("Input a string: ") lenstr = len(string) stop = math.floor(lenstr / 2) strLeft = string[0:stop:1] if lenstr % 2 == 1: strTemp = string[stop+1:] else: strTemp = string[stop:] strRight = strTemp[::-1] if strLeft == strRight: print("It is a palindrome.") else: print("It is not a palindrome.")
true
c57e06c0a030903d5cd949ee03e4575760f9058a
linhnvfpt/homework
/python/practice_python/exer9.py
797
4.25
4
#Generate a random number between 1 and 9 (including 1 and 9). #Ask the user to guess the number, then tell them whether they guessed too low, #too high, or exactly right. #(Hint: remember to use the user input lessons from the very first exercise) #Extras: #Keep the game going until the user types “exit” #Keep track of how many guesses the user has taken, and when the game ends, print this out. import random a = random.randint(1, 9) b = 1 index = 0 while b != 0: b = int(input("Guess number. Input a number (input 0 to exit): ")) if b == 0: break index = index + 1 if a < b: print("Too high.") elif a > b: print("Too low.") else: print("Exactly right.") print("User guessed ",index," times.")
true
382a04567820ccba224bfa9301aa2b03b8c55d8f
linhnvfpt/homework
/python/w3resource/python-execises/part-I/18.py
254
4.125
4
# Write a Python program to calculate the sum of three given numbers, if the values are equal then return three times of their sum def sum(a,b,c): if a == b == c: return 3 * a return a + b + c print(sum(1,2,3)) print(sum(1,1,1))
true
0ef8cb7de0f18c6c2841e091ac887947d0202e32
SparshRajGupta/MyPythonStudy
/function2.py
214
4.15625
4
def max(a,b): if a > b: print 'a is greater than b' if b > a: print 'b is greater than a' if b == a: print "a is equal to b" max(15,6) x = 15 y = 15 max(x, y)
true
ff4234f503c0fa2950290a15fa7812a929339666
shelkesagar29/CTCI
/Chapter2/p8_loop_detection.py
2,880
4.1875
4
import unittest from DS.linkedlist import LinkedList def solution1(ll): """ Time Complexity: O(n) where n is the length of the linked list Space Complexity: O(1) Args: ll (LinkedList): linked list object Returns: data: Node value where loop starts if LL has loop. -1: If LL has no loop. """ # Note that ll implementation uses sentinel head and tail node # In the solution, no other information than linked list head is used! # setp 1, Detect whether linked list has loop or not slow = ll.head.next fast = ll.head.next has_loop = False is_first = True while fast.data != None and fast.next.data !=None: if slow.data == fast.data: if is_first: is_first = False pass else: has_loop = True break slow = slow.next fast = fast.next.next # setp2, detect the starting of the loop # here we take slow pointer to the head, fast remains at same position # increment both pointers by one and where they meet is the loop start # over simplified proof: https://stackoverflow.com/a/33149978 if not has_loop: return -1 slow = ll.head.next while True: if slow.data == fast.data: return slow.data slow = slow.next fast = fast.next """ Bonus: Remove the loop. keep the slow pointer steady after loop start is detected. Increment fast pointer by one until slow pointer is the next. Set tail node as the next node of the node immediately before slow pointer. while fast.next.data!=slow.data: fast = fast.next fast.next = ll.tail """ def solution2(ll): """ Time Complexity: O(n) Space Complexity: O(n) In this solution, we use set. """ h_set = set() current_node = ll.head.next while current_node.data != None: if current_node.data in h_set: # if loop needs to be removed, set tail node as the next of the previous node. return current_node.data else: h_set.add(current_node.data) current_node = current_node.next return -1 class TestClass(unittest.TestCase): test_ll_1 = LinkedList(initial_members=[1,2]) dup_node = test_ll_1.append(value=3) _ = test_ll_1.append(value=4) last_node = test_ll_1.append(5) last_node.next = dup_node test_ll_2 = LinkedList(initial_members=[1,2,3,4,5,6,7,8]) test_cases = [ (test_ll_1, 3), (test_ll_2, -1) ] test_functions = [solution1, solution2] def test_template(self): for test_function in self.test_functions: for t_input, e_output in self.test_cases: self.assertEqual(test_function(t_input), e_output) if __name__ == "__main__": unittest.main()
true
71885218b778cc0cc9afadbafb326b99569b469f
joshavenue/TIL-python
/confusing_forloop.py
378
4.1875
4
# you divide it in 3 parts: the _yielding_ part is the first `Word` , # then you have the _loop_ `for Word in WORD_TOKENS` and lastly, # you have the _condition_ `if not Word in STOP_WORDS` FILTERED_SENTENCE = [Word for Word in WORD_TOKENS if not Word in STOP_WORDS] # IS THE SAME AS BELOW for Word in WORD_TOKENS: if Word not in STOP_WORDS: yield Word
false
23bc0cc710743858138edb3f0072f5665f5e79dc
Lokesh824/DataStrucutres
/SinglyLinkedList/LinkedList_RotateList.py
2,201
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 13 15:56:37 2019 @author: inkuml05 """ class Node: def __init__(self, data): self.next = None self.data = data class LinkedList: def __init__(self): self.Head = None def append(self,data): new_node = Node(data) if self.Head is None: self.Head = new_node else: curr_node = self.Head while curr_node.next: curr_node = curr_node.next curr_node.next = new_node def print_List(self): curr = self.Head while curr: print('| {0} | {1} |'.format(curr.data, curr.next),end=' -> ') curr=curr.next print('\n') ''' The Given linked list should be rotated from the given position example - 1-2-3-4-5-6-7 and we give n as 4 then the output should be 5-6-7-1-2-3-4 Algorithm: 1.Store the head in some temp variable so that it can be used later 2.Move from the first node to the nth node (n is the given rotation value) 3.Then make the nth node next as none 4.Make the n+1th node as head node 5.Now iterate again and stop where the first null in next part occurs that is the rotated node end part and we should store in this inital head so that it will form a chain again ''' def rotate_list(self, n): c=1 temp_head = self.Head curr_node = self.Head while c<=n: curr_node = curr_node.next c+=1 new_head = curr_node.next curr_node.next = None self.Head = new_head new_curr = self.Head while new_curr.next: new_curr = new_curr.next break new_curr.next = temp_head return LL = LinkedList() LL.append(1) LL.append(2) LL.append(3) LL.append(4) LL.append(5) LL.append(6) LL.append(7) LL.print_List() LL.rotate_list(4) LL.print_List()
true
334e546c84d7885009414d79597c9094b1fa4aaf
DesireeRainey/sorts
/merge.py
1,381
4.3125
4
#Python Merge Sort import time import random def merge(arr1, arr2): results = [] while len(arr1) > 0 and len(arr2) > 0: if arr1[0] > arr2[0]: results.append(arr2.pop(0)) else: results.append(arr1.pop(0)) return results + arr1 + arr2 def merge_sort(arr): #base case: array length is less than or equal to one #recursive case: any other array length stored in the else if len(arr) <= 1: return arr #This states that the array is sorted else: # Find the middle index of the array. (needs to be an integer) middle_index = len(arr) // 2 #dividing the array in half between the left side and the right side left = arr[:middle_index] right = arr[middle_index:] #Recurse on the shorter lists left_sorted = merge_sort(left) right_sorted = merge_sort(right) #Now that I have sorted lists, merge them return merge(left_sorted, right_sorted) #test data for merge sorted random_arr = [1, 2, 4, 5, 6, 3, 77, 5] sorted_arr = merge_sort(random_arr) print("Result: ", sorted_arr) my_arr = [] for i in range(0, 100000)): my_arr.append(random.randint(0, 100000)) #time start_time = time.time() sorted_arr = merge_sort(my_arr) print(time.time() - start_time, ' seconds') #Test data for merge function # my_arr1 = [2, 3, 5] # my_arr2 = [1, 1, 2, 6] # print(merge(my_arr1, my_arr2))
true
dc7f52c08038a2921da8e5727eab7d08bc93e231
lily-liu-17/ICS3U-Unit3-04-Python-Month_Number
/month_number.py
1,049
4.46875
4
#!/usr/bin/env python3 # Created by: Lily Liu # Created on: Sept 2021 # This program converts the number to its corresponding month def main(): # This program converts the number to its corresponding month # input user_input = int(input("Enter the number of the month (ex: 5 for May) : ")) # process and output if user_input == 1: print("January") elif user_input == 2: print("February") elif user_input == 3: print("March") elif user_input == 4: print("April") elif user_input == 5: print("May") elif user_input == 6: print("June") elif user_input == 7: print("July") elif user_input == 8: print("August") elif user_input == 9: print("September") elif user_input == 10: print("October") elif user_input == 11: print("November") elif user_input == 12: print("December") else: print("Invalid input.") print("") print("Done.") if __name__ == "__main__": main()
true
9e228a898159f911345e282a57e739435c13b58a
mrthomasjackson/DPW
/learning_python/main.py
1,763
4.1875
4
#I am trying python for the first time __author__ = 'tjackson' welcome_message = "Welcome!" space = " " #this is a one line comment ''' Doc string (multiple line comments) ''' first_name = "Thomas" last_name = "Jackson" #print(first_name + " " + last_name) #response = raw_input("Enter Your Name") #print welcome_message + space + response birth_year = 1993 current_year = 2015 age = current_year - birth_year #print age print "You are " + str(age) + " years old" budget = 10000 if budget > 100000: high_car = "A8" print "Yeah, I can afford an " + high_car elif budget > 5000: print "Yay! You can afford a nice used car!" else: # print "Don't get upset, but you may have to wait a while before buying a car." pass characters = ["a","b","c"] #print characters characters.append("d") #print characters #print characters[2] alphabet = dict() #initiate dictionary alphabet = {"first": "a", "second": "b"} print alphabet["first"] #while loop ''' i = 100 while i>0: print str(i) + " bottles on the wall" i -= 1 #for loop for i in range(0, 100): print str(i), " bottles on the wall" i = i+1 #for each loop family = ["Scott", "Jenny", "Thomas", "Ellen"] for f in family: print f + " Jackson" #functions def convert_cm_in(): request = int(raw_input("How many centimeters would you like to convert?")) inches = (request * 2.54) return inches conversion = convert_cm_in() print conversion ''' #inputting variables into larger strings title = "This is very useful." body = "Yes, I agree with you." html = ''' <!DOCTYPE HTML> <html> <head> <title> {title} </title> </head> <body> {body} </body> </html> ''' html = html.format(**locals()) print html
true
7255ae920308382d90f7429a6fdd1b4ad5fbacf2
CesaireTchoudjuen/programming
/week04-Flow/Weeklytask04-collatz.py
597
4.40625
4
# Program that asks the user to input any positive integer and outputs the successive values of the following calculation # At each step calculate the next value by taking the current value and, if it is even, divide it by two, but if it is odd, multiply it by three and add one # Program ends if the current value is one value = int(input("Please enter a positive integer: ")) while value != 1: # Loop only runs when value is different than 1 if value % 2 == 0: value = value / 2 print(int(value)) else: value = ( value * 3) + 1 print(int(value))
true
ca6c1e7b3c4ada5a12875b77b2ed1fd98b14b5d0
CesaireTchoudjuen/programming
/Week05-Datastructures/Lab5.1.py
392
4.25
4
# Author: Cesaire Tchoudjuen # Create a tuple that stores the months of the year, from that tuple create another tuple with just the summer months (May, June, July), # print out the summer months one at a time months =("January", "February", "March", "April", "May", "June", "july", "August", "September", "October", "November", "December" ) summer = months[4:7] for month in summer: print(month)
true
0ddf38f7db811222edabfc4e52e8a105e1a64bd8
CesaireTchoudjuen/programming
/Week05-Datastructures/Lab5.4.py
477
4.3125
4
# Author: Cesaire Tchoudjuen # Program that stores a student name and a list of her courses and grades in a dict student = { "name":"Mary", "modules": [ { "courseName":"Programming", "grades": 45 }, { "courseName":"History", "grades": 99 } ] } print("Student: {}".format(student["name"])) for module in student["modules"]: print("\t {} \t: {}".format(module["courseName"], module["grades"]))
true
cc1d552b37290d710e1527ba18251d93566212ce
ni/NI-ELVIS-III-Python-Examples
/examples/digital/DIO_multipleChannels.py
2,510
4.28125
4
""" NI ELVIS III Digital Input and Output Example - Single Point, Multiple Channels This example illustrates how to write values to and read values from multiple digital input and output (DIO) channels. The program first defines the configuration for the DIO channels, and then writes to and reads from the DIO channels. Each time the write function is called, a data point is written to the channels; each time the read function is called, a data point is returned from the channels. The DIO configuration consists of two parameters: bank and channel. There are two identical banks of DIO channels (A and B). Each bank contains twenty digital input and output channels. Each DIO channel contains two directions: write and read. List all the channels you use, including read and write channels, in an array when configuring a DIO session. The NI ELVIS III helper library (academicIO.py) decides the direction based on the function called. Both the write and the read functions support reading/writing multiple channels. To write to multiple channels, list all the channels after the value to write, as indicated in the following line of code: write(value_to_write, [channel_to_write_1, channel_to_write_2, ...]) To read from multiple channels, list all the channels to read from, as indicated in the following line of code: read([channel_to_read_1, channel_to_read_2, ...]) This example uses: 1. Bank A, Channel DIO2, write direction. 2. Bank A, Channel DIO4, read direction. 3. Bank A, Channel DIO3, write direction. 4. Bank A, Channel DIO8, read direction. Hardware setup: 1. Connect DIO2 to DIO4 on bank A. 2. Connect DIO3 to DIO8 on bank A. Result: The program writes values to DIO2 and DIO3 and reads back values from DIO4 and DIO8 on bank A. """ import time from nielvis import DigitalInputOutput, Bank, DIOChannel # specify the bank bank = Bank.A # specify the DIO channels channel2 = DIOChannel.DIO2 channel3 = DIOChannel.DIO3 channel4 = DIOChannel.DIO4 channel8 = DIOChannel.DIO8 # configure a DIO session with DigitalInputOutput(bank, [channel2, channel3, channel4, channel8]) as DIO: # define the value as a Boolean value = False # write the value False to both DIO2 and DIO3 on bank A # the written value must be a Boolean variable DIO.write(value, [channel2, channel3]) # read values from DIO4 and DIO8 on bank A data = DIO.read([channel4, channel8]) # print the values read. The values read are [0,0] print(data)
true
80b1f540dbef03dccfa59a0018bd159b09e0667f
TripleM98/CSI-127-Assignments
/04/TheCollatzSequence.py
377
4.25
4
def collatz(number): if (number % 2 == 0): return number//2 elif(number % 2!=0): return number*3+1 try: n = int(input('Enter number:')) while n>1: print (collatz(n)) n=(collatz(n)) if(n<1): print('You must enter a number greater than or equal to 1.') except ValueError: print('Error: You must enter a number.')
true
03205d727383b65eebcc20252fe6831a82a65f4f
disfear86/Data-Analysis
/Udacity_Data_Analysis/convert_cols.py
709
4.125
4
import pandas as pd grades_df = pd.DataFrame( data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87], 'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]}, index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio', 'Fred', 'Greta', 'Humbert', 'Ivan', 'James'] ) def convert_one(grade): if grade >= 90: return 'A' elif grade >= 80: return 'B' elif grade >= 70: return 'C' elif grade >= 60: return 'D' else: return 'F' def convert_grades(grades): ''' Returns a new DataFrame of converted numerical to letter grades. ''' return grades.applymap(convert_one) new_df = convert_grades(grades_df) print new_df
true
181a446bb977ca8cec16c9eb1e9d57b0f90579d4
Dan-Blanchette/cs270-system-software
/pa5-Deadhuckabee-DanB-master/quick_sort/main.py
2,180
4.25
4
#!/usr/bin/env python3 # Dan Blanchette # CS-270 # quick sort and binary search part 2B # Acknowledgements: For removing encoding='uft-8-sig' # https://stackoverflow.com/questions/53187097/how-to-read-file-in-python-withou-ufef from quicksrt import quickSort from binSearch import binarySearch from PyDictionary import PyDictionary def main(): dictionary = PyDictionary() choice = True # Read all the words in words_notsorted.txt into a list # encoding call removes /uffef byte order mark from the file importing process # which was causing the first line entry of the file to be incorrectly sorted # to the end of the list. with open("words_notsorted.txt", encoding='utf-8-sig') as fileIn: wList = [] for words in fileIn: wList.append(words.rstrip()) # sort the list of words by passing it to the sorting function n = len(wList) quickSort(wList, 0, n-1) choice = [''] # loop until user wants to exit while True: # ask user to enter a word uInput = input("please enter a word: ") searchWord = "" searchWord = uInput # search the word in the list using binary search binarySearch(wList, 0, len(wList)-1, searchWord) # if word is found in the list results = binarySearch(wList, 0, len(wList)-1, searchWord) if results != -1: # write the code: print(dictionary.meaning(searchWord)) choice = input("Would you like to continue?\nEnter (1) for Yes\nor any key to continue: ") if choice == '1': print("The Program has exited successfully") break else: pass else: # prompt user, word not found print("Error: word was not found on the list") choice = input("Would you like to continue?\nEnter (1) for Yes\nor any key to continue: ") if choice == '1': print("The Program has exited successfully") break else: pass # exit out of the loop if user wants to stop if __name__ == "__main__": main()
true
d95ca70a76412181d75b5a0f74ef43de76a3f910
zezhouliu/am106
/p2/mmi.py
537
4.125
4
import sys import extended_euclid def mult_mod_inverse(n, p): ''' Applies the extended euclids in order to calculate the multiplicative modular inverse. returns x such that n * x = 1 mod p ''' r1, r2 = extended_euclid.extended_euclids(n, p) if r1 < 0: r1 = r1 + p return r1 if __name__ == '__main__': # num args and args num_args = len(sys.argv) if num_args != 3: print 'usage: python p6.py n p' else: print mult_mod_inverse(int(sys.argv[1]), int(sys.argv[2]))
true
533cb3d8959636d0a559f5a60fa08134c657244e
iAreth/arm
/strings.py
880
4.625
5
myStr = "AdayDos" print("My name is " + myStr) # Sumando | Uniendo Strings print("Uso de {f}") print(f"My name is {myStr}") # Palabra clave de Python | Que es lo que podemos hacer con un cierto tipo de datos # upper | Mayuscula # lower | Minuscula # count | Contar cuantas veces se esta utilizando un caracter # print("Tipo de dato upper:") # print(myStr.upper()) # print("Tipo de dato lower:") # print(myStr.lower()) # print("Tipo de dato replace:") # print(myStr.replace('Hello', 'Byeee').upper()) # print("count:") # print(myStr.count('o')) # print("Tipo de dato split:") # print(myStr.split('o')) # print("Tipo de dato find") # print(myStr.find('d')) # print("Tipo de dato index") # print(myStr.index('ll')) # print("Tipo de dato numerico") # print(myStr.isnumeric()) # print("Tipo de dato alfanumerico") # print(myStr.isalpha()) print(myStr[2]) # Inverso print(myStr[-1])
false
d82d9f4cf66e670676417cf7109d7cdfd4cda43c
AcerAspireE15/python-exception-handling
/12.py
744
4.125
4
def function1(a, b): print(a+b) print(a*b) print(a-b) print(a/b) print(a%b) function1(20, 3) print('hello') try: a = 20 b = 0 print(a/b) except ZeroDivisionError: print('there is a divide by zero error') try: a = 20 b = 10 print(a/b) except ZeroDivisionError: print('there is a divide by zero error') try: a = 20 b = 0 print(a/b) except ZeroDivisionError: print('there is a divide by zero error') finally: print('this is going to execute no matter what') try: a = 20 b = 10 print(a/b) except ZeroDivisionError: print('there is a divide by zero error') finally: print('this is going to execute no matter what')
true
45096fc08cf5eefb39ec06eb1f85aa3fe1191ac5
Omiee123/Mordern-Cryptography
/Diffi Hellman Algo.py
943
4.25
4
#!/usr/bin/env python # coding: utf-8 #Diffi Hellman Key Exchange Algorithm #Step 1 : Choose Random Number A,B (Private Random Number) #Step 2 : Choose g and p (Shared Value) #Step 3 : Find Xa and Xb (Xa = g**a mod p & Xb = g**b mod p) #Step 4 : Share Xa and Xb #Step 5 : Key Generation k = Xb**a mod p = xa**b mod p #Step 1 : Choose Random Number A,B (Private Random Number) A = int(input("Choose Random Number for A : ")) B = int(input("Choose Random Number for B : ")) #Step 2 : Choose g and p (Shared Value) g = int(input("Enter g : ")) p = int(input("Enter p : ")) #Step 3 : Find Xa and Xb (Xa = g**a mod p & Xb = g**b mod p) xa = (g**A)%p xb = (g**B)%p #calculated individually #Step 4 : Share Xa and Xb print("xa : "+str(xa)) print("xb : "+str(xb)) #Step 5 : Key Generation k = Xb**a mod p = xa**b mod p print("Key Recived by xa") k_A = (xb**A)%p print("k : "+str(k_A)) print("Key Recived by xb") k_B = (xa**B)%p print("k : "+str(k_B))
false
4f6a55c21dd48d5730f61e46124d8dcfc90527ed
shrikantnarvekar/Python-GUI
/checkdates.py
513
4.125
4
from date import Date def main(): bornBefore = Date(6, 1, 1988) date = promptAndExtractDate() while date is not None : if date <= bornBefore : print( "Is at least 21 years of age: ", date ) date = promptAndExtractDate() print( "Enter a birth date." ) month = int( input("month (0 to quit): ") ) if month == 0 : return None else : day = int( input("day: ") ) year = int( input("year: ") ) return Date( month, day, year ) main()
true
7fdee8036dbffc95abe749d3e6dd8fd7456442df
brittanyp/CP1404-Workshops
/WS2/shipCalc.py
382
4.1875
4
quantity = int(input("Enter amount of item: ")) while quantity < 0 : print("Invalid input") quantity = int(input("Enter amount of item: ")) costPerItem = float(input("Enter shipping cost per item: ")) totalCharge = costPerItem * float(quantity) if totalCharge > 100 : totalCharge = totalCharge - (0.1 * totalCharge) print("Your shipping cost is: $%.2f" % totalCharge)
true
a528f8676030d3c51cd07a913f030a769b781522
chipoltie0/Roguelike_v1.1
/GamePiece.py
1,412
4.28125
4
class Piece: """ This is the base object that interacts with the map object, contains information such as the location of the object, what map it is on, and possible a connected character sheet """ def __init__(self,map, start_point, collision=False,color=(0,0,0),char='*'): self.map = map # store the map this piece is on self.location = start_point # store location of the piece self.collision = collision self.color = color self.char = char def move_piece_to(self,point,map=None): """ moves a piece to a new location :param point: point to change the piece's location :param map: map to move the piece to, if None, then same map currently on :return: nothing, updates self.location """ if map is not None: self.map = map self.location = point class Stair(Piece): """ This is a special case of piece that can change the player's level """ def __init__(self,map, point, color,end_floor, char = '/'): super().__init__(map,point,color,char=char) self.end_floor = end_floor def interact(self, piece: Piece): """ when a piece interacts with the stairs, it changes the pieces map value :param piece: piece that interacted :return: nothing, edits piece """ piece.map = self.end_floor
true
89158eb6b1effb875571a0fcdebf4b6396901f9e
SoniaRode21/Python
/SearchingAndSorting/FOAproject1/quickSort.py
1,159
4.25
4
_author = 'Soniya Rode' ''' The program includes functions to partition the array and quick sort the data. ''' def partition(arr, l, r): ''' Function to partition the array based on pivot value :param array: list containing elements to be sorted :param l : left most index of the list :param r : right most index of the list :return: partition index ''' small = (l - 1) #pivot value is the rightmost value of the list pivot = arr[r] for _ in range(l, r): # If current element is smaller than or # equal to pivot if arr[_] <= pivot: # increment index of smaller element small = small + 1 arr[small], arr[_] = arr[_], arr[small] arr[small+ 1], arr[r] = arr[r], arr[small + 1] return (small + 1) def quickSort(array,l,r): ''' Function to sort the data :param array: list containing elements to be sorted :param l : left most index of the list :param r : right most index of the list :return: None ''' if l<r: q=partition(array,l,r) quickSort(array,l,q-1) quickSort(array,q+1,r)
true
c8763f1099ce7b22739d80cce03a639ef1eb18ec
jaehyunan11/Python_Learning
/Day_27/challenge_1.py
921
4.28125
4
from tkinter import * """ 1. Pack -> default located in the upper center ex: input.pack(side="left") 2. Place -> Specific coordinate ex: my_label.place(x=100, y=200) 3. Grid -> Row and column """ # Window setup window = Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) window.config(padx=100, pady=200) # Label my_label = Label(text="I am a Label", font=("Arial", 24, "bold")) my_label.config(text= "New Text") my_label.grid(column=0, row=0) my_label.config(padx=50, pady=50) # Button def button_clicked(): print("I got clicked") new_text = input.get() my_label.config(text = new_text) button = Button(text="Click Me", command=button_clicked) button.grid(column=1, row=1) new_button = Button(text="New Button", command=button_clicked) new_button.grid(column=2, row=0) # Entry input = Entry(width=10) print(input.get()) input.grid(column=3, row=2) window.mainloop()
true
fc47f571e5d321bf5de59b7a82f2e85b8f763719
jaehyunan11/Python_Learning
/Day_27/main.py
2,311
4.15625
4
from tkinter import * window = Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) #Label my_label = Label(text="I am a Label", font=("Arial", 24, "bold")) my_label.pack() # my_label["text"] = "New Text" my_label.config(text= "New Text") # Button def button_clicked(): print("I got clicked") new_text = input.get() my_label.config(text = new_text) button = Button(text="Click Me", command=button_clicked) # in order to layout in the screen. button.pack() # Entries entry = Entry(width=30) # Add some text to begin with entry.insert(END, string="Some text to begin with.") # Gets text in entry print(entry.get()) entry.pack() # Text text = Text(height=5, width=30) # Puts cursor in textbox text.focus() # Adds some text to begin with. text.insert(END, "Example of multi-line") # Get's current value in textbox at line character 0 print(text.get("1.0", END)) text.pack() # Spinbox def spinbox_used(): print(spinbox.get()) spinbox = Spinbox(from_= 0, to=10, width=5, command=spinbox_used) spinbox.pack() # Scale # Called with current scale value def scale_used(value): print(value) scale = Scale(from_= 0, to = 100, command = scale_used) scale.pack() # Checkbutton def checkbutton_used(): print(checked_state.get()) checked_state = IntVar() checkbutton = Checkbutton(text="Is on?", variable= checked_state, command=checkbutton_used()) checked_state.get() checkbutton.pack() # Radiobutton def radio_used(): print(radio_state.get()) # Variable to hold on to which radio button value is checked radio_state = IntVar() radiobutton1 = Radiobutton(text="Option1", value=1, variable=radio_state, command=radio_used) radiobutton2 = Radiobutton(text="Option2", value=2, variable=radio_state, command=radio_used) radiobutton1.pack() radiobutton2.pack() # Listbox def listbox_used(event): # Gets current selection from listbox print(listbox.get(listbox.curselection())) listbox = Listbox(height=4) fruits = ["Apple", "Pear", "Orange", "Banana"] for item in fruits: listbox.insert(fruits.index(item), item) listbox.bind("<<ListboxSelect>>" , listbox_used) listbox.pack() window.mainloop()
true
769f56fe12f0c5f4557142390f77794e85ba6696
joyc/python-book-test
/AutomatePython/scr/isPhoneNumber.py
857
4.15625
4
def isPhoneNumber(text): if len(text) != 13: return False # not phone number-sized for i in range(0, 3): if not text[i].isdecimal(): return False # not an area code if text[3] != '-': return False # does not have first hyphen for i in range(4, 8): if not text[i].isdecimal(): return False # does not have first 4 digits if text[8] != '-': return False # does not have second hyphen for i in range(9, 13): if not text[i].isdecimal(): return False # does not have last 4 digits return True # "text" is a phone number! message = 'Call me at 415-5155-1011 tomorrow. 415-5155-9999 is my office.' for i in range(len(message)): chunk = message[i:i+13] if isPhoneNumber(chunk): print('Phone number found: ' + chunk) print('Done')
true
479efa73a80822daa2a50e7a3e29df47bc206b63
Ellipse404/100-Exercises-Python-Programming-
/100+ Exercises Solved/Question - 4.py
494
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 13 19:47:56 2019 @author: BHASKAR NEOGI """ # Level 1 try : l = input("Enter Comma(,) Seperated Numbers : ") y = l.split(",") t = tuple(y) print(t,y) # print(y) print("::------------ Another One ------------::") k = input("Numbers : ") h = k.split(",") print(h) print(int(k)) print(tuple(k)) except ValueError : print("Please Choose The Correct Value :")
false
f0095dcba414f444da0fc2290894261f554ab373
Ellipse404/100-Exercises-Python-Programming-
/100+ Exercises Solved/Question - 8.py
323
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 17 13:04:41 2019 @author: BHASKAR NEOGI """ # Level - 2 w = input("Enter the Words You Want To list Alphabetically Seperated By Comma ',' :: ").split(",") w.sort() print("Output In List : ",w) print("Output In Comma Seperated Style : ",','.join(w))
false
b410b9665dd20ae1203f8cf7d474fbb50046a331
Matheusdehsouza/Process_Kaffa
/exercise 1/CNPJ1.py
681
4.125
4
#Programa desenvolvido em Python para verificação se o digitado se parece com um CNPJ cnpj = input(' Digite os 14 números do seu CNPJ: ') .replace (".","") .replace ("/","") .replace ("-", "") #Linha para a digitação do CNPJ e comandos para que o ponto, barra e traço não sejam contados conta = len(cnpj) #linha para a leitura do CNPJ, quantos carcteres, fora os que não são contados, tem if conta != 14: print("CNPJ inválido!") #Primeira parte, se não houver 14 caracteres, não se parece então irá aparecer uma mensagem de erro else: print("CNPJ aceito") #Segunda parte, se tiver os 14 aceitáveis, se parece com um CNPJ, logo é aceito
false
301ac2b22fd395a78ceb5d8bbe9f75e05dee0c1b
SamuelVera/Algorithims-Misc
/bucketSort/Python/bucketSort.py
2,159
4.3125
4
def insertSort(arr: list, order: str = "asc") -> list: """Apply insert sort in the given order for the given array of integers ------------------- Complexity: Time: O(n^2) Space: O(n) Array in memory ------------------- Parameters: arr : list List to order order : "asc" | "desc" Order type, ascending or descending ------------------- Returns: list Ordered list """ cacheArr = arr.copy() #Cache array n = len(cacheArr) #List length #Actual algorithm for i in range(1, n): #Iterate from 1 to n - 1 key = cacheArr[i] #Cache key j = i - 1 #Previous index if order == "asc": #Ascending order while j >= 0 and key < cacheArr[j]: #Iterate in reverse until spot is found cacheArr[j + 1] = cacheArr[j] #Move higher numbers up j -= 1 #Move reverse index a place else: #Descending order while j >= 0 and key > cacheArr[j]: #Iterate in reverse until spot is found cacheArr[j + 1] = cacheArr[j] #Move lower numbers up j -= 1 #Move reverse index a place cacheArr[j + 1] = key #Set key to position return cacheArr #Return ordered array def bucketSort(A: list, order: str = "asc"): """Do bucket sort to the given list A""" slot_num = 10 #Number of buckets arr = [] #Buckets for i in range(0, slot_num): #Initialize buckets arr.append([]) for i in A: #Fill the buckets j = int(slot_num * i) #Index for bucket arr[j].append(i) #Put into bucket for i in range(0, slot_num): #Sort the buckets arr[i] = insertSort(arr[i], order) #Do insert sort over array and overload k = 0 #Pointer for return if order == "asc": for i in range(0, slot_num): #Build output array for j in range(0, len(arr[i])): A[k] = arr[i][j] k += 1 else: for i in reversed(range(0, slot_num)): #Build output array for j in range(0, len(arr[i])): A[k] = arr[i][j] k += 1 return A
true
d61520033fdb1d0402bb719b9242cf18095d62e2
achillesecos/15-112-term-project
/dijkstra.py
2,139
4.15625
4
#Term Project #Achilles Ecos #aecos #Graph Theory #Cite Pseudo code from Wikipedia #https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm class Graph: def __init__(self): #dictionary of nodes to its neighboring nodes where key is node and #value is array of neighboring nodes self.graph = {} self.weight = {} #add the "line" from a node to another node def addEdge(self, start, end, distance): #normal order if start not in self.graph: self.graph[start] = [end] else: self.graph[start].append(end) #Reverse order if end not in self.graph: self.graph[end] = [start] else: self.graph[end].append(start) self.weight[(start,end)] = distance self.weight[(end,start)] = distance #returns an array of nodes that neighbor a node def getNeighbors(self, node): return self.graph[node] #returns the distasnce between two nodes def getWeight(self, node1, node2): return self.weight[(node1, node2)] def dijkstra(graph, initial, target): #array of different nodes to check que = [] #distance from initial start to node distance = {} #the previous nodes checked previous = {} distance[initial] = 0 #inital has no previous node previous[initial] = None que.append(initial) #check through all the nodes while len(que) != 0: #access first node from que node = que.pop(0) #more efficient if node == target: break #check neighbor nodes for neighbor in graph.getNeighbors(node): tmpDist = distance[node] + graph.getWeight(neighbor, node) #if tempDistance is less than previous distance, update distance #when checking distance of new node, also update distance if neighbor not in distance or tmpDist < distance[neighbor]: que.append(neighbor) distance[neighbor] = tmpDist previous[neighbor] = node return distance, previous graph = Graph() graph.addEdge(1,2,7) graph.addEdge(1,3,9) graph.addEdge(1,6,14) graph.addEdge(2,3,10) graph.addEdge(2,4,15) graph.addEdge(6,3,2) graph.addEdge(6,5,9) graph.addEdge(3,4,11) graph.addEdge(4,5,6) dist, prev = dijkstra(graph,1,5) print(prev) print(graph.graph) print(dist) print(dijkstra(graph,1,5))
true