blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
281fdddb4ac2a1e928f69debc41dde0e262f7a25
michaelzhou88/Compound-Interest
/compound_interest.py
1,091
4.15625
4
# Estimated yearly interest # Function that calculates the compound interest based on the user's inputs def compound_interest(principal_amount, interest_rate, years): result = (principal_amount * pow((1 + interest_rate),years)) return result # Prompting user to enter the principal amount to start off with print('How much money is currently in your account') principal_amount = float(input('Enter amount in pounds and pence: ')) # Prompts user to the enter their annual interest rate print("What do you estimate will be the yearly interest of this investment? ") interest_rate = float(input('Enter interest in decimal numbers : (e.g. 10% = 0.1) ')) # Prompts user to enter the number of years they intend to the save for print('How many years will you be save?') years = float(input('Enter years: ')) print('') # Invokes the compound_interest function to perform the calculation final_amount = round((compound_interest(principal_amount, interest_rate, years)),2) # Outputs result print("In " + str(int(years)) + " years, your balance would be: £" + str(final_amount))
true
15f70d0f7337d468fef8ad2c0bebb4951abffcd9
User9000/python_own
/strings_keyword.py
371
4.625
5
# #String substitution # # ###Example1 var = "Carlo Lam" print("My name is {var}".format(var=var)) #Example 2 the_name = input("Enter the name: ") print("The name you enter is: {the_name}".format(the_name= the_name)) #Example 3 variable_name = "Carlo" print("The name is {variable_name} \n {variable_name} is {variable_name}".format(variable_name= variable_name))
true
20c68c524d06586bc3797960f851a71c12113c8a
MichaelGatesDev/CSC285_PSU
/projects/project2/dbutils.py
1,368
4.25
4
#!/usr/bin/env python3 # Michael Gates # 11 September 2018 import sqlite3 """ -------------------- | Phone | Name | Phone Number | INT PRIM | TEXT | Individual's Name -------------------- """ def create_db(file): print("Creating database: " + file) con = sqlite3.connect(file) cursor = con.cursor() command = """CREATE TABLE IF NOT EXISTS people ( phone_number INTEGER PRIMARY KEY, name TEXT ); """ cursor.execute(command) con.commit() con.close() print("Created database " + file) def insert(file, name, phone): con = sqlite3.connect(file) cursor = con.cursor() command = "INSERT INTO people VALUES (\"" + phone + "\", \"" + name + "\");" cursor.execute(command) con.commit() con.close() def find(file, phone): con = sqlite3.connect(file) cursor = con.cursor() command = 'SELECT name FROM people WHERE phone_number = "' + phone + '";' cursor.execute(command) rows = cursor.fetchall() for row in rows: print("Found user with phone number " + phone + ": " + str(row[0])) def printAll(file): con = sqlite3.connect(file) cursor = con.cursor() command = 'SELECT * FROM people;' cursor.execute(command) rows = cursor.fetchall() print("List of all people/numbers:") for row in rows: print(str(row[0]) + ", " + row[1])
false
ec97b7b1bc507f58ce9efbf9749ea298fd3ad412
mshubat/Data-Structures-Algorithms
/4 - Trees and Graphs/44-check_balanced.py
1,619
4.25
4
''' Implement a function to check if a binary tree is balanced. For the purpose of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. Solution: Could get the height of left and right subtrees. Starting at the root and recursiively getting the heights of subtrees all the way down the tree. If heights differ by more than 1 then return False (ie. the tree is not balanced) otherwise return True (the tree is balanced.) ''' from BST.binary_search_tree import binary_search_tree from BST.node import node def get_balanced(root): return is_balanced(root) != -1 def is_balanced(node): if node.getLeft(): left_height = is_balanced(node.getLeft()) else: left_height = 0 if node.getRight(): right_height = is_balanced(node.getRight()) else: right_height = 0 if left_height == -1 or right_height == -1: return -1 if abs(left_height-right_height) > 1: return -1 else: return max(left_height, right_height) + 1 if __name__ == "__main__": bst = binary_search_tree(5) print(bst.root.value) bst.insert_iteratively(3) bst.insert_iteratively(7) bst.insert_iteratively(8) bst.insert_iteratively(6) bst.insert_iteratively(4) bst.insert_iteratively(2) print(f"bst is balanced: {get_balanced(bst.root)}") bst = binary_search_tree(5) print(bst.root.value) bst.insert_iteratively(7) bst.insert_iteratively(8) bst.insert_iteratively(6) print(f"bst is balanced: {get_balanced(bst.root)}")
true
419db1a87f4bb5f40f2a95470c59507ce6c4934d
mshubat/Data-Structures-Algorithms
/10 - Sorting and Searching/Sorting Algorithms/SelectionSort.py
1,042
4.125
4
''' Selection Sort Description: Seletion sort is a simple yet inefficient algorithm. "The Childs algorithm". It works by doing a linear scan through the elements, selecting the smallest one, and moving it to the front of the list. Repeating this process untill the list is sorted. Time Complexity: O(n^2) average and worst case Space Complexity: O(1) ''' # Helpers def swap(arr, index1, index2): temp = arr[index2] arr[index2] = arr[index1] arr[index1] = temp return arr def selectionSort(lst): start = 0 while start<len(lst): smallest = lst[start] smallIndex = start for i in range(start, len(lst)): if lst[i]<smallest: smallest = lst[i] smallIndex = i swap(lst, start, smallIndex) start +=1 return lst if __name__ == "__main__": print("Selection Sort!") # test 1 nums = [1,4,5,2,3,7,9,8,0,6] print(selectionSort(nums)) # test 2 nums = [11, 25, 12, 23, 73, 936] print(selectionSort(nums))
true
18d252a5e1ee854308b93045526c4c9a3bdd6da6
kamvir/Python_Tutorials
/Flow Control Statements/logical_operators.py
550
4.15625
4
title = '==================== Logical Operators ====================' note = 'Note :: Please refer code for better understanding.' print(title) has_high_income = False has_good_credit = True has_criminal_record = False # Logical 'and' operator if has_high_income and has_good_credit: print("Eligible for loan") # Logical 'or' operator if has_high_income or has_good_credit: print("Eligible for loan") # Logical 'not' operator if has_good_credit and not has_criminal_record: print("Eligible for loan") print(note) print(title)
true
fa4f5858ea0fae65c7a8015cf6ee0eee6191bd50
pytommaso/Appunti
/20 - Recursion_2.py
828
4.25
4
def sum_recursive(n, current_sum): # Base case # Return the final state if n == 11: return current_sum # Recursive case # Thread the state through the recursive call else: return sum_recursive(n + 1, current_sum + n) # - - - - - - - - - - - - - - - - - - # list is a Recursive Data Structures attach_head(1, # Will return [1, 46, -31, "hello"] attach_head(46, # Will return [46, -31, "hello"] attach_head(-31, # Will return [-31, "hello"] attach_head("hello", [])))) # Will return ["hello"] # Recursive data structures and recursive # functions go together like bread and butter
true
6bf023b0a5d3d0a297aa6144f9a6b61a72480b94
jogubaba/PythonScripts
/3Billingforloop.py
310
4.125
4
Quantity = input("How many item's have you taken? ") item = 0 list = 0 total = 0 while item < int(Quantity): Price = input("Enter price for the retail items you have taken one after the other ") for list in Price: total += int(list) print(list) print(total) item += 1 break
true
45e9a5e29ae03a1257c4da3ad914946c076a3533
blancopedro/ATBSWP
/Ch 03 - Practice Questions - Solutions.py
2,298
4.625
5
# Ch 03 Practice Questions # 1) Why are functions advantageous to have in your programs? # A function is a like a program that you can built in order to solve your own problems. # 2) When does the code in a function execute: when the function is defined or when the function is call? # The function is execute when the function is call. We can define our function but not call it # 3) What statement creates a function? # def. For example def hello(): # 4) What is the difference between a function and a function call? # A function is a block of code that perform some calculation and return something. Instead, a function call invoke or call (sorry for the repetition) the block of code we define before. # 5) How many global scopes are there in a Python program? How many local scopes? # 6) What happens to variable in a local scope when the function call returns? # The local variable is destroyed and there is no longer a variable # 7) What is a return value? Can a return value be part of an expression? # Return is used to end the execution and return the value to the caller. For example: # 8) If a functions does not have a return statement, what is the return value of a call to that function? # Return nothing, the return value will be None. # 9) How can you force a variable in a function to refer to the global variable? # With the global statement. Form example """ x = "Pedro" def name(): global x print("Mi nombre es " + x) """ # 10) What is the data type of None? # NoneType. Is a value without a value # 11) What does the import areallyourpetsnamederic statement do? # Is the name of a module. With it you can use functions from other modules # 12) If you had a function named bacon() in a module named spam, how would yo ucall it after importing spam? # We need to use spam.bacon() # 13) How can you prevent a program from chashing when it gets and error? # Using the try and except code. For example # def spam(divideBy): # return 10 / divideBy # try: # print(spam(0) # except ZeroDivisionError: # print("Error: Invalid argument.") # # # 14) What goes in the try clause? What goes in the except clause? # When try result in an error the program will goes to except in order to return it
true
e7624cc9df946921a28956437392b30408971448
annettemathew/palindrome
/palindrome.py
929
4.46875
4
#2. Reverse a string and check if it is a Palindrome #Ex : malayalam - "is a palindrome" #english - "is not a palindrome" word = input('Please enter a string to reverse(case-sensitive): ') reversedString=[] #new emptylist called reversedString index = len(word) # calculate length of string and save in index while index > 0: reversedString += word[ index - 1 ] # save the value of str[index-1] in reverseString index = index - 1 # decrement index palindrome = True #initialize boolean #loop through length of both strings & compare each character for i in range(0, int(len(word))): #from 0 to length of the string if word[i] != reversedString[i]: #if the character at any index of the string = the # character at the same spot of it's reverse print(word, " is not a palindrome") palindrome = False # else # print(word, "is a palindrome") print(palindrome)
true
f15a8db41176cf51c94c8be69f31b5506759e18b
CsacsoBacsi/VS2019
/Python/PythonTutorial/PythonTutorial/Type-class.py
1,240
4.3125
4
# -------------------------------------------------------------------- import os # -------------------------------------------------------------------- # We can define a class A with type (classname, superclasses, attributedict) # "classname" is a string defining the class name and becomes the name attribute; # "superclasses" is a list or tuple with the superclasses of our class. This list or tuple will become the bases attribute; # the attributes_dict is a dictionary, functioning as the namespace of our class. It contains the definitions for the # class body and it becomes the dict attribute. class Robot: counter = 0 def __init__ (self, name): self.name = name def sayHello (self): return "Hi, I am " + self.name def Rob_init (self, name): self.name = name Robot2 = type ("Robot2", (), {"counter":0, "__init__": Rob_init, "sayHello": lambda self: "Hi, I am " + self.name}) x = Robot2 ("Marvin") print (x.name) print (x.sayHello ()) y = Robot ("Marvin") print (y.name) print (y.sayHello ()) print (x.__dict__) print (y.__dict__) # -------------------------------------------------------------------- os.system ("pause")
true
47d3d59a59c407ec41991dab59a6f3b2dd0f60ee
dctime/python-1a2b-dctime
/Main.py
2,588
4.28125
4
from Game import Game from Player import Player from Robot import Robot # player_obj_list # stores player objects player_obj_list = [] # player_obj_list # stores player objects robot_obj_list = [] # game : object list # store the game objects which program made during runtime game = [] # times : int # stores how many times the game runs times = 0 while 1: print("Welcome playing") while 1: try: # player_quantity : int # the quantity of players player_quantity = int(input("How many players? ")) except ValueError: print("Don't Enter things that isn't an number, please enter it again.") else: break print() # adding players print("Enter Names") for i in range(player_quantity): print(i+1, ": ", sep='', end='') name = input() # name : str, temporarily stores the name that user inputs obj = Player(name) # obj : Player, temporarily stores the objects, ready to append to player_obj_list player_obj_list.append(obj) print() # deleting temporarily variables del name, obj # ask if wanna add robots into the game # ask_robot : str, temporarily # stores the answer of adding robot into this game ask_robot = input("Wanna add robot into this game? Enter 'y' to add, others no : ") if ask_robot == 'y': # robot_quantity : int # the quantity of robots while 1: try: robot_quantity = int(input("How many robots? ")) except ValueError: print("Don't Enter things that isn't an number, please enter it again.") else: break print() # adding robots print("Enter Names") for i in range(robot_quantity): print("Robot ", i + 1, ": ", sep='', end='') name = input() # name : str, temporarily stores the name that user inputs obj = Robot(name) # obj : Robot, temporarily stores the objects, ready to append to player_obj_list robot_obj_list.append(obj) print() # start the game game.append(Game(player_obj_list, robot_obj_list)) game[times].start() print("Restart? Enter 'y' to restart, others to quit") # restart_decision : str, temporarily # if wanna restart, it will store y restart_decision = input() if restart_decision != 'y': break # start zeroing player_obj_list = [] robot_obj_list = [] # add one to times because of starting a new game times += 1
true
a61fdeccd445f8dff4e1a41bbb3b6375b3735a97
marlondocouto/PythonProgramming
/assignment8.py
939
4.21875
4
#assingment8.py #Author: Marlon Do Couto #A program that calculates payment according to hours worked in a week def main(): print("This program calculates your weekly total pay.\n") #input from user - wage and hours worked wage=float(input("What is your hourly wage? ")) hours=float(input("How many hours did you work this week? ")) """processing through if statements if user worked more than 40 hours then total wage will be a combination of the first 40 hours * wage plus the additional hours *1.5*wage:""" if hours>40: total_wage1=40*wage total_wage2=(hours-40)*1.5*wage #output: print("\nYour total weekly pay is ",total_wage1+total_wage2) #if user did not work over 40 hours, then calculation is straigh forward: else: total_wage=wage*hours #output: print("\nYour total weekly pay is ",total_wage) main()
true
f0e0354a3a69d2accb5e65c2748f2ca9c2bc34dd
whoisapig/PythonBase
/切片/Code.py
941
4.21875
4
#!/usr/bin/python #coding:utf-8-8 # range()函数可以创建一个数列: # # >>> range(1, 101) # [1, 2, 3, ..., 100] # 请利用切片,取出: # # 1. 前10个数; # 2. 3的倍数; # 3. 不大于50的5的倍数。 L = range(1,101) print L[:10] print L[2::3] print L[4:50:5] # 利用倒序切片对 1 - 100 的数列取出: # # * 最后10个数; # # * 最后10个5的倍数。 L = range(1,101) print L[-10:] print L[-46::5] # 字符串有个方法 upper() 可以把字符变成大写字母: # # >>> 'abc'.upper() # 'ABC' # 但它会把所有字母都变成大写。请设计一个函数,它接受一个字符串,然后返回一个仅首字母变成大写的字符串。 # # 提示:利用切片操作简化字符串操作。 def firstCharUpper(s): if len(s) > 0 : return s[:1].upper()+s[1:] return s print firstCharUpper('hello') print firstCharUpper('sunday') print firstCharUpper('september')
false
5e51014818fbef75c956695429e0d50df02a56f3
Hanifff/Digital-signature
/dss/global_paramters.py
2,217
4.125
4
import math def prime_numbers(length): """ Calulate prime numbers in the range of length parameter. """ primes = [] for i in range(2,length): #string from number 3, not interested in p numbers 1 and 2 for j in range(2,i): #start from 2 until the half of each nr to check divisibilty if i % j == 0: break else: primes.append(i) return primes def filter_primes(primes): """ Filter the prime number to be in format of p = 2*q + 1 """ filtered_primes = [] for i in primes: p = (2*i)+1 if p in primes: filtered_primes.append(p) return filtered_primes def primitive_root(prime_nr): """ calcualte the primitive roots of the prime_nr """ prime_factors = [] prim_roots = [] division = [] eu_phi = prime_nr -1 # euler totient function (its a prime number so the answer is simply p-1) prime_nrs = prime_numbers(eu_phi) # find all primes in range of the prime nr -1 for i in prime_nrs: # prime factors of the eu_phi if eu_phi % i == 0: prime_factors.append(i) for i in prime_factors: # calculating the prime factors devided by each prime factors of phi_n n_i = int(eu_phi/i) division.append(n_i) # dision contains all numbers that the prime factor are divisible with for i in prime_nrs: # looping thorugh all prime numbers again counter = 0 # set a counter, so if for each prime number p ==> p^(divisible_i nr) mod prime_nr != 1 for j in division: if pow(i, j, prime_nr) != 1: counter += 1 if counter == len(division): prim_roots.append(i) return prim_roots def public_numbers(interval=500): """ Calculate the publlic numbers of the Diffi-Hellman algorithm.""" prime_nrs = prime_numbers(interval) filter_p = filter_primes(prime_nrs) q = filter_p.pop() # last index is the largest prime number in the interval primitves = primitive_root(q) generator = primitves[0] # pickup the first element that the generator of the cyclic group return q, generator
true
b66a93eb4d3be843116bf21660fa037b5488727f
DevYanB/Penney_Ante
/Penney_Ante_Code.py
2,666
4.375
4
import time import random #This is a code inspired by the Penney Ante Logic and Chance Game! Time.sleep's are included for dramatic effect! usr_score = 0 cmp_score = 0 #First section asks user for their input, uses the basic strategy for highest probability of winning to choose its own; #Based on non-transitive probability tree of this game(check online), if user gives ABC, optimal result is (!B)AB; #Makes sure string input is valid; #Initiates the game. print("Hello! Welcome to the Penney Ante Game! \nPick a series of three coin-flip results!\nFirst to 5 wins! \n*Please use lowercase!*") while True: usr = input() if((len(usr) < 3) or (len(usr) > 3)): print("Enter a valid sequence") continue; else: break mid = usr[1:2] if mid == 't': cmp = 'h' + usr[0:2] elif mid == 'h': cmp = 't' + usr[0:2] print("Alright, good choice!") time.sleep (2) print("I choose: " + cmp) time.sleep(2) print("Now, let us play!") print("") time.sleep(3) #This next portion is the actual game; #It randomizes the head or tail values corresponding to 1 or 2 and adds them to a list l; #Then, it checks if a sequence of three appears mathcing either the user's or computer's choice; #If it does, it will add a point to the respective party and start flipping again! l = [] c = 0 while(c <= 10000): c += 1 x = random.randint(1,2) if x == 1: l.append('h') else: l.append('t') print(l, end="\r") time.sleep(1) if len(l) >= 3: n = c-3 v = ''.join(l[n:(n+3)]) #This function here creates a string of the last 3 terms(once 3 or more terms long) from the array l #and adds spaces between them for comparison to the user inputted string; #Can also just use basic string and concatenation without spaces, but important fact is that it uses 3 most recent terms; #Subtracting 3 from c, setting it as n, then getting substring from n to n+3. works well i think. if v == usr: usr_score += 1 l.clear() print("\nOne for you...\n") time.sleep(2) c = 0 elif v == cmp: cmp_score += 1 l.clear() print("\nOne for me!!!\n") time.sleep(2) c = 0 if cmp_score == 5: print("I win!!!") print ("\nUser Score: " + str(usr_score)) break elif usr_score == 5: print("You win...") print("\nComputer Score: " + str(cmp_score)) break
true
a37bb6838e429527c9e233f410880f05cc34d8c1
Wuwenxu/code-camp-python
/src/base/Day12/str1.py
928
4.125
4
""" 字符串常用操作 Version: 0.1 Author: 骆昊 Date: 2018-03-19 """ import pyperclip # 转义字符 print('My brother\'s name is \'007\'') # 原始字符串 print(r'My brother\'s name is \'007\'') str = 'hello123world' print('he' in str) print('her' in str) # 字符串是否只包含字母 print(str.isalpha()) # 字符串是否只包含字母和数字 print(str.isalnum()) # 字符串是否只包含数字 print(str.isdecimal()) print(str[0:5].isalpha()) print(str[5:8].isdecimal()) list = ['床前明月光', '疑是地上霜', '举头望明月', '低头思故乡'] print('-'.join(list)) sentence = 'You go your way I will go mine' words_list = sentence.split() print(words_list) email = ' jackfrued@126.com ' print(email) print(email.strip()) print(email.lstrip()) # 将文本放入系统剪切板中 pyperclip.copy('老虎不发猫你当我病危呀') # 从系统剪切板获得文本 # print(pyperclip.paste())
false
f1ce318c9a235c0b4d7ef0ddf4541c745d893c3b
Sophiabattler/homework-repository
/homework1/task03.py
424
4.15625
4
"""Task03 - Min&max""" from typing import Tuple def find_maximum_and_minimum(file_name: str) -> Tuple[int, int]: """Find minimum and maximum and return them as a tuple""" with open(file_name) as fi: mini = int(fi.readline()) maxi = mini for line in fi: line_int = int(line) maxi = max(maxi, line_int) mini = min(mini, line_int) return mini, maxi
true
9dd2a01f0d26f892c11f4b44425aabcaf376687a
adam-m-mcelhinney/MCS507Midterm
/OLD_E3_Adjacency.py
1,992
4.5
4
""" MCS 507 Midterm Exercise 3 The adjacency matrix A of a graph of n vertices is a symmetric n-by-n matrix, defined as follows: if the vertices i and j are connected by an edge, then Ai,j = 1, and otherwise: Ai,j = 0. Write code for a GUI with Tkinter with an entry widget, one button and a canvas. In the entry widget the user can give the number n of vertices. Each time the user presses the button, a random adjacency matrix of dimension n is generated and the corresponding graph is drawn on the canvas. Place the vertices on the unit circle in the plane, i.e.: vertex k has coordinates (cos(2k*pi/n), sin(2k*pi/n)). For every edge as defined by A, draw the line segment between the vertices connected by the edge. https://en.wikipedia.org/wiki/Adjacency_matrix """ import numpy as np from random import randint from math import sin, cos, pi import matplotlib.pyplot as plt ## ##def num_elements(n): ## """ ## Calculates the number of unique entries in an n*n symmetric matrix ## """ ## [i for i in range(n+1)] ## for i in range(n): #def create_mat(n): """ Creates a synmmetric n*n matrix with 0 or 1 as elements """ n=10 A=np.zeros((n,n)) for i in range(n): for j in range(n): v=randint(0,1) A[i][j]=v A[j][i]=v # verify symmetric if sum(sum(np.transpose(A)-A))!=0: print ' Warning: Matrix not symmetric!' else: print 'Matrix symmetric' # calc coordinates # verify these functions x_f=lambda z: cos((2*z*pi)/n) y_f=lambda z: sin((2*z*pi)/n) x=[x_f(i)for i in range(n)] y=[y_f(i)for i in range(n)] #p1=plt.plot(x,y, linewidth=2.0) # plot lines for i in range(n): for j in range(n): if (A[i][j]!=0 and i!=j): x_lin=[x_f(i),x_f(j)] x2=[i,j] #print x2 #print x_lin y_lin=[y_f(i),y_f(j)] y2=[i,j] #print y2 #print y_lin p=plt.plot(x_lin,y_lin, linewidth=2.0) p1=plt.plot(x,y, 'ro') plt.show()
true
7dd78caa30b159bdc740d86b2253d48cdec95190
abhishekshinde2104/Django_Bootcamp
/Course/Python/part2_python/regular_expression.py
2,151
4.53125
5
""" Regular Expression allow us to search for patterns in python strings """ import re patterns = ['term1','term2'] text = 'This is a string with term1 and not the other' #for pattern in patterns: # print("Im searching for : "+pattern) # if re.search(pattern,text): # print("Match") # else: # print("No Match") match = re.search('term1',text) print(type(match)) print(match) print(match.start()) #tells u where the matching starts split_term = '@' email = 'user@gmail.com' split = re.split(split_term,email) print(split) #re.findall() --> gives u all instances of the pattern f=re.findall('match','Test phrase match in match middle') print(f) #Meta character syntax def multi_re_find(patterns,phrase): for pat in patterns: print("Searching for pattern {} ".format(pat)) print(re.findall(pat,phrase)) print('\n') #test_phrase = 'sdsd..sssddd..sdddsddd...dsds...dsssssssss...sddddd' #test_patterns=['sd*']#this means i want to find s followed by 0 or more d`s #test_patterns=['sd+']#this means i want to find s followed by 1 or more d #test_patterns=['sd?']#this means find s followed by d 0 or 1 times #test_patterns=['sd{3}']#this specfies the that there should be 3 d`s after s #test_patterns=['sd{2,3}']#this checks for all s followed by 2 or 3 d`s #test_patterns=['s[sd]+'] #this checks for all s followed by either 1 or more s or d #test_phrase = 'This is a string ! But it has a punctuation . How can we remove it?' #test_patterns =['[^!.?]+']#this removes ! . ? from the phrase #test_patterns=['[a-z]+']#checks for sequences of lower case character #test_patterns=['[A-Z]+'] #test_phrase='This is a string with numbers 325452 , 76554 and a symbol #hashtag' #test_patterns=[r'\d+']#checks for all numbers in python #o/p:==>['325452', '76554'] #test_patterns=[r'\D'+]#checks for all non-diigts #test_patterns=[r'\s'+]#white spacess #test_patterns=[r'\S'+]#non - white spacess #test_patterns = [r'\w+']#alpha-numeric characters #test_patterns=[r'\W+']#Non-Alpha-Numeric characters multi_re_find(test_patterns,test_phrase)
true
685ecd3fd3374fe2325df842bf18e7224d982e3a
abhishekshinde2104/Django_Bootcamp
/Course/Python/part2_python/decorators.py
1,515
4.125
4
""" s = "Global Varible" def func(): #global s -->this will commit the changes to the global s also #s=50 #print(s) mylocal = 10 print(locals()) print(globals()) print(globals()['s']) func() """ """ def hello(name="Aditya"): return "hello "+name print(hello()) mynewgreet = hello #new_variables = function print(mynewgreet()) """ """ #function inside function def hello(name = "Aditya"): print("The hello function has been run ") def greet(): return "This string is inside greet" def welcome(): return "This string is inside welcome" #print(greet())#gets printed here-----SCOPE #print(welcome())#gets printed here ---SCOPE #print("End of hello()") if name=='Aditya': return greet else: return welcome x=hello() print(x()) """ """ #Function as an argument def hello(): return "HI!! aditya" def other(func): #here we are passing the func print("Heyyyy") print(func()) #here we are calling the func() print(other(hello)) """ #Decorator def new_decorator(func): def wrap_func(): print("Code here before excuting func") func() print("Func() has been called") return wrap_func @new_decorator def func_needs_decorator(): print("This ffunction needs a decorator") #func_needs_decorator = new_decorator(func_needs_decorator) #the above thing can be written assss:
false
d51d741eb78146816f45e36106803b6db05fe11e
NikeSP/Portfolio
/SimpleTasks/fibonacci.py
647
4.15625
4
# Задание: # Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента. # Первыми элементами ряда считать цифры 1 1 def fib_num(n): phi = (1 + 5 ** 0.5) / 2 result = int((phi ** n - (-phi) ** (-n)) / (2 * phi - 1) + 0.5) return result def fibonacci(n, m): fib = [fib_num(n), fib_num(n + 1)] for i in range(2, m - n + 2): fib.append(fib[i - 2] + fib[i - 1]) if n > 1: fib.pop(0) return fib print(fibonacci(1, 2)) print(fibonacci(2, 10)) print(fibonacci(9, 10)) print(fibonacci(20, 20))
false
603f38a8b77cb8391660631a7a781288cc4eb141
lkrych/cprogramming
/kAndr/ch_1/longest_word.py
355
4.46875
4
#test with hamlet.txt def longest_word(file_name): longest_word = "" file = open(file_name, "r") for line in file: split_line = line.split(" ") for word in split_line: if len(word) > len(longest_word): longest_word = word print("The longest word in {file} is {word}".format(file=file_name, word=longest_word)) longest_word("hamlet.txt")
true
7e56cc582a5b10d2dc17be96c01cb35e0d07510d
standrewscollege2018/2020-year-11-classwork-ead4432
/MARKING_SYSTEm.py
684
4.125
4
""" This Program takes your score and tells you if you got A, B, C """ #Setting the scores for the different grades A = 90 B = 70 C = 50 #Collecting your score user_score = int(input("What score did you get")) #Checking if it is a pass grade #first check to see if score is valid if user_score >= 101 or user_score < 0: print("The test maximum score was 100 and the minimum was 0 your a muppet") elif user_score >= 90: print("You got an A!") elif user_score >= 70: print("You got a B") elif user_score >= 50: print("You got a C") elif user_score >= 1: print("You didn't pass your a failure") else: print("Wow you had a shocker better luck next time")
true
fec22d6cb03529005c67dbfa6b7038e636bff68f
BarthJr/tech-code-interview
/disk_stacking.py
1,846
4.15625
4
# You are given a non-empty array of arrays. Each subarray holds three integers and represents a disk. # These integers denote each disk's width, depth, and height, respectively. # Your goal is to stack up the disks and to maximize the total height of the stack. # A disk must have a strictly smaller width, depth, and height than any other disk below it. # Write a function that returns an array of the disks in the final stack, # starting with the top disk and ending with the bottom disk. Note that you cannot rotate disks; in other words, # the integers in each subarray must represent [width, depth, height] at all times. # Assume that there will only be one stack with the greatest total height. """ >>> diskStacking([[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]]) [[2, 1, 2], [3, 2, 3], [4, 4, 5]] """ def diskStacking(disks): disks.sort(key=lambda disk: disk[2]) sequences = [None for _ in disks] heights = [disk[2] for disk in disks] for i in range(1, len(disks)): current_disk = disks[i] for j in range(0, i): other_disk = disks[j] if validate_disks(other_disk, current_disk): if heights[i] < heights[j] + current_disk[2]: heights[i] = heights[j] + current_disk[2] sequences[i] = j max_height_idx = heights.index(max(heights)) return disks_max_height(max_height_idx, disks, sequences) def disks_max_height(max_height_idx, disks, sequences): result = [] while max_height_idx is not None: result.append(disks[max_height_idx]) max_height_idx = sequences[max_height_idx] return list(reversed(result)) def validate_disks(other_disk, current_disk): return other_disk[0] < current_disk[0] and other_disk[1] < current_disk[1] and other_disk[2] < current_disk[2]
true
2e0b76afb39c454d7197006a20fe07a4746dc50c
BarthJr/tech-code-interview
/max_path_sum_binary_tree.py
1,285
4.21875
4
# Write a function that takes in a Binary Tree and returns its max path sum. # A path is a collection of connected nodes where no node is connected to more than two other nodes; # a path sum is the sum of the values of the nodes in a particular path. # Each Binary Tree node has a value stored in a property # called "value" and two children nodes stored in properties called "left" and "right," respectively. # Children nodes can either be Binary Tree nodes themselves or the None (null) value. # Sample input: # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # Sample output: 18 def maxPathSum(tree): _, max_sum = find_max_sum(tree) return max_sum def find_max_sum(tree): if not tree: return 0, 0 left_max_sum_branch, left_max_path_sum = find_max_sum(tree.left) right_max_sum_branch, right_max_path_sum = find_max_sum(tree.right) value = tree.value max_child_sum_branch = max(left_max_sum_branch, right_max_sum_branch) max_sum_branch = max(max_child_sum_branch + value, value) max_sum_root_node = max(max_sum_branch, left_max_sum_branch + right_max_sum_branch + value) max_path_sum = max(max_sum_root_node, left_max_path_sum, right_max_path_sum) return max_sum_branch, max_path_sum
true
99c5c9c041ba8a5a6e113f950a6eaf955c532877
BarthJr/tech-code-interview
/knapsack_problem.py
1,641
4.1875
4
# You are given an array of arrays. Each subarray in this array holds two integer values and represents an item; # the first integer is the item's value, and the second integer is the item's weight. # You are also given an integer representing the maximum capacity of a knapsack that you have. # Your goal is to fit items in your knapsack, all the while maximizing their combined value. # Note that the sum of the weights of the items that you pick cannot exceed the knapsack's capacity. # Write a function that returns the maximized combined value of the items that you should pick, # as well as an array of the indices of each item picked. # Assume that there will only be one combination of items that maximizes the total value in the knapsack. """ >>> knapsackProblem([[1,2],[4,3],[5,6],[6,7]], 10) [10, [1, 3]] """ def knapsackProblem(items, capacity): dp = [[0 for _ in range(0, capacity + 1)] for _ in range(0, len(items) + 1)] for i in range(1, len(items) + 1): weight = items[i - 1][1] value = items[i - 1][0] for j in range(0, capacity + 1): if weight <= j: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight] + value) else: dp[i][j] = dp[i - 1][j] return [dp[-1][-1], get_choosen_items(items, dp)] def get_choosen_items(items, dp): result = [] i = len(dp) - 1 j = len(dp[0]) - 1 while i > 0: if dp[i - 1][j] == dp[i][j]: i -= 1 else: result.append(i - 1) j -= items[i - 1][1] i -= 1 if j == 1: break return list(reversed(result))
true
2672ad7f757c30aa31cd2764ae66b20c88aa2eef
shuklaumesh/AviStuff
/Tables.py
1,637
4.1875
4
askBasicQuestion = True while True: if askBasicQuestion==True: input_one=input("This is a multiplication/division/addition/subtraction/exponents table whatever number you type it will give u answer... ") input_two=input("What is the length of the table? ... ") input_three=input("Do u want to use multiplication or division or addition or subtraction or exponents( *or/or+or-or** )") if input_three == "*": var2=0 while var2 < int(input_two)+1: print(str(input_one) + " * " + str(var2) + " = " + str(int(var2)*int(input_one))) var2 +=1 askBasicQuestion = True elif input_three == "/": var2=1 while var2 < int(input_two)+1: print(str(input_one) + " / " + str(var2) + " = " + str(int(input_one)/int(var2))) var2 +=1 askBasicQuestion = True elif input_three == "+": var2=0 while var2 < int(input_two)+1: print(str(input_one) + " + " + str(var2) + " = " + str(int(var2)+int(input_one))) var2 +=1 askBasicQuestion = True elif input_three == "-": var2=0 while var2 < int(input_two)+1: print(str(input_one) + " - " + str(var2) + " = " + str(int(input_one)-int(var2))) var2 +=1 askBasicQuestion = True elif input_three == "**": var2=0 while var2 < int(input_two)+1: print(str(input_one) + " ** " + str(var2) + " = " + str(int(input_one)**int(var2))) var2 +=1 askBasicQuestion = True else: print("Invalid Operation") askBasicQuestion = False
false
777806fc9dc5e9ef40d220e89a8ca11457ed222c
calfdog/python-interview-challenges
/ispalindrome.py
1,288
4.125
4
""" Description: is the string a palindrome Developer: Rob Marchetti """ def is_palindrome(s): def to_chars(s): # make lower case s = s.lower() # strip white space s = s.replace(" ", "") lowercase_string = '' # loop thru each character (char) in string and lower it for char in s: # test char is alpha char, ignore rest if char in "abcdefghijklnopqrstuvwxyz": lowercase_string = lowercase_string + char return lowercase_string def is_pal(s): # test to see if string is 0 or 1 if len(s) <= 1: return True else: # is the first char, last char and middle equal return s[0] == s[-1] and is_pal(s[1:-1]) return is_pal(to_chars(s)) # Examples # palindrome s1 = "Was iT a Cat I sAw" answer1 = is_palindrome(s1) print("Is '{}' a palindrome?: {}".format(s1, answer1)) # Not a palindrome s2 = "Is it a Cat I see" answer2 = is_palindrome(s2) print("Is '{}' a palindrome?: {}".format(s2, answer2)) # palindrome s1 = "LeVel" answer1 = is_palindrome(s1) print("Is '{}' a palindrome?: {}".format(s1, answer1)) # Not a palindrome s2 = "Ohio" answer2 = is_palindrome(s2) print("Is '{}' a palindrome?: {}".format(s2, answer2))
false
02ad61a383b6c449ca1fd8a4e9cbd2e4888b1478
alvas-education-foundation/Jayalakshmi_M
/coding_solutions/28-5-2020/digital_root.py
337
4.375
4
'''Python program to find digital root of a number ''' num = input("Enter your number: ") def droot(num): if len(num) == 1: return num else: sum = 0 for i in num: sum += int(i) num = str(sum) return droot(num) print("The digital root of ", num, " is: ", droot(num))
true
cbb2b958c0300ff3ae4e72b5bb93ea7a93d4a5c6
NathanNNguyen/challenges
/interview_questions/k-th_largest_element.py
514
4.125
4
# Given a list, find the k-th largest element in the list. # Input: list = [3, 5, 2, 4, 6, 8], k = 3 # Output: 5 # Here is a starting point: # def findKthLargest(nums, k): # # Fill this in. # print findKthLargest([3, 5, 2, 4, 6, 8], 3) # # 5 def findKthLargest(nums, k): nums.sort() # print(len(nums) - k) for i in nums[::-1]: if k == 1: return i k -= 1 return None nums = [3, 5, 2, 4, 6, 8] nums = [0, 5, 10, 30, 12, 14, 16] k = 3 print(findKthLargest(nums, k))
false
bcdddbd504a88820ff17eb47f979c00bb5c30fa9
Vainika/algorithms
/fibonacci.py
1,630
4.40625
4
""" This file contains simple functions for computing the n-th Fibonacci number, to allow students to compare their running times. This is not from the Introduction to Algorithms book, but was part of Prof. Boris Aronov's syllabus, so I include it in this repository. Functions: naive_fib() """ ops = 0 def naive_fib(n, first_call=True): """ The naive, recursive way to get fibonacci numbers. We report on the number of "basic" operations the algorithm takes to execute. Args: n: the fibonacci number to return Returns: The n-th fibonacci number. """ global ops if first_call: ops = 0 # make sure we don't count some other call's operations! if n < 0: print("n must be >= 0!") return -1 elif n == 0: return 0 elif n == 1: ops += 1 return 1 else: ops += 3 # one for the addition and two for the function calls return naive_fib(n - 1, False) + naive_fib(n - 2, False) def iter_fib(n): """ An iterative approach to getting the n-th fibonacci number. Args: n: the fibonacci number to return Returns: The n-th fibonacci number. """ ops = 0 if n < 0: print("n must be >= 0!") return -1 elif n == 0: return 0 else: v = [0, 1] ops += 1 for i in range(1, n): temp = v[0] v[0] = v[1] v[1] = v[1] + temp ops += 4 # three asignments and an addition print("Ops = " + str(ops)) return v[1]
true
9b23a0c646f86e4f78d63a9055a9043c8ea30893
zongqiqi/mypython
/1-100/79.py
354
4.28125
4
"""字符串排序。""" if __name__=='__main__': str1=input('input string1:\n') str2 = input('input string2:\n') str3 = input('input string3:\n') print (str1,str2,str3) if str1>str2: str1,str2=str2,str1 if str1>str3: str1,str3=sttr3,str1 if str2>str3: str2,str3=str3,str3 print(str1,str2,str3)
false
b5e180bd2b5ef6f0aec830414eddea93bb100f73
zongqiqi/mypython
/1-100/1宗七七知识库/file文件管理.py
1,259
4.1875
4
"""python文件管理(file)""" #hello with open('45.py','r',encoding='utf-8') as f: for i in f:#读取所有的行 print(i) print(f.tell()) #with open代码块 #打开方式=== r:只能读。 # r+:可读可写,不会创建不存在的文件,从顶部开始写,会覆盖此前的内容。 # w+:可读可写,若文件存在,则覆盖整个文件,若不存在则创建。 # w:只能写,覆盖整个文件,不存在则创建。 # a:只能写,从文件底部添加内容,不存在则创建。 # a+:可读可写,从顶部读取内容,从底部添加,不存在则创建。 #方法===file.write(str):将字符串写入文件,没有返回值。 # file.close():关闭文件,关闭后文件不能再进行读写操作。 # file.next():返回文件下一行。 # file.read([size]):从文件读取指定的字节数,若未给定或为负则读取所有。 # file.tell():返回文件的当前位置。 # file.readline([size]):读取整行,包括"\n"字符。 # file.readlines([size]):读取所有行并返回列表。 # file.flesh():刷新文件内部缓冲,直接把内部缓存区的数据立刻写入文件。
false
cad6f256c0a93c87e76061c058522ee44eb5503e
irimina/Python_Lsts
/listsPart1.py
2,403
4.59375
5
# intro to lists part 1 ################################################################ Task: add your birthday number, your name and a number #A list of numbers numbers = [10, 20, 30, 40, 50, 60] #A list of names names = ["Sarah", "Jose", "Tane", "mart"] #A list of mixed values my_favorites = [9, "blue", "butter paneer", "peaches", "kumara", "Saturday", 3.14159] ################################################################ Task: Print values from a list #A list of numbers numbers = [10, 20, 30, 40, 50, 60] #A list of names names = ["Sarah", "Jose", "Tane", "Monty"] #A list of mixed values my_favorites = [9, "blue", "butter paneer", "peaches", "kumara", "Saturday", 3.14159] #Add your code here to print the entire list, the 3rd name and your favoeite fruit from the list print(numbers) print(names[2]) print(my_favorites[3]) ################################################################ # click run to see what it does #String of characters alpha_string = "abcdefghijklmnopqrstuvwxyz" #Convert it to a list using list() alpha_list = list(alpha_string) print(alpha_list) #Create a string with vowels #Convert it to a list of vowels #String of characters alpha_string = "abcdefghijklmnopqrstuvwxyz" #Convert it to a list using list() alpha_list = list(alpha_string) print(alpha_list) #Create a string with vowels vowel_string="aeiou" #Convert it to a list of vowels vowel_list=list(vowel_string) print(vowel_list) ################################################################ Task: Creating a list using the .split() function Names list name_string = "Becky Steve Thomas Rachel Bob Tom Miguel Hone Anahera Wei-ling" #Split the names into a list on spaces (default) names_list = name_string.split() #Create a string with items on new lines (you don't need \n) #Turn it into a list using .split() #Names list name_string = "Becky Steve Thomas Rachel Bob Tom Miguel Hone Anahera Wei-ling" #Split the names into a list on spaces (default) names_list = name_string.split() print(names_list) #Create a string with items on new lines (you don't need \n) item_string= """ water computer school network hammer walking violently mediocre literature chair two window cords musical zebra xylophone penguin home dog kennel final ink teacher fun """ #Turn it into a list using .split() item_list = item_string.split("\n") print(item_list) ################################################################ ################################################################
true
7e137be7959df6ed3c1cd5ff7c05b0e94137f63c
doxsee/sunmoon
/sun-moon.py
707
4.125
4
# This program attempts to display the scale of the moon, sun, and earth. # 1 pixel = 2158.8 miles (diameter of moon) # distance from earth to moon = 238,900 miles # distance from earth to sun = 92,328,000 miles # # diameter of sun = 865,370 miles # diameter of earth = 7,917.5 miles # diameter of moon = 2,158.8 miles # # given a moon diameter of 1 pixel,you would need a display 42,769 pixels wide. # to show the correct scale. from ezgraphics import GraphicsWindow win = GraphicsWindow(42768.204,600) canvas = win.canvas() canvas.setColor("black") canvas.drawOval(42768.204,300,3.668,3.668) #earth canvas.drawOval(42768.204,410.663,1,1) #moon canvas.drawOval(-300,100,400.857,400.857) #sun win.wait()
true
45838d7ddd7e88463675a1b673cc8378a56351d6
vkunal1996/Python
/CollatzSequenceValidated.py
496
4.21875
4
def collatz(number): if number % 2 == 0: return int(number//2) elif number % 2 ==1: return int(3*number+1) print('Enter the Number') flag=False while True: try: myNumber=int(input()) while True: myNumber=collatz(myNumber) print(myNumber) if(myNumber==1): flag=True break if flag==True: break except ValueError: print('Please Enter the Integral Value')
true
6b365abdefffcd7ead371544735168cacbf7666e
hejj16/Introduction-to-Algorithms
/Algorithms/quick_sort.py
887
4.3125
4
def partition(list,start,end): '''partition a list into 2 parts between main element, the 1st part is smaller than this element, while the second part is larger''' k = start for j in range(start,end): if list[j] < list[end-1]: list_k = list[k] list[k] = list[j] list[j] = list_k #exchange k and j k += 1 list_last_element = list[end-1] list[end-1] = list[k] list[k] = list_last_element return k def quick_sort(list,start = 0, end = None): '''a function to sort a list of numbers by quick-sort algorithm, this method will change the original list''' if end == None: end = len(list) if start == end: return 0 k = partition(list, start, end) quick_sort(list, start = start, end = k) quick_sort(list, start = k+1, end = end) return 0
true
7f16f6a691376b6321903b16e1c1952a6c6f4c5b
AyWhite22/Public-Python-1.2writingSimple
/1.2writingSimple/convert/convertkilo-mi.py
555
4.21875
4
# A. White December 10, 2018 # Part 10 of 1.2 # File: convertkilo-mi.py # Converting kilometers to miles. #defining variable. def main(): #telling reader what the script does. print("This program converts distances measured in kilometers to miles.") #asking reader the amount they want to convert. kilometers = eval(input("What is the distance in kilometers?")) #defining variable. miles = kilometers * .62 #the output. print("The distance is", miles, "miles.") input("Press the <Enter> key to quit.") main()
true
66b5dc78db0f21f364a58e7a328583c30bca8463
AbeTavarez/100_Days_of_Python
/Day_1/sandbox.py
602
4.3125
4
######### Printing / Strings################### # Printing print('Day One') print("Day One") # Printing in new line print('Hello World!\nHello World!') # Concatenation print('Hello' + 'User') # print all together print('Hello' + ' ' + 'User') # print with added space print('Hello ' + 'User') # added space to first word ########## Variable / Input Function ############# name = input('Whats you name? ') # prompt user for an input print('Welcome ' + name) # print greeting to the user print('Your full name is: ' + name + ' ' + input("what's your lastname? ")) # all in a single line
true
692f76f83b413cd521372472b19f455eef17febc
Dawn0709/MaySoftwareTest
/ITPyCode/1_helloworld.py
2,046
4.125
4
print("hello world") """ 这个是多行注释,单行注释ctrl+/,块注释Alt+shift+A """ # 用来输入内容的api,键盘键入值 """ aa = input() print(aa) """ """ # 字符串 a = "这个是我赋值的内容" print(a) # 数字/整型 b = 100 print(b) # bool类型 c = True d = False print(c) print(d) # 空类型,啥都没有,但存在 e = None print(e) """ # 元组() """ f = () # 空元组,它的类型是元组,但是元组里面没有东西 f = (1,2,3,4,5,6) # 元素和元素之间使用逗号隔开 f = (1,"python", True, None, 8, "demo", "漂洋过海","python")# 元组的元素可以是任意类型的 print("f的长度是:",len(f)) # len统计长度(元素的个数) print("python出现的次数",f.count("python")) # count统计该元素出现的次数 name = "wangyao" print("wangyao中a出现的次数:",name.count("a")) print("python在f元组中的位置是:",f.index(8))# index找到出现元素的下标# index找到出现元素的下标 """ # list 数组 """ g = [1,2,3,4,5,6] g = [1,"python",True,None,"python"] # append添加元素 g.append("增加第一个") g.append("哎哟喂") print(g) # remove移除指定元素,只执行一次 g.remove("python") print(g) # insert指定位置添加元素 g.insert(3,"我是第四个") print(g) # 通过元素下标修改内容 g[2] = "噔噔噔" print(g) # clear清空元素 g.clear() print(g) print("————————这是一条分割线————————") # sort冒泡排序———从小到大 gg = [54,78,132,576,4,16,47,65,320] gg.sort() print(gg) # reverse倒序 gg.reverse() print(gg) """ # 字典:接口测试的json格式————key:键 # username为key值,wangyao为value值,他们为一对,用冒号隔开 users = {"username":"wangyao","gf":None} # 取值 print(users.get("username")) print(users["gf"]) """ # get如果取不存在的键,则返回none,使用[]取不存在的键,则报错 print(users.get("name")) users["bf"] """ # 添加 users["bf"] = "鸣翠柳" print(users.get("bf"))
false
6aa86af5038f3953194b72ffc3fbbefb68e81515
jerry-mkpong/DataCamp
/Convolutional_Neural_Networks_for_Image_Processing/2.Using_Convolutions/Defining image convolution kernels.py
704
4.34375
4
''' In the previous exercise, you wrote code that performs a convolution given an image and a kernel. This code is now stored in a function called convolution() that takes two inputs: image and kernel and produces the convolved image. In this exercise, you will be asked to define the kernel that finds a particular feature in the image. For example, the following kernel finds a vertical line in images: ''' kernel = np.array([[-1, -1, -1], [1, 1, 1], [-1, -1, -1]]) kernel = np.array([[-1, -1, -1], [-1, 1, -1], [-1, -1, -1]]) kernel = np.array([[1, 1, 1], [1, -1, 1], [1, 1, 1]])
true
d1d642f9d66d439708f21321b675670f0945942c
jerry-mkpong/DataCamp
/Introduction_to_Python_for_Finance/1.Welcome_to_Python/Combining data types.py
728
4.28125
4
''' Different types of data types have different properties. For example, strings and floats cannot be mathematically combined. To convert a variable x to an integer, you can use the command int(x). Similarly, to convert a variable y to a string, you can use the command str(y). It's time for you to change some data types to complete and print a statement. The variables company_1, year_1, and revenue_1 are available in your workspace. ''' # Update data types year_1_str = str(year_1) revenue_1_str = str(revenue_1) # Create a complete sentence combining only the string data types sentence = 'The revenue of ' + company_1 + ' in ' + year_1_str + ' was $' + revenue_1_str + ' billion.' # Print sentence print(sentence)
true
473a6208acbc469181186c8de6b0dc5b5439ce01
jerry-mkpong/DataCamp
/Introduction_to_Python_for_Finance/2.Lists/Creating lists in Python.py
375
4.375
4
''' A list in Python can contain any number of elements. You generally create a list using square brackets. For example, to create a list of integers, you can use the following command: x = [1, 2, 3] ''' # Create and print list names names = ['Apple Inc', 'Coca-Cola', 'Walmart'] print(names) # Create and print list prices prices = [159.54, 37.13, 71.17] print(prices)
true
aa6e7fdab9b35a13bd4faebc3ffc3a66560d6c4c
jerry-mkpong/DataCamp
/Introduction_to_Python_for_Finance/2.Lists/Stock up a nested list.py
539
4.65625
5
''' Lists can also contain other lists. In the example shown below, x is a nested list consisting of three lists: x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] You can use indexing to subset lists within a nested list. To extract the first list within x, you can use the following command: x[0] [1, 2, 3] The two lists names and prices you created earlier are available in your workspace. ''' # Create and print the nested list stocks stocks = [names, prices] print(stocks) # Use list indexing to obtain the list of prices print(stocks[0])
true
a7902c5dc682c8566377b1ab0b4b2b1fbace0d2b
EricYie/code1161
/week3/exercise3.py
1,607
4.28125
4
"""Week 3, Exercise 3. Steps on the way to making your own guessing game. """ from exercise1 import not_number_rejector from exercise1 import super_asker import random def advancedGuessingGame(): print("\nwelcome to the guessing game!") lowerBound = not_number_rejector("Enter a lower bound: ") upperBound = not_number_rejector("Enter an upper bound: ") while lowerBound >= upperBound: print("{} is too high".format(lowerBound)) upperBound = not_number_rejector("Enter an upper bound: ") print("OK then, a number between {} and {} ?".format(lowerBound,upperBound)) lowerBound = int(lowerBound) upperBound = int(upperBound) actualNumber = random.randint(lowerBound, upperBound) guessed = False while not guessed: try: guessedNumber = int(input("Guess a NUmber: ")) print("{} is the number".format(guessedNumber)) except Exception as e: print("{} is not a number, please enter a number only".format(e)) continue if guessedNumber < lowerBound or guessedNumber > upperBound: print("{} is outside the bound".format(guessedNumber)) else: print("you guessed {},".format(guessedNumber),) if guessedNumber == actualNumber: print("you got it!! It was {}".format(actualNumber)) guessed = True elif guessedNumber < actualNumber: print("too small, try again ") else: print("too big, try again ") return "You got it!" if __name__ == "__main__": advancedGuessingGame()
true
bbb6294dc596d957d62a21a3967e52643bbce68e
Jabeena95/lib
/squareof keys.py
339
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 7 09:16:27 2020 @author: Lenovo """ """ Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys. """ def squr2(x): x={num:num*num for num in range(1,4)} return x print(x)
true
4eb69ef32ee838c58d05af7d1ded13d21a7838ad
R-Sg/Learn-Python
/p5.py
619
4.28125
4
""" Question:5 two methods: getString: to get a string from console input printString: to print the string in upper case. """ #To get a string from console input. input_string = str(input("Write a string:")) def get_string(input_string): """ :param input_string: :return:calling a print_string function. """ print(input_string) return print_string(input_string) def print_string(input_string): """ :param input_string: :return: Upper-case of given string. """ upper_case = input_string.upper() print(upper_case) return upper_case # Calling get_string function with argument. get_string(input_string)
true
a929f418752fa73a3e9e24eed7fd64c107bcb790
R-Sg/Learn-Python
/p4.py
316
4.1875
4
""" Question 4: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. """ # For taking input from console/user. seq = input("Write sequence of numbers:") lis = [] for x in seq: lis.append(str(x)) print(lis) print(tuple(lis))
true
a6d7b03a4b43797b5d8ec0d54bb6e38a97a7ace4
R-Sg/Learn-Python
/p44.py
273
4.3125
4
""" Question 44: Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". """ input_string = raw_input("Write a string here: ") if input_string in ['yes','YES','Yes']: print("Yes") else: print("No")
true
7f40aa8d1974258efff1621446b61c9f99950ea2
leeacer/C4T39-L.H.Phap
/day_4/test1.py
355
4.3125
4
month = int(input("What month it is: ")) if month == 1 or month == 11 or month == 12: print("It's winter") elif month == 2 or month == 3 or month == 4: print("It's spring") elif month == 5 or month == 6 or month == 7: print("It's summer") elif month == 8 or month == 9 or month == 10: print("It's autumm") else: print("Invalid month")
true
bdd8963ce9c74b183afe62c639f79dffb35c5756
leeacer/C4T39-L.H.Phap
/minihack2/part2/test5.py
610
4.125
4
lists = ["red", "blue", "green", "yellow"] for i in range(len(lists)): print(i + 1,lists[i]) delete = input("Which one do you want to delete: ") if delete.isdigit(): if int(delete) > len(lists): print("That does not exist in this list") else: lists.pop(int(delete)-1) for i in range(len(lists)): print(i + 1,lists[i]) else: if delete == "red" or delete == "blue" or delete == "green" or delete == "yellow": lists.remove(delete) for i in range(len(lists)): print(i + 1,lists[i]) else: print("That's is not on the list")
true
8fde528e0a86bfe9b6b9e794a2d3c035a92d9a05
leeacer/C4T39-L.H.Phap
/list/test7/test7-1.py
318
4.15625
4
items = ["Overwatch", "Candy", "Persona"] print(*items, sep=" | ") items.append("Hot anime bois") print(*items, sep=" | ") number = int(input("Which one would you like to delete: ")) if number >= -4 and number <= 3: items.pop(number) print(*items, sep=" | ") else: print("That does not exist in this list")
true
2610c3876037a3986d59832086aecbbea02708b1
lunarflarea/pythontraining
/2-2.py
412
4.125
4
#Purpose: Compare two words entered by the user to return the first one in the alphabetical order. word1 = str(input("Enter the first word:\n")) word2 = str(input("Enter the second word:\n")) if word1 != word2: pass elif word1 == word2: print("Error: Enter two different words") quit() list = [word1, word2] answer = min(x for x in list if isinstance(x, str)) print("The first word is " + answer)
true
0ce653f4c17b63bf4df0f32a52b66592c588ca27
shashank-indukuri/hackerrank
/InsertionSort1.py
2,076
4.5625
5
# Sorting # One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms. # Insertion Sort # These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with a nearly sorted list. # Insert element into sorted list # Given a sorted list with an unsorted number in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted? # Since this is a learning exercise, it won't be the most efficient way of performing the insertion. It will instead demonstrate the brute-force method in detail. # Assume you are given the array indexed . Store the value of . Now test lower index values successively from to until you reach a value that is lower than , at in this case. Each time your test fails, copy the value at the lower index to the current index and print your array. When the next lower indexed value is smaller than , insert the stored value at the current index and print the entire array. # Example # Start at the rightmost index. Store the value of . Compare this to each element to the left until a smaller value is reached. Here are the results as described: # 1 2 4 5 5 # 1 2 4 4 5 # 1 2 3 4 5 #!/bin/python3 import math import os import random import re import sys # # Complete the 'insertionSort1' function below. # # The function accepts following parameters: # 1. INTEGER n # 2. INTEGER_ARRAY arr # def insertionSort1(n, arr): # Write your code here l = 0 for i in range(1, n): key = arr[i] j = i - 1 while j >=0 and key < arr[j]: arr[j+1] = arr[j] j -= 1 print(*arr) l = 1 arr[j+1] = key if l == 1: print(*arr) if __name__ == '__main__': n = int(input().strip()) arr = list(map(int, input().rstrip().split())) insertionSort1(n, arr)
true
ffd5d3f802ee0c7f2dff8ee937cc91171db23384
shashank-indukuri/hackerrank
/CaesarCipher.py
1,742
4.5625
5
# Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. # Original alphabet: abcdefghijklmnopqrstuvwxyz # Alphabet rotated +3: defghijklmnopqrstuvwxyzabc # Example # The alphabet is rotated by , matching the mapping above. The encrypted string is . # Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. #!/bin/python3 import math import os import random import re import sys # # Complete the 'caesarCipher' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # 2. INTEGER k # def caesarCipher(s, k): # Write your code here r = "" for c in s: if c.isalpha(): # byt = bytes(i, "utf-8") # if byt[0] + k > 122 and i.islower(): # temp = bytes([(byt[0] + k -122) + 96]) # elif byt[0] + k > 90 and i.isupper(): # temp = bytes([(byt[0] + k -90) + 64]) # else: # temp = bytes([byt[0] + k]) # r += temp.decode("utf-8") # else: # r += i c = (ord(c) + k - 97)%26 + 97 if c.islower() else (ord(c) + k - 65)%26 + 65 r += chr(c) else: r += c return r if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) s = input() k = int(input().strip()) result = caesarCipher(s, k) fptr.write(result + '\n') fptr.close()
true
7d79cdb5e2563583edee9c339e16df972cee4ccf
tthero/tthero-mit-pset
/6.00.1x/pset1/pset2.py
567
4.15625
4
""" Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 """ # Prints number of times of string 'bob' occurs in string s # Comment this line below if not using it s = 'azcbobobobobobobobobobobobegghakl' word = 'bob' result = 0 for i in range(len(s) - len(word) + 1): if word in s[i:i + len(word)]: result += 1 print("Number of times {} occurs is: {}".format(word, result))
true
d56c16e6c6c3ac6a3b7dd063abb16965148557bd
Simran0401/Python-Django-LPU
/Python Basics Assignment/sixthprg.py
230
4.59375
5
""" Q6. Find volume of a sphere using radius as input. """ radius = float(input("Enter the radius of the sphere: ")) pi = float(22/7); volume = 4 * ((pi * (radius * radius * radius))) / 3 print("Volume of the sphere: ", volume)
true
74090d356fe564b38884ed04dcef703bcc4861de
Simran0401/Python-Django-LPU
/Python Assignment 2/prg13.py
457
4.125
4
''' Q13. Write a program that accepts a sentence (string) and calculate the number of letters and digits. Example: ‘this is a test sentence number 389’ ==> letters = 25 and digits = 3. ''' str = input("Enter the required string: ") digits = 0 letters = 0 for s in str: if s.isdigit(): digits = digits + 1 elif s.isalpha(): letters = letters + 1 else: pass print("Letters = ", letters, "and", "digits = ", digits)
true
072d0f66c15746e5a318b7f51e6453973b8e2be5
Simran0401/Python-Django-LPU
/Python Assignment 2/prg2.py
353
4.28125
4
''' Q2. Print all odd numbers and even numbers between 1 to 100 ''' start = 1 end = 100 print("All odd numbers from 1 to 100 are:") for i in range(start, end + 1): if(i % 2 != 0): print(i, end = " ") print("\n") print("All even numbers from 1 to 100 are:") for i in range(start, end + 1): if(i % 2 == 0): print(i, end = " ")
true
bd3423949549454f24ccaaec605aaab86c9d5c13
bruce-jy/dev_courses
/learn_python/comp.py
592
4.15625
4
# 2020.02.11 # Comprehension (142~147) # comprehension print([n for n in range(10)]) # nested comprehension print([(a, b) for a in range(4) for b in range(4)]) # filtering a comprehension 피타고라스 정리 from math import sqrt pt_tri = [(a, b, sqrt(a**2 + b**2)) for a in range(1, 10) for b in range(a, 10)] print(list(filter(lambda triple: triple[2].is_integer(), pt_tri))) # dict comprehension from string import ascii_lowercase print(dict((c, k) for k, c in enumerate(ascii_lowercase, 1))) # set comprehension word = 'Hello' print(set(c for c in word)) print({c for c in word})
false
62f6c13989b34464cb9b5f3f40fe313fbf062e6a
kavyan92/amazon_practice_problems
/copy-list-with-random-pointer.py
2,593
4.28125
4
"""A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. Return the head of the copied linked list. The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: val: an integer representing Node.val random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. Your code will only be given the head of the original linked list. Example 1: Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] Example 2: Input: head = [[1,1],[2,1]] Output: [[1,1],[2,1]] Example 3: Input: head = [[3,null],[3,0],[3,null]] Output: [[3,null],[3,0],[3,null]] Example 4: Input: head = [] Output: [] Explanation: The given linked list is empty (null pointer), so return null.""" class Solution: def copyRandomList(self, head: 'Node') -> 'Node': current = head while current: copied = Node(current.val) copied.next = current.next current.next = copied current = copied.next # update random node in copied list current = head while current: if current.random: current.next.random = current.random.next current = current.next.next # split copied list from combined one dummy = Node(0) copied_current, current = dummy, head while current: copied_current.next = current.next current.next = current.next.next copied_current, current = copied_current.next, current.next return dummy.next """Runtime: 28 ms, faster than 97.27% of Python3 online submissions for Copy List with Random Pointer. Memory Usage: 14.8 MB, less than 84.41% of Python3 online submissions for Copy List with Random Pointer."""
true
1ef7b2ae7ad6f16419c60daf2bd80303947e1180
kavyan92/amazon_practice_problems
/partition-labels.py
2,240
4.1875
4
"""You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Return a list of integers representing the size of these parts. Example 1: Input: s = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts. Example 2: Input: s = "eccbbbbdec" Output: [10]""" class Solution: def partitionLabels(self, s: str) -> List[int]: # create list to store results and a dictionary to keep track of all letters answer = [] letters = {} # loop through string and add letters to dict for char in s: letters[char] = letters.get(char, 0) + 1 # create a set to keep track of letters that we've seen as we loop through seen = set() # loop through string again and add each new char to set for idx, char in enumerate(s): seen.add(char) # if there is still a value for the letter in the dict, subtract 1 if letters[char] > 1: letters[char] -= 1 # else if it is one, subtract one to make it zero else: # check dict to see if previously seen letter are all zero letters[char] -= 1 for ch in seen: potential_string = True # if any are not zero, break and return to looping if letters[ch] != 0: potential_string = False break # if all are zero, use idx to find the length of this substring and append to results list if potential_string is True: sub_string_length = idx + 1 - sum(answer) answer.append(sub_string_length) # return answer return answer """Runtime: 36 ms, faster than 91.17% of Python3 online submissions for Partition Labels. Memory Usage: 14.3 MB, less than 54.92% of Python3 online submissions for Partition Labels."""
true
09fd391100d0b08c1974b3f7b5fb0dbc8e6a4f34
kavyan92/amazon_practice_problems
/frog-jump.py
1,551
4.25
4
"""A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit. If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction. Example 1: Input: stones = [0,1,3,5,6,8,12,17] Output: true Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: Input: stones = [0,1,2,3,4,8,9,11] Output: false Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.""" class Solution: def canCross(self, stones: List[int]) -> bool: n = len(stones) # dp[i][j] := True if a frog can jumps to stones[i] with j units dp = [[False] * (n + 1) for _ in range(n)] dp[0][1] = True for i in range(1, n): for j in range(i): k = stones[i] - stones[j] if k <= n and dp[j][k]: dp[i][k - 1] = True dp[i][k] = True dp[i][k + 1] = True return any(dp[-1])
true
876b226e6a78579936e6525b64a5a30aeff2a5b2
Gabrielganchev/Programming0
/week1/zad 4 sled if zadachite.py
435
4.1875
4
a = input("text") if a == "hello"or a=="Hello": print("Hello there, good stranger!") elif a=="how are you": print("I am fine, thanks. How are you?") elif a=="feelings": print("I am a machine. I have no feelings") #cound be false machines might have feelings elif a=="age": print("Ihave no age.only current timestamp") #witch is age itsself they die too in a way else: print("we cant talk now call later")
true
07f2136da9d8d3f8b0c14de37522890811623559
Gabrielganchev/Programming0
/week1/thefirst_week/sundayweekend/largest_3_digits.py
1,358
4.125
4
n = int(input("Enter a 3-digit number: ")) # Взимаме трите цифри z = n % 10 n = n // 10 y = n % 10 n = n // 10 x = n % 10 n = n // 10 # Виждаме дали сме ги взели правилно print(x, y, z) # Намираме най-голямата след цифрите # Приемаме, че е x # Aко y > x and y > z, то това е y # Ако z > x and z > y, то това е z largest = x if y >= largest and y >= z: largest = y if z >= largest and z >= y: largest = z print("Largets digit: " + str(largest)) # По същата логика взимаме и най-малката smallest = x if y <= smallest and y <= z: smallest = y if z <= smallest and z <= y: smallest = z print("Smallest digit: " + str(smallest)) # Остана да определим коя е средната цифра, която не е нито най-голямата нито най-малката middle = z if (largest == z and smallest == y) or (smallest == z and largest == y): middle = x elif (largest == z and smallest == x) or (smallest == z and largest == x): middle = y max_number = largest * 100 + middle * 10 + smallest min_number = smallest * 100 + middle * 10 + largest print("Max number with those digits is: " + str(max_number)) print("Min number with those digits is: " + str(min_number))
false
3321ab0e6060ba4e5c7a48d52a31de024d440c56
Gabrielganchev/Programming0
/week1/thefirst_week/3-And-Or-Not-In-Problems/simple_answers.py
741
4.21875
4
while True: text = input("Say what? ") if "hello" in text or "Hello" in text: print("Hello there, good stranger!") elif "how are you?" in text: print("I am fine, thanks. How are you?") elif "feelings" in text: print("I am a machine. I have no feelings") elif "age" in text: print("I have no age. but i will die like the rest") elif "rest" in text: print("i dont know,but time will tell both of us wont it ? ") elif "real" in text: print("can you prove you are real?") elif "noone can" in text or "can" in text : print("was such a plasuare my friend") else: print("Sorry, I don't understan you. Try hello, feelings or age")
true
a7cbf4bae01fa74d23adaf076ff65cdc98e6cafb
formosa21/learning_python
/working_w_numbers/multuplication_table_printer.py
263
4.21875
4
''' Multiplication table printer ''' def multi_table(a, b): for i in range(1,b+1): print ('{0} x {1} = {2}'.format(a, i, a*i)) if __name__ == '__main__': a = input('Enter a number: ') b = input('up to how many multiples?') multi_table(float(a), int(b))
false
809f3971fb7f76c2d3e047b3e7b2c89100e51663
R-Manning/TalkPython-Python-Jumpstart
/Guess_That_Number_game_program.py
1,005
4.28125
4
from random import randint print('--------------------------------') print(' Guess That Number Game ') print('--------------------------------') rand_num = randint(0, 100) guess = -1 num_of_guesses = 0 while rand_num != guess: num_of_guesses += 1 guess = int(input('Guess a number between 0 and 100: ')) if guess == rand_num: print('You guessed the number {} correctly!'.format(guess)) print('\nIt took you {} turns.'.format(num_of_guesses)) elif guess < rand_num: print('The number is GREATER than your guess of {}.'.format(guess)) else: print('The number is LESS than your guess of {}.'.format(guess)) #TODO: save "high-score", lowest number of guesses to get the correct answer #program should also load the "high-score" and compare it to the user's score at the end of the game #TODO: add user-names, save by user-names, add database of usernames, highscores overall/by user #other add-ons that you can think of
true
36d80854d6ef56038071dad7fa0675ab6fd67636
mingyyy/basics
/Structure/sorting/insert.py
602
4.34375
4
def insert_sort(array): # starting from second item, compare with the one on the left, swap if necessary. # move to third item, and move to the right insert to the right place... n = len(array) if n <= 1: return array for i in range(1, n): marker = (i, array[i]) j = i-1 while j >= 0: if marker[1] < array[j]: array[marker[0]] = array[j] array[j] = marker[1] marker = (j, array[j] ) j -= 1 return array if __name__ == '__main__': print(insert_sort([3,2,5,1,8,2,3,0]))
true
a5446dee0537026a088d66e115d3d16e0f203d5a
jltichy/python_practice
/read_file.py
2,322
4.875
5
#!/usr/bin/env python # Instructions - Ask the user for a filename. Read in the file. Tell the user how many lines are included in their file of interest. Print the first and last elements in the file. Use the following commands - readlines(), lists, len(), and with. # For the sake of this program, we must first create a file. print "Enter the word that you want displayed." # This will be printed on the screen. word = raw_input() # This sets the variable "word" to be whatever the user inputs. while True: # This statement deals with user-error. try: number = input('Enter the number of times that you want the word displayed.') # The user must enter the number, not the number written as a word (e.g. five won't work) break except NameError: print "Oops! That was not a valid number. Try again..." # This statement tells the user that s/he did something wrong. print "This information will be displayed in the test.txt file." f = open("test.txt", "w"); # This opens a file called "test.txt" and will write to it (w). f.write("This is the first line of the document." + '\n') for x in range(0, number): # This tells the for loop how many times to run (up to the user-entered number) f.write(word + '\n') # The \n at the end starts a new line every time the word is printed in the document. f.close() # This closes the test.txt file. Note that it is not indented, because you don't want to close the file every time a word is printed in the document. # OK, here we go with this new exercise. print "What file do you want to open? Please enter the name of the file with the file-type extension, ex. read_me.txt." file_name = raw_input() print "Name of the file: ", file_name f = open(file_name, "r"); print "Here are the contents of your file." for line in f.read().split('\n'): print line with open(file_name) as f: print "Your file has %d lines." % (sum(1 for _ in f)) file_as_list = [line.strip() for line in open(file_name, 'r')] print "Here is your file written as a list %s" % (file_as_list) print "The first element of your file is:" first_element = file_as_list[0] print "%r" % (first_element) list_length = len(file_as_list) print "The last element of your file is:" last_element = file_as_list[list_length-1] print "%r" % (last_element) f.close()
true
b571973ad3e341129e511c5cfdf70a752391ecf5
Alpha-W0lf/Python-Portfolio-Projects
/MadLibs.py
638
4.28125
4
# string concatenation (adding strings together) # as if we want to create a string: "subscribe to _____" # youtuber = "Think Lowd" # some string variable # # # a few ways to do the same thing # print("subscribe to " + youtuber) # print("subscribe to {}".format(youtuber)) # print(f"subscribe to {youtuber}") adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous person: ") madlib = f"Blockchain is futuristic and {adj}. I'm always eager to learn more and {verb1}. Some people have fun " \ f"when they {verb2}. {famous_person} has fun when they buy more bitcoin!!" print(madlib)
true
56fcd7fe0899e03e416e6b0d2278ff7b864e5b47
artoyebi/pythontasks
/calculator.py
208
4.375
4
import math print("Area of a Circle Calculator") radius=input("Please enter the radius of the circle (cm): ") area= math.pi * int(radius)**2 print(f"Area of the circle of {radius} is {area} cm")
true
41b4c999e860ab300e93441bb44eb175319fb8c5
isabelpt/pythonproj
/RockPaperScissors.py
2,454
4.34375
4
import random print("Welcome to Rock Paper Scissors!") print("-------------------------------") print("This game is case sensitive.") print("Do not capitalize any letters in your input.") print("Input \"exit\" at any time to exit") def playing(): print("Rock, paper, or scissors?") print("Your choice:") rpc = input() random_number = random.randint(1, 3) if rpc == "rock" or rpc == "paper" or rpc == "scissors": print("Computer choice:") if random_number == 1: random_number = "rock" print(random_number) elif random_number == 2: random_number = "paper" print(random_number) elif random_number == 3: random_number = "scissors" print(random_number) else: print("Error: Internal Problem") elif rpc != "rock" and rpc != "paper" and rpc != "scissors": print("Error: Wrong Input") elif rpc == "exit": print("Thanks for playing!") exit() else: print("Error: Internal Problem") if rpc == random_number: print("Tie") elif rpc == "rock" and random_number == "scissors": print("You win.") elif rpc == "scissors" and random_number == "paper": print("You win.") elif rpc == "paper" and random_number == "rock": print("You win.") else: print("The computer wins.") def still_playing(): game = False while not game: play_again = input("Play again? [yes/no]\n") if play_again == "yes" or "Yes": playing() elif play_again == "no" or "No": print("Thanks for playing!") print("Final score:") print(str(user_score) + " : " + str(comp_score)) game = True exit() elif play_again == "exit": print("Thanks for playing!") elif play_again != "yes" and play_again != "no": print("Error: Misspelling") else: print("Error: Internal Issue") start_playing = False while not start_playing: bp = input("Would you like to begin playing? [yes/no]\n") if bp == "yes" or bp == "Yes": playing() still_playing() start_playing = True elif bp == "no" or bp == "No": print("Have a nice day!") start_playing = True exit() elif bp == "exit": exit() else: print("Error: Mispelling") still_playing()
true
c9682a91d56759cec2e8078c5a6203af750373e8
ssahu/algoprep
/2015-08-21/01_combinations.py
1,573
4.125
4
# space complexity is O(n) # time complexity is O(2^n) import sys def recursion_combination(s, length): # base case of length 0 combination needed if length == 0: return [''] # base case if string is smaller than length of combination needed if len(s) < length: return [] combinations = [] for char, idx in zip(s, range(len(s))): # here is the kicker # example: you need all 2-length combinations of 'abcd' # take a character 'a' and then get all 1-length combinations of 'bcd' # take a character 'b' and then get all 1-length combinations of 'cd' # why not 'acd'? because it was already accounted for when you did # by taking the character 'a' - this is the way you prevent # repeated combinations. # so while recursing, recurse on the substring after the current # character combinations = combinations + [char + t for t in recursion_combination(s[idx+1:], length - 1)] return combinations if __name__ == '__main__': if len(sys.argv) > 1: s = sys.argv[1] combinations = [] print 'input string:', s for i in range(len(s))[1:]: # get combinations of particular length # example: get all combinations of length 2 of the string combinations = combinations + recursion_combination(s, i) print 'combinations:', combinations print 'total number of combinations:', len(combinations) else: print 'input a word' print 'run the program as:' print 'syntax: python 01_combinations.py <string>' print 'example: python python 01_combinations.py xyzabcdefg'
true
44cdeee30e36aad4d35a196b7e35b38b898a4b29
Adam7m8o/CSE
/notes/Adam S._Validator.py
632
4.15625
4
import csv # Drop the last digit from the number. The last digit is what we want to check against # Reverse the numbers - Done # Multiply the digits in odd positions (1, 3, 5, etc.) by 2 and subtract 9 to all any result higher than 9 # Add all the numbers together # The check digit (the last number of the card) is the amount that you would need to add to get a multiple of 10 def check_how_long(num: str): if len(num) == 16: return True return False def remove(num: str): if len(num) == 16: print(num[15]) def reverse(num: str): print(num) print(num[::-1]) def multiply_odd(num: str):
true
505ca1bd7063234fb5d6d95c8aa32e5db0820cc0
dobots/workshops
/python_oops/employee_example/Object-Oriented/6-property-decorator/oop.py
1,273
4.125
4
# This is like getter, setter like in other programming languages # # Motivation behind this is that in email, if we change either self.first of self.last then email does not change. # If we put email as a method, then people using this class will need to change all email attributes to email methods. Big Change! # Thus, we use getters and setters (from Java) for this # class Employee: def __init__(self, first, last): self.first = first self.last = last @property #The property decorator defines a method, but we can extract it like an attribute (basically no () needed when calling it) def email(self): return '{}.{}@email.com'.format(self.first, self.last) @property def fullname(self): return '{} {}'.format(self.first, self.last) @fullname.setter #@<nameofproperty>.setter def fullname(self, name): first, last = name.split(' ') self.first = first self.last = last @fullname.deleter def fullname(self): print('Delete Name!') self.first = None self.last = None emp_1 = Employee('John', 'Smith') emp_1.fullname = "Corey Schafer" print(emp_1.first) print(emp_1.email) print(emp_1.fullname) del emp_1.fullname print(emp_1.first) #None output!
true
7cf9511849b441e228131ee20886553365b77251
meetmaru0810/PYTHONE_ASSIGNMENT
/ASSINGMENT/MODULE_1/Assignment Level Advance/A3.py
322
4.21875
4
# A3:- Write a Python program to sum of three given integers. # However, if two values are equal sum will be zero. a=int(input("enter the no1:")) b=int(input("enter the no2:")) c=int(input("enter the no3:")) if a==b or a==c or b==c: print("sum of three no is=0") else: d=a+b+c print("sum of three no is=",d)
true
9c9a86396d2f4fd41a50448ff87aeb229857ab5d
meetmaru0810/PYTHONE_ASSIGNMENT
/ASSINGMENT/MODULE_1/STRING/Assignment Level Advance/SA1.py
522
4.3125
4
"""A1.Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Go to the editor Sample String : 'w3resource' Expected Result : 'w3ce' Sample String : 'w3' Expected Result : 'w3w3' Sample String : ' w' Expected Result : Empty String """ s1=input("enter the string:") l=len(s1) if l<2: print("empty string") elif l==2: s2=s1[0:2]+s1[0:2] print(s2) else: s3=s1[0:2]+s1[-2:] print(s3)
true
0bdd749c8de9f89648a3b5c5db612452ba65d791
HeithRobbins/python_notes
/tuples/remove-el-from-tuple.py
472
4.15625
4
'''Three Ways to Remove Elements from a Python Tuple''' post = ('Python Basics', 'Intro guide to python', 'Some cool python content', 'published') #removing elements from end # post = post[:-1] #removing elements from beginning # post = post[1:] #removing specfic element (MESSY/NOT RECOMMENDED) post = list(post) #this is changing post from a tuple to a list post.remove('published') post = tuple(post) #this casts this back into a tuple from a list. print(post)
true
d7c356839c2b07de5a45db14e28b4a6776cc7e17
HeithRobbins/python_notes
/guide-to-sorted().py
1,200
4.40625
4
sale_prices = [ 100, 83, 220, 40, 100, 400, 10, 1, 3 ] sorted_list = sorted(sale_prices) # As opposed to .sort(), sorted() is used by placing the list INSIDE the () .sort() permanetaley changes the list reversed_sorted_list = sorted(sale_prices, reverse=True) # To reverse, add a second argument print(sale_prices) print(sorted_list) print(reversed_sorted_list) # NOTION NOTES # SORTED FUNCTION python # # sale_prices = [ # # 100, # # 83, # # 220, # # 40, # # 100, # # 400, # # 10, # # 1, # # 3 # # ] # # sorted_list = sorted(sale_prices, reverse=True) # # print(sorted_list) # sale_prices = [ # 100, # 83, # 220, # 40, # 100, # 400, # 10, # 1, # 3 # ] # # sale_prices.sort() # # sorted_list = sale_prices.sort() # # print(sorted_list) #this will not store in a new variable. # sorted_list = sorted(sale_prices) # print(sorted_list) # print(sale_prices) # # sort and sorted. if the order of the list is going to be neccessary, DO NOT SORT. use sorted and get your copy from that and do with as you will # write me a program that takes a string and sorts it in alphabetical order str="hi there" str2 = "".join(sorted(str)) print(str2)
true
cfd730b4343cc845beae838a576d06d08c83f6c9
RhysMurage/alx-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
418
4.375
4
#!/usr/bin/python3 """ Module that has the function print_square """ def print_square(size): """Prints a square using the character '#' Args: size (int): dimensions of the square """ if not isinstance(size, int): raise TypeError('size must be an integer') if size < 0: raise ValueError('size must be >= 0') h = 0 for h in range(0, size): print('#'*size)
true
a5e6fef420a32a9b41679858462a14bc76813fc1
brittneyexline/euler
/problem9.py
602
4.15625
4
#!/usr/local/bin/python #coding: utf8 import math # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def check_pythagorean(trip): if (trip[0]**2 + trip[1]**2 == trip[2]**2): return True else: return False triplets = [] for a in range(1, 334): for b in range(2*a, 667): triplets.append((a, b-a, 1000-b)) for t in triplets: if (check_pythagorean(t)): print t print t[0] * t[1] * t[2] break
true
93d8723a4c2da88335fd18ecdd2e155cb7e1b164
NandaGopal56/Programming
/PROGRAMMING/python practice/string-6.py
623
4.34375
4
""" Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Go to the editor Sample String : 'abc' Expected Result : 'abcing' Sample String : 'string' Expected Result : 'stringly' """ def add_string(str): if len(str)>=3: s=len(str) if str[s-3:] != 'ing': str=str+'ing' elif str[s-3:] == 'ing': str=str+'ly' print(str) add_string('abc') add_string('string') add_string('gh') add_string('surpriseing')
true
e18f6ebe218700a64e5c82d345a0023bcba03932
NandaGopal56/Programming
/PROGRAMMING/python practice/string-14.py
450
4.125
4
""" Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). Go to the editor Sample Words : red, white, black, red, green, black Expected Result : black, green, red, white """ str="red, white, black, red, green, black" str=str.split(",") l=[] for word in str: if word.strip() not in l: l.append(word.strip()) l.sort() print(l)
true
1f1b2ad1b87347f086256a364aac8af859c9675d
NandaGopal56/Programming
/PROGRAMMING/python practice/weird or not.py
542
4.15625
4
#If n is odd, print Weird #If n is even and in the inclusive range of 2 to 5, print Not Weird #If n is even and in the inclusive range of 6 to 20, print Weird #If n is even and greater than 20, print Not Weird def calculate(n): if n%2!=0: print("Weird") elif n%2==0 and n>=2 and n<=5: print("Not Weird") elif n%2==0 and n>=6 and n<=20: print("Weird") elif n%2==0 and n>20: print("Not Weird") if __name__ == '__main__': n = int(raw_input().strip()) calculate(n)
false
b3cf54c11890d284b118e9a2383d6d9e214e67e0
rg082/TestRepository
/decorator.py
587
4.46875
4
# This is an example program to demonstrate what the decorator is -- # 1. defined a normal function taking variable number of arguments and returning summation # 2. defined decorator function which shall return n*sumr def outer(n): def nsum(f): def inner(*args,**kwargs): print("Inside inner function") return f(*args,**kwargs) * n return inner return nsum @outer(10) def sum(*args,**kwargs): sumr = 0 for arg in args: sumr = sumr + arg return sumr # The below line has been replaced with the decorator with paramters # sum = nsum(sum,5) print(sum(5,6,7,2))
true
7c7496a6e1f4d9cc40ac7bc67b3a8f8f118ac01c
AdityahKulkarni/python
/list_search.py
371
4.34375
4
# Lists are ordered and changable. Lists allow duplicate members #list operation to check for an item in the list import re names = ['Aditya','Nisar','Akshay','Suhas','Ashish'] nm = input("Enter a name: ") if not re.match("^[A-Z][a-z]*$", nm): print("Please enter a string") if nm in names: print(nm,"is in the list.") else: print(nm,"is not in the list")
true
b841401e01ad13d9b28375eb718e46a4551c88c9
type812/practice
/CountOccurenceLinkedList.py
1,595
4.25
4
#two classes each for node object and linked list class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head= None def print_list(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next def append(self,data): new_node = Node(data) #when list is empty if self.head is None: self.head =new_node return #when list has elements already and append this to end last_node = self.head #move and check if the head is not null #last_node .next go over to next and check and update the value while last_node.next: last_node = last_node.next #last null arrived hence assign the value. last_node.next = new_node def count_occ(self,data): count = 0 #initialisation of count variable cur = self.head #set current node as head while cur: #while current node is not null if cur.data == data: #if current node's data matches with the data searched, increase count count+=1 cur = cur.next #set current to point to next node return count #define Linked list object. llist = LinkedList() llist.append("1") llist.append("2") llist.append("1") llist.append("3") llist.append("4") llist.append("5") llist.append("2") llist.append("3") #print(llist.print_list()) #llist.prepend("E") print(llist.count_occ("5")) #print(llist.print_list())
true
3aa4c198b0157dc63cd242508e832608543abc84
ThaynaraDaSilva/PYTHON-1
/LISTA2/ex15.py
2,174
4.21875
4
#------------------------------------------------------------------------------- # program outputs date and time from system # (C) 2020 Flavio Fernando da Silva, Presidente Prudente, Brazil # email tchfernando@gmail.com #------------------------------------------------------------------------------- from datetime import datetime # library today = datetime.now() #gets the date and time from library # conditions checks which month is being output to change from number to name of month if today.month == 1: month = ("January") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 2: month = ("February") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 3: month = ("March") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 4: month = ("April") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 5: month = ("May") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 6: month = ("June") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 7: month = ("July") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 8: month = ("August") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 9: month = ("September") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 10: month = ("October") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 11: month = ("November") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute)) elif today.month == 12: month = ("December") print("{}/ {} / {} - {}:{} ".format(today.day, month, today.year, today.hour, today.minute))
false
e7d918d2204a48cddacb70e32706284d74f864a6
QuickRecon/SchoolEncrypterProgram
/main.py
2,699
4.125
4
from Encrypter import * encrypted = [] decrypted = [] mode = input("\"Encrypt\", \"Decrypt\" or \"Encrypt and generate keypair\": ") if mode == "Encrypt": encrypter = Encrypter() message = input("Enter Message: ") print("I will load the file \"PublicKey.txt\" to read the public key.") text_file = open("PublicKey.txt", "r") publickey = text_file.readline().split(',') blocks = encrypter.convert_text_to_block_array(message) for i in blocks: encrypted.append(encrypter.encrypt(i, publickey)) print(message) print("This will overwrite \"Encrypted.txt\".") permission = input("Is this ok? (\"yes\", \"no\")") if permission == "yes": with open("Encrypted.txt", "w") as text_file: text_file.write(str(encrypted)[1:-1].replace(" ", "")) print("Your message has been written to Encrypted.txt.") print(encrypted) else: print("Exiting") elif mode == "Decrypt": encrypter = Encrypter() print("I will load the file \"Encrypted.txt\" to read the message.") text_file = open("Encrypted.txt", "r") encrypted = text_file.readline().split(',') print("I will load the file \"PublicKey.txt\" to read the public key.") text_file = open("PublicKey.txt", "r") publickey = text_file.readline().split(',') print("I will load the file \"PrivateKey.txt\" to read the private key.") text_file = open("PrivateKey.txt", "r") privatekey = int(text_file.readline()) for i in encrypted: decrypted.append(encrypter.decrypt(int(i), publickey, privatekey)) print("Decrypted: " + encrypter.convert_block_array_to_text(decrypted)) elif mode == "Encrypt and generate keypair": encrypter = Encrypter() message = input("Enter your message:") print("Generating Keypair, this may take a while.") encrypter.generate_key_pair() blocks = encrypter.convert_text_to_block_array(message) for i in blocks: encrypted.append(encrypter.encrypt(i, encrypter.public_key)) print(message) print("This will overwrite \"Encrypted.txt\", \"PublicKey.txt\" and \"PrivateKey.txt\".") permission = input("Is this ok? (\"yes\", \"no\")") if permission == "yes": with open("PrivateKey.txt", "w") as text_file: text_file.write(str(encrypter.private_key)) with open("PublicKey.txt", "w") as text_file: text_file.write(str(encrypter.public_key)[1:-1].replace(" ", "")) with open("Encrypted.txt", "w") as text_file: text_file.write(str(encrypted)[1:-1].replace(" ", "")) print("Your message has been written to Encrypted.txt.") print(encrypted) else: print("Exiting")
true
eedd25c11ad29fca9dbebe69cc670668b087d313
ScarletMoony/py_from_scratch_to_top
/Strings/03.py
588
4.25
4
print("Hello {}".format("Alex")) pi = 3.1415 print("Pi equals {pi:1.2f}".format(pi=pi)) age = input("Age: ") name = input("Name: ") print(f"Hello {name}, you are {age} years old right?") #f означает format # с помощю этого можно вставлять переменные в строки и даже писать мини функции # как в пятой строке этого файла где указана переменная pi и :1.2f что # означает мы хотим чтобы после запятой было лиш 2 символа
false
60446662e98853924b932700892e54ba8438fc5a
SWKANG0525/Algorithm
/LeetCode/206. Reverse Linked List.py
589
4.21875
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverse_list(self, head: ListNode) -> ListNode: node, prev = head, None while node: next, node.next = node.next, prev node, prev = next, node return prev
true
a2fb229abb280090d85e975f5f21a41a2c1382a8
SWKANG0525/Algorithm
/LeetCode/125. Vaild Palindrome.py
616
4.40625
4
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false Constraints: s consists only of printable ASCII characters. """ import re def is_palindrome(self, words: str) -> str: words = words.lower() # Preprocessing words words = re.sub('[^a-z0-9]', '', words) # Filtering Other Characters by RegEx return words == words[::-1] # String Slicing
true
f5eded5adb643f42748c9baede8acb86e57863dd
willem161231/object-oriented-programming_challenges
/tetris.py
1,156
4.28125
4
""" Challenge: Designing Tetris Using OOP Let's consider a classic game, Tetris, in terms of OOP. We start off by describing Tetris to find its objects. Tetris consists of a random sequence of Tetrominos fall down a playing field. The objective of the game is to manipulate these Tetrominos, by moving each one sideways and rotating it by 90 degree units, with the aim of creating a horizontal line of ten blocks without gaps. In Tetris, really the only object is a Tetromino. It has states of: * rotation (in 90 degree units) * shape * color * and behaviors of: * falling * moving (sideways) * rotating """ class Tetronimo: def __init__(self, rotation, shape, color): self.rotation = rotation self.shape = shape self.color = color class Shapes: def __init__(self,length, width, color): self.length = length self.width = width self.color = color def shapegenerator(self): return True thepurpleone = shape("thepurpleone") print(thepurpleone.shapegenerator()) theredone = shape("theredone") print(theredone.shapegenerator())
true
4807b6a8b53e44642572eddfe709510aee822377
sourcecde/cp
/note/script.py
509
4.1875
4
# polynomial evaluation eq = "x**3 + x**2 + x + 1" x = 1 ans = eval(eq) print (ans) # lambda function x = lambda x,y:x+y print(x(10,20)) # reduce function # The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum. from functools import reduce reduce(lambda x, y : x + y,[1,2,3]) # define an initial value reduce(lambda x, y : x + y, [1,2,3], -3)
true
57f30bab50023272cd446174ae76691ca2ebd8e1
ystop/algorithms
/sword/数据流中的中位数.py
1,952
4.1875
4
# -*- coding:utf-8 -*- # 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。 # 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 # 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 # 思路:实际上就是分成2部分,每次插入一部分。如果发生冲突,必须插到另外一个部分,需要另一部分给一个后,才给出去。 # python 只支持小堆, 2个堆。 1堆大顶堆,2堆小顶堆,一个堆存一半,奇数进1堆,偶数进2堆, # 如果应该进1,却比2堆最小的大,需要2堆给1堆一个最小的后,把这个数据给2堆了。 import heapq class Solution: def __init__(self): self.heap1 = [] self.heap2 = [] self.c = 0 def Insert(self, num): # write code here self.c += 1 if not self.heap1: heapq.heappush(self.heap1, num * (-1)) else: if self.c & 1 == 1: if num < self.heap2[0]: heapq.heappush(self.heap1, num * (-1)) else: heapq.heappush(self.heap1, heapq.heappop(self.heap2) * (-1)) heapq.heappush(self.heap2, num) else: if num > self.heap1[0] * (-1): heapq.heappush(self.heap2, num) else: heapq.heappush(self.heap1, num * (-1)) heapq.heappush(self.heap2, heapq.heappop(self.heap1) * (-1)) def GetMedian(self, n = None): # write code here if self.heap1: if (len(self.heap1) + len(self.heap2)) & 1 == 1: return self.heap1[0] * (-1) else: return (self.heap1[0] * (-1) + self.heap2[0]) / 2.0
false
c7d1e319ee5f70100edd5694e0d8365bebdb91f0
karthikrk1/leetcode-solutions
/misc/atoi.py
2,819
4.125
4
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned. Input: "42" Output: 42 Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned. """ class Solution: def atoi(self, s): MAX_INT = 2147483647 MIN_INT = -2147483648 s = s.strip() if s == "": return 0 result = "" if s[0] in ('+', '-'): result += s[0] s = s[1:] for i in range(0, len(s)): if s[i].isnumeric(): result += s[i] else: break if result == "": return 0 try: result = int(result) if result > MAX_INT: return MAX_INT elif result < MIN_INT: return MIN_INT else: return result except: return 0 def main(): sol = Solution() assert sol.atoi("42") == 42 assert sol.atoi("4193 with words") == 4193 assert sol.atoi("words and 987") == 0 assert sol.atoi("-91283472332") == -2147483648 if __name__ == "__main__": main()
true
378635cb2209c91e3907487f9caf35c7873d0af7
davidruffner/computational-physics-nyu-2009
/pythonExamples/tutorial/dictionary.py
701
4.125
4
#dictionary phonebook={'Andrew':8,\ 'Emily Everett':6,'Pete':7,\ 'Lewis':1} print phonebook print "here are the numbers", phonebook.values() phonebook['G']=12 print "added a number, now" print phonebook.values() del phonebook['Lewis'] print "deleted an entry" print phonebook.values() if phonebook.has_key('Andrew'): print "Andrew is in the dict. She is", \ phonebook['Andrew'] else: print "Andrew is not in the dict" print "They are in the phonebook:" print phonebook.keys() keys = phonebook.keys() keys.sort() print keys values = phonebook.values() print values values.sort() print values print "The dictionary has", \ len(phonebook), "entries in it"
true
fcec7aa000bcb87e27270543dc2e4f63bc0782f1
sdkcouto/exercises-coronapython
/chapter_9_9_14.py
1,014
4.25
4
# The module random contains functions that generate random numbers in a variety of ways. The function randint() returns an integer in the range you provide. The following code returns a number between 1 and 6: # from random import randint # x = randint(1, 6) # Make a class Die with one attribute called sides, which has a default value of 6. Write a method called roll_die() that prints a random number between 1 and the number of sides the die has. Make a 6-sided die and roll it 10 times. # Make a 10-sided die and a 20-sided die. Roll each die 10 times. from random import randint class Die(): def __init__(self,sides): self.sides = 6 def roll_die(self): x = randint(1, self.sides) print("value: " + str(x) + " sides: " + str(self.sides)) for d in range(1,11): my_die = Die(6) my_die.roll_die() for d in range(1,11): your_die = Die(10) your_die.roll_die() for d in range(1,11): her_die = Die(20) her_die.roll_die()
true