blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4358054198987e9ca4a66d22007c4badfa5bb618
jvanson/algorithims
/algodaily/reverse_string.py
1,195
4.40625
4
# Can you write a function that reverses an inputted string without using the built-in Array#reverse method? #Let's look at some examples. So, calling: #reverseString("jake") should return "ekaj". # Constraints # Do not use the built-in #reverse() method or [::-1] if Python # Ideal solution would run in O(n) time complexity and O(1) space complexity def reverse_string(s): myarray = list(s) reversearray = [] counter = len(myarray) - 1 while counter > -1 : print(myarray[counter]) reversearray.append(myarray[counter]) counter -= 1 return ''.join(reversearray) # 2nd way that is faster using 2 pointer pattern def reverse_string_two_pointer(s): my_array = list(s) start = 0 end = len(my_array) - 1 while start < end: swap_characters(my_array, start, end) print(my_array) start += 1 end -= 1 return ''.join(my_array) def swap_characters(myarray, start, end): temp = myarray[start] myarray[start] = myarray[end] myarray[end] = temp #result = reverse_string('reverseastring') result = reverse_string_two_pointer('reverseastring') print(result) assert result == 'gnirtsaesrever'
true
5cb63b387b30be2219f6a8f104db6bd063fbfb8e
james-dietz/advent-of-code-2020
/challenges/day02/solutions/part1.py
1,595
4.28125
4
from typing import Tuple Policy = Tuple[str, int, int] def parse_policy(line: str) -> Tuple[Policy, str]: """ Parse a password policy, returning the required letter, and the minimum and maximum number of times it must occur. :param line: the line to parse :return: a tuple containing the password policy, and the password """ policy, password = line.split(sep=": ") character = policy[-1] min_occurrences, max_occurrences = policy.split(" ")[0].split("-") return (character, int(min_occurrences), int(max_occurrences)), password def is_valid_password(policy: Policy, password: str) -> bool: """ Tests whether the provided password conforms to the password policy. :param policy: The character required to be present and the range of possible occurrences :param password: The password to test :return: Whether the password is valid or not """ required_character, min_occurrences, max_occurences = policy occurences = 0 for character in password: if character == required_character: occurences += 1 return min_occurrences <= occurences <= max_occurences def solve_part1(input_filename: str) -> int: with open(input_filename, "r") as input_file: # parse each line's policy and extract the password lines = [parse_policy(line.rstrip("\n")) for line in input_file.readlines()] # count the number of valid passwords return sum([is_valid_password(policy, password) for policy, password in lines]) if __name__ == '__main__': print(solve_part1("../inputs/input.txt"))
true
e0b551ec4c917e42992308a2a02f539dd675a2c0
AbhiGupta06/Data_hendling
/centered.py
980
4.25
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 19 14:36:01 2019 @author: BSDU """ """ Code Challenge Name: Centered Average Filename: centered.py Problem Statement: Return the "centered" average of an array of integers, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. Take input from user Input: 1, 2, 3, 4, 100 Output: 3 """ x = input("Enter the input form User") list1 = x.split(",") list2 = [] for i in list1: num = int(i) list2.append(num) list2.sort() list2.pop() list2.pop(0) average = sum(list2)/len(list2) print("Produce the final average = {}".format(average))
true
560635234e3c41e6a9a4114d773cad3d08a38cea
Ekupka1/Python-Code
/VolumesAreaOfSphere.py
1,747
4.28125
4
# Programming Assignment 1, Circle "Volumes and Area" # Ethan Kupka # Sept 27th, 2019 #Program intentions: Estimating the area in the circle, volume in the sphere, hyper-volume in hyper sphere. #Monte Carlo Method, pi is not given. import random import math numdarts = 100000 insideCount = 0 for i in range(numdarts): randx = random.random() * random.randrange(-1, 2, 2) randy = random.random() * random.randrange(-1, 2, 2) #randz = random.random() * random.randrange(-1, 2, 2) x = randx y = randy #z = randz #t.goto(x,y) freddistance = x**2 + y**2 #+ z**2 #for statement if freddistance <= 1: #fred.color("green") #print("yes") insideCount = insideCount + 1 else: #fred.color("red") #print("no") insideCount = insideCount #fred.stamp() #end of if statement print("The number of darts that inside the circle was:", insideCount) pi = (insideCount / 100000) *4 print("PI is:", pi) #Estimating Area of Circle area = pi * (.5 ** 2) print(area, "Is the estemated area of the circle.") #Estimating Volume of Sphere volume = (4/3) * pi * (.5 ** 3) print(volume, "Is the estimated volume of the 3D sphere.") rvolume = (4/3) * math.pi * (.5 ** 3) print(rvolume, "Is the actual volume of the 3D sphere.") #Estimating Hyper Volume of Hyper-Sphere hvolume = (1 / 2) * (pi ** 2) * (.5 ** 4) print(hvolume, "Is the estimated hyper volume of the hyper sphere.") rhvolume = (1 / 2) * (math.pi ** 2) * (.5 ** 4) print(rhvolume, "Is the actual volume of the 3D sphere.") #wn.exitonclick() #Dimension Names: C2D) S1 R2 - S3D) S2 R3 - HS4D) S3 R4 #Equation: X^2 + y^2 < 1 #EC: A = pi*r^2 #EVS: V = (4/3)*pi*r^3 #EHVS: V1 = (1/2)(pi^2)(r^4) ###V2 = 2(pi^2)(r^3)
true
cc8fc115f67873c2a10af75c196743fa28aa0c84
georgemortleman27/python3-reading-tracker
/readingtracker.py
1,250
4.1875
4
book_list = open("booklist.txt", "a") choice = input("add new or see read ").lower() if choice == "add new": wanna_quit = False while wanna_quit == False: book_name = input("book name: ") author_name = input("author name: ") fiction_or_non_fiction = input("f or nf ").lower() if fiction_or_non_fiction == "f": fiction_or_non_fiction = "fiction" elif fiction_or_non_fiction == "nf": fiction_or_non_fiction = "Non Fiction" book_rating = input("rate the book: ") book_list.write(f"{book_name}, {author_name}, {fiction_or_non_fiction}, {book_rating}" + "/10" + "\n") print(f"{book_name} has been added to your booklist") quit_option = input("Would you like to quit? y or n: ").lower() if quit_option == "y": wanna_quit = True elif quit_option == "n": pass elif choice == "see read": book_list_readable = open("booklist.txt", "r") output = book_list_readable.read() print(output) no_of_fiction = output.count("fiction") no_of_non_fiction = output.count("Non Fiction") no_of_books = no_of_fiction + no_of_non_fiction print(f"You've read {no_of_fiction} fiction books") print(f"You've read {no_of_non_fiction} non fiction books") print(f"You've read {no_of_books} books") else: print("Error. Please Try Again")
false
4fef6a2dd1db0554c3c49269b5843328bb1e1ce6
kevinpau/Bellevue_University_DSC_510
/DSC510_Assignment_4.py
2,707
4.6875
5
""" This week we will implement “if statements” in a program. Your program will calculate the cost of fiber optic cable installation by multiplying the number of feet needed by $.87. We will also evaluate a bulk discount. You will prompt the user for the number of fiber optic cable they need installed. Using the default value of $.87 calculate the total expense. If the user purchases more than 100 feet they are charged $.80 per foot. If the user purchases more than 250 feet they will be charged $.70 per foot. If they purchase more than 500 feet they will be charged $.50 per foot. Display a welcome message for your program. Get the company name from the user Get the number of feet of fiber optic cable to be installed from the user Evaluate the total cost based upon the number of feet requested. Display the calculated information including the number of feet requested and company name. """ # Welcome Message def welcome(): print(""" ########################################### ## ## ## Welcome to Fiber Optic Installs ## ## ## ## We offer the following rates: ## ## $0.87/foot ## ## $0.80/foot for 100 feet or more ## ## $0.70/foot for 250 feet or more ## ## $0.50/foot for 500 feet or more ## ## ## ########################################### """) # Customer information requested def customer_data(): # waiting for user input company_name = input("What is your company name? ") while True: cable_feet = input("Enter the number of feet to be installed: ") # test cable_feet try: if float(cable_feet): break except: print("Cable feet was not a number.", " Please enter a valid number") return company_name, float(cable_feet) # determine total cost def calc_cost(input_length): # set price based on length if input_length < 100: price = 0.87 elif input_length < 250: price = 0.80 elif input_length < 500: price = 0.70 else: price = 0.50 # input_length * price = cost cost = price*input_length return cost, price welcome() name, length = customer_data() tot_cost, install_rate = calc_cost(length) print("Welcome {}, your installation rate is ${:0.2f}/foot.".format(name, install_rate)) print("Based on your installation length of {:0.2f} feet, your total cost will be: ${:0.2f}.".format(length, tot_cost))
true
00367c0b543da8eddb54dc4e2bea10622d8b85c4
lakshmikodi/Python
/Python Notes/Identifiers_Or_Variables.py
1,612
4.21875
4
#!/usr/bin/python #! = Shebang # /usr/bin/python = Absolute path of the python # Creating variables in python # A-Z # Hash means single line comment # a-z # combinations of A-Z & a-z # 0-9 # combinations of A-Z , a-z & 0-9 # an underscore (_). # combinations of A-Z , a-z , 0-9 & _ # Below is the multi-line comment """ """ or ''' '''' """We can use camel-case style i.e., capitalize every first letter of the word except the initial word without any spaces.""" '''This is multi-line comment''' highScoreValue = 1 # Camel-Case Style Variable a = 1 A = 2 #007Redhat = 100 # We are not suppose to use 0-9 as variable names as prefix. Red_007_hat = 100 _007= 200 _007_PyCharm = 200 tools="pycharm" ide_tools='anacodna' course="""Python Python Basic and Advanced Python CGI """ version='''Python 2.x Python 3.x Pycharm - Is a IDE tool Spyder - Is a IDE tool ''' # Let's access variables print("Lets access Camel-Case Style Variable : ",highScoreValue,type(highScoreValue),id(highScoreValue)) print("") print(a,"Access a lower case variable",type(a),id(a)) print("") print("Access a upper case ",A,"variable",type(A),id(A)) print("") print("Lets use combination of all : ",Red_007_hat,type(Red_007_hat),id(Red_007_hat)) print("") print(_007,type(_007),id(_007)) print("") print("UnderScore Digits and Alphabets: ",_007_PyCharm,type(_007_PyCharm),id(_007_PyCharm)) print(tools,type(tools),id(tools)) print(ide_tools,type(ide_tools),id(ide_tools)) print("") print("We are calling course",course,type(course),id(course)) print("") print("Calling version",version,type(version),id(version))
true
cfea1dbcf4b7d62cc5797e00a78f477f30ea1d22
OneCleverDude/SlotMachine
/slotmachine.py
2,589
4.34375
4
# # Slot Machine # ###################################################### # print("Welcome to the Slot Machine!") numberOfTimes = input('How many times do you want to play?') slotsPossible = ["bar","bar","bar","cherry","crown"] Loser = ["\nNot today kid!"] money = int(input ('How much money do you have to start?')) perpullcost = int(input('How much do you want to gamble per pull?')) # # This part builds an array of possible answers. # (the are also called "elements" of the array. # You can try adding or removing things to this list. # ###################################################### # from random import * # # This part loads random so we can use choice later. # Imports are a really neat part of Python, and we'll # talk more about them later, but for now, just know that # we're getting all of the things that random has. # (that's what the asterick does, grabs all of the things.) # ###################################################### # def play(currentmoney,perpullcost): slot1=choice(slotsPossible) slot2=choice(slotsPossible) slot3=choice(slotsPossible) sassyLoss = choice(Loser) win = sassyLoss # # Here we set up three slot by naming three variables as # slot1, slot2, and slot3. If we wanted more, we would just # need a slot4, slot5, and so on. # # the choice() function is from random that we imported # above and that function will get one (and only one) of # the possible elements on the array we built above. # ###################################################### # if (slot1==slot2==slot3=="cherry"): win = "\nYou win "+str(perpullcost) currentmoney = currentmoney + int(perpullcost*10) if (slot1==slot2==slot3=="crown"): win = "\nYou win $50" currentmoney = currentmoney + int(50) if (slot1==slot2==slot3=="bar"): win = "\nYou win $5" currentmoney = currentmoney + int(5) print(slot1+":"+slot2+":"+slot3+" "+win) return currentmoney # # Here is where we decide if you won. We check to see # if the three slot variables are all equivilant (remember # that you want equilivant (==) not an assignment (=). # when they are all equilivant and match the last string, then # we do something with it. In this case, we return it to be printed. # ###################################################### for i in range(int(numberOfTimes)): money = money - int(perpullcost) money = int(play(money, perpullcost)) print("You have "+str(money)+" left.") #we should add a tracker for winnings
true
21917d9dedc5d5b161ac853e88f591397ca9d176
NicoKNL/coding-problems
/problems/kattis/prettygoodcuberoot/sol.py
1,106
4.125
4
import sys def get_lower_and_upper_bound(n): i = 1 while pow(i, 3) < n: i *= 2 if pow(i, 3) == n: return (i, i) lower = i // 2 upper = i return (lower, upper) def closest_to_n(n, lower, upper): diff_below = n - pow(lower, 3) diff_above = pow(upper, 3) - n if diff_below < diff_above: return lower else: return upper def search_approximate_cube_root(n, lower, upper): if upper - lower == 1: return closest_to_n(n, lower, upper) center = (lower + upper) // 2 if pow(center, 3) < n: return search_approximate_cube_root(n, center, upper) elif pow(center, 3) > n: return search_approximate_cube_root(n, lower, center) else: # center == cube_root_of n return center def solve(n): n = int(n) if n == 0: print(0) return lower, upper = get_lower_and_upper_bound(n) approx_cube_root = search_approximate_cube_root(n, lower, upper) print(approx_cube_root) if __name__ == "__main__": for line in sys.stdin: solve(line.strip())
false
5337ac899406ff7d722cb1cb64dc88fdc05abe62
sekendarios/Rock-paper-scissor-game
/rock.py
1,143
4.125
4
import random while True: user_action=input("Enter a choice (rock, paper, sccissor):") possible_action=["rock", "paper", "scissors"] computer_action=random.choice(possible_action) print(f"\nYou Choose",user_action) print(f"\ncomputer Choose",computer_action) if user_action == computer_action: print(f"both player selected {user_action}. it is a tie") elif user_action=="rock": if computer_action =="scissors": print("Rock smashed scissors>> <<YOU WIN>>") else: print("paper cover rock>> <<YOU LOSE>>") elif user_action=="paper": if computer_action =="rock": print("paper cover rock>> <<YOU WIN>>") else: print("scissor cuts paper>> <<YOU LOSE>>") elif user_action=="scissor": if computer_action =="paper": print("scissor cut paper>> <<YOU WIN>>") else: print("Rock smashed scissors>> <<YOU LOSE>>") play_again = input("Play again? (y/n)") if play_again.lower() !="y": break
true
ddd4f4661b389bec631f2aec2f787fb9135caa91
dalalsunil1986/Interview-Prep
/Easy/nonconstructible_change.py
1,618
4.21875
4
""" The idea is to sort the input array, and simply see first if we have the coin 1. If we do, we know we can make change for amount of 1. If not, that's the minimum. Continuing on, we then use change (some number, k) to establish the amount of change we can make UP to and including that number. If we can make change in the interval [1, k] then as long as this inequality holds (coin_value <= k + 1) then we can use any amount in the interval [1, k] + coin_value to extend our interval to [1, k + coin_value] since we can add (1 + coin_val) = k + 1, or 2 + coin_val = k + 2, ... k + coin_val. In the event that we NEVER encounter such a coin in the array that is > k + 1 then we know the minimum change we cannot make is 1 greater than the max change using all of the coins in the array, since we can make any amount from [1, change] thus we can't make change + 1 and we return that. """ def nonConstructibleChange(coins): # validate input, if no coins can't make 1 cent if not coins: return 1 coins.sort() # if after sorting 1 isn't first coin, we can't make 1 cent of change if coins[0] != 1: return 1 min_change = 0 for coin in coins: if coin > min_change + 1: return min_change + 1 # implicit else, we can now make change for ALL integers in the interval [1, min_change] min_change += coin # if we never hit the case where a coin is larger than min_change + 1 in entire array, then # the min change we can't make is 1 greater than # the max change we could make using all of the coins in the array return min_change + 1
true
70ba1fd8e01c8de324b4fb0f174312b431f3c95c
mayusGomez/algorithms
/DivAndConq/mergesort.py
1,062
4.21875
4
""" Mergesort implementation """ import random def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = merge(numbers_list[:mid]) numbers_list_b = merge(numbers_list[mid:]) i = 0 j = 0 while i < len(numbers_list_a) and j < len(numbers_list_b): if numbers_list_a[i] <= numbers_list_b[j]: result.append(numbers_list_a[i]) i += 1 else: result.append(numbers_list_b[j]) j += 1 if i >= len(numbers_list_a): result += numbers_list_b[j:] else: result += numbers_list_a[i:] return result if __name__ == '__main__': numbers_list = [random.randint(0, 100) for x in range(50)] print(f'intial: {numbers_list}') numbers_list = merge(numbers_list) print(f'result: {numbers_list}')
true
5e600f522c66deaa7eb94e87d22b6a15996fdbd3
odairpedrosojunior001/Udacity_IPND
/quiz_dias_do_mes.py
1,020
4.25
4
#-*- coding: utf-8 -*- # Dada a variável days_in_month (dias do mês), crie uma função how_many_days, # que recebe um número representando um mês do ano e devolve o número de dias naquele mês. def how_many_days(month_number): days_in_month=[31,28,31,30,31,30,31,31,30,31,30,31] if month_number==1: return days_in_month[0] if month_number==2: return days_in_month[1] if month_number==3: return days_in_month[2] if month_number==4: return days_in_month[3] if month_number==5: return days_in_month[4] if month_number==6: return days_in_month[5] if month_number==7: return days_in_month[6] if month_number==8: return days_in_month[7] if month_number==9: return days_in_month[8] if month_number==10: return days_in_month[9] if month_number==11: return days_in_month[10] if month_number==12: return days_in_month[11] print how_many_days(12)
false
e26b023954e2f6329062d8d36203afb4b0dd7f58
mayurshetty/Python-Assignment-from-HighSchool
/Lab4.01-de_vowel/Lab 4.01-de_vowel.py
571
4.125
4
vowel_list = ["a","e","i","o","u","A","E","I","O","U"] def de_vowel(a_string): global vowel_list de_vowel_string = [] for list_letter in a_string: if list_letter not in vowel_list: de_vowel_string.append(list_letter) return("".join(de_vowel_string)) def count_vowels(a_string): global vowel_list vowel_letter_num = 0 for list_letter in a_string: if list_letter in vowel_list: vowel_letter_num += 1 print(vowel_letter_num) no_vowels = de_vowel("This sentence has no vowels") count_vowels("This sentence has no vowels") print(no_vowels)
false
916c125a10c8b3f97d44efbd90dbb63248fc46a1
bakil/pythonCodes
/class/inheritance 2.py
822
4.4375
4
class Parent(): def __init__(self,last_name,eye_color): print("Parent constructor called") self.last_name = last_name self.eye_color = eye_color def show_info(self): print "parent info : ", self.last_name , self.eye_color class Child(Parent): # this mean class child will inhert class Parent def __init__(self,last_name,eye_color,number_of_toys): print "child constructor called" Parent.__init__(self,last_name,eye_color)# here we initilize parent class from child class self.number_of_toys = number_of_toys def show_info(self): # when child and parent have same method name ==> method override print "child info : ", self.last_name , self.eye_color ,self.number_of_toys miley_cyrus = Child("Cyrus","blue",5) print miley_cyrus.last_name print miley_cyrus.number_of_toys miley_cyrus.show_info()
false
b2d2cfd97bed63210f7b4910317c29bfb7fd183f
kurbanuglu/lab---pro
/D3_Loop_RecursiveFunction_19.02.19.py
1,168
4.4375
4
# Fibonacci Loop and Recursive Functions # Factorial Loop and Recursive Functions # Power Loop and Recursive Functions def FibonacciLoop(n): a,b=0,1 for i in range(n-1): a,b=b,a+b return a result=FibonacciLoop(5) print(result) def FibonacciRecursive(n): if(n<=3): return 1 else: return FibonacciRecursive(n-1)+FibonacciRecursive(n-2) result_1=FibonacciRecursive(5) print(result_1) def FactorialLoop(n): s=1 for i in range(1,n+1): s=s*i return s result_2=FactorialLoop(5) print(result_2) def FactorialRecursive(n): if(n==1): return 1 else: return n*FactorialRecursive(n-1) result_3=FactorialRecursive(5) print(result_3) def PowerLoop(a,b): s=1 for i in range(b): s=s*a return s result_4=PowerLoop(5,2) print(result_4) def PowerRecursive(a,b): if(b==0): return 1 elif(b==1): return a elif(b%2==0): return PowerRecursive(a*a,b//2) elif(b%2!=0): return PowerRecursive(a*a,b//2)*a result_5=PowerRecursive(5,4) print(result_5)
false
e6a572bd05fe484d0e071d17e51dbee37fe1ecf6
MackRoe/PythonZendeskChallenge
/array_helper.py
692
4.25
4
def make_array(): ''' Creates an array with a length of 100 and containing values from 1 to 100''' new_array = ['1', '2', '3', '4', '5', '6', '7'] highest_value = max(new_array) # # ** Print statement for debugging ** # print('Highest Value: ', highest_value) highest_value = int(highest_value) while highest_value < 100: highest_value += 1 # ** Print statement for debugging ** # print(highest_value) new_array.append(str(highest_value)) comma_seperated_values = '1' comma_seperated_values=', '.join(new_array) # print(comma_seperated_values) return comma_seperated_values # Uncomment to debug * make_array()
true
f5fa1d4a996e6fc2f8054d5504c1c3b5cdd86556
Junaid1011/PythonBasic
/hello.py
835
4.46875
4
# print("hello world") ###########Question############### # Open the file romeo.txt and read it line by line. For each line, split the line into a list # of words using the split() method. The program should build a list of words. For each word on # each line check to see if the word is already in the list and if not append it to the list. # When the program completes, sort and print the resulting words in alphabetical order. # fname = input("Enter file name: ") # fh = open(fname) # lst = list() # lst.append('Arise') # for line in fh: # print(line.rstrip().split()) fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: word= line.rstrip().split() for element in word: if element in lst: continue else : lst.append(element) lst.sort() print(lst)
true
775714b35c58505d5c3573326c0160b182913aed
Hardik00010/Pass-Generator
/pass_generator.py
364
4.125
4
#You have Python3 install to use this script #Executing command #$python3 pass_generator.py string = input("Enter The Words You Want separated by commos :> ") a = string.split(",") n = (int(input("Enter number of Words you input above"))+1) x = n import itertools for e in range(x): for i in itertools.permutations(a,e): print(''.join(i))
true
7e805f27064564ab062df358b6f5b304b19f6489
Yonatan-Kosarev/games
/диалог.py
1,637
4.125
4
while True: oper = input('ты в чёрной дыре!!!!!!!') if oper == "и что мне делать" or oper == "И что мне делать": oper = input("нам надо отсюдо выбраться!") if oper == "Но как" or oper == "но как": oper = input("расшифруй слово КОДИУМ") if oper == "Но я не знаю" or oper == "но я не знаю": oper = input("подумай!!!! (звук обрыва связи)") if oper == "Ок" or oper == "ок": oper = input("-д-у-м-а-й-") if oper == "к-коронно о-ореховый д-дневно и-инностранный у-узноваемый м-мозг": oper = input("(восстоновление связи) неееееееет ") if oper == "Но я не знаю" or oper == "но я не знаю": oper = input("придётся тебе сказать-----к-космическо о-одиночный д-дистанционно и-интересный у-уникально-крутой у-урок") if oper == "Ок а что теперь" or oper == "ок а что теперь": oper = input("потеря св-я-з--- ") if oper == "Неет" or oper == "неет": oper = input("кон-е------ц") break else: print("конец")
false
5b1c121f429e4504cf298f44ecc1c46f13fd2186
harshareddy794/Athmanirbhar-Python-programming-track
/Week 2/8.py
441
4.21875
4
# 8. Write a python function to check whether the given number is Adam number or not # EXAMPLE: Input: 12 Output: Adam Number # Explanation: 12*12=144 Reverse of 12 is 21→ 21*21=441 Reverse of 144==441 def adam(n): rev_mul=n*n n=(str(n))[::-1] n=int(n) mul_rev=n*n if(rev_mul==int(str(mul_rev)[::-1])): print(True) return else: print(False) n=int(input()) adam(n)
true
61ca2c98114da200fadaf1f9416a508164b73295
Shajidur-Rahman/python-with-codewithharry
/Chapter-6/06_main.py
316
4.125
4
sub1 = int(input('enter marks: ')) sub2 = int(input('enter marks: ')) sub3 = int(input('enter marks: ')) plus = (sub1+sub2+ sub3) result = (plus*100)/300 if sub1<33 or sub2<33 or sub3<33: print('The student is failed') elif result < 40: print('The student is failed') else: print('The student is passed')
false
947e31e7f5cb6188922010867d7072261516ce72
irahulgulati/dataStructures
/linkedlist/singlylinkedlist/singlyLinkedList.py
2,913
4.1875
4
from .node import Node class LinkedList: """ * Creating LinkedList class which represent the linkedlist * data structure. Each object instantiate of this class * will give the individual instance of linkedlist with * access to linkedlist operational methods. * `head` is class attribute which is of type Node and denotes * the head node of the instantiated linkedlist """ head: Node = None # addNode method to add signle node to linkedlist def addNode( self, data: int ) -> None: if self.head is None: self.head = Node(data) else: newNode = Node(data) currentNode = self.head while currentNode.next is not None: currentNode = currentNode.next currentNode.next = newNode def deleteWithValue( self, data: int ) -> None: if self.head is None: return if self.head.data == data: self.head = self.head.next return currentNode = self.head if currentNode.next.data == data: currentNode.next = currentNode.next.next currentNode = currentNode.next def searchWithValue( self, data: int ) -> Node: if self.head.data == data: return self.head currentNode: Node = self.head while currentNode.data != data: currentNode = currentNode.next return currentNode def size( self ) -> int: size: int = 0 if self.head is None: return 0 currentNode: Node = self.head while currentNode: size += 1 currentNode = currentNode.next return size def insertAfterNode( self, prevNode: Node, data: int ) -> None: if self.size() == 0: return currentNode: Node = self.head while currentNode != prevNode: currentNode = currentNode.next newNode: Node = Node(data) newNode.next = currentNode.next currentNode.next = newNode def deleteAfterNode( self, prevNode: Node ) -> None: if self.size() == 0: return currentNode: Node = self.head while currentNode != prevNode: currentNode = currentNode.next if currentNode.next == None: return currentNode.next = currentNode.next.next def deleteHead( self ) -> None: if self.head is None: return self.head = self.head.next return def insertHead( self, data: int ) -> None: if self.head is None: self.addNode(data) return oldHead: Node = self.head self.head = Node(data) self.head.next = oldHead return
true
a415fe5320b5be947ad0e6653b796c1ea3e745e2
alikhanlab/python-city
/outdoors/park.py
635
4.125
4
def draw_park(num_trees = 10, num_people = 10): """ The function prints symbolic trees and people. It takes as parameters: 'num_trees' - number of trees to print. 'num_people' - number of people to print. Returns None. """ if num_trees < 0: raise ValueError('Number of trees can not be negative') for _ in range(num_trees): print('~\|/~') if num_people < 0: raise ValueError('Number of people can not be negative') for _ in range(num_people): print('-_-') print('<|>') print("/ \ ") return
true
997b19ba7fe467313a9e64ccc5cd046ecd7f1304
henryxian/leetcode
/reverse_linked_list.py
786
4.15625
4
# Reverse Linked List # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ stack = [] dummy = ListNode(None) dummy.next = head curr_node = dummy.next hd = None while curr_node != None: stack.append(curr_node) curr_node = curr_node.next if len(stack) != 0: tail = stack.pop() tail.next = None hd = tail while len(stack) != 0: tail.next = stack.pop() tail = tail.next tail.next = None return hd
false
1d61123877d5d3f78a9f235d4527a12ca16db94b
mengyuqianxun/coding-interview-Python
/jianzhioffer/11.py
414
4.15625
4
def BubbleSort(array): if len(array) == 0: print('数组为空') return [] if len(array) == 1: return array for i in range(len(array)-1): for j in range(len(array)-i-1): if array[j] > array[j+1]: array[j],array[j+1] = array[j+1],array[j] return array if __name__ == '__main__': array = [13,2,8,3,40,3,9,0,7] array = BubbleSort(array) for i in range(len(array)): print(array[i],end = ' ')
false
044b076a30123cc48a988c09448da7684f636728
patrickjwolf/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
480
4.3125
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): count = arr.count(0) zeros_list = [0 for i in range(count)] print(zeros_list) #iterate through array x = [i for i in arr if i != 0] print(x) arr= x + zeros_list return arr if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
true
d4266dd75cb9faad211662ff337cb80213882d18
abhinavprasad47/KTU-S1-S2-CS-IT-Python_C-programs
/Python Programmes/26_pattern_*.py
350
4.21875
4
# program to Display the pattern # * # * * # * * * # n inputs the number of lines n=input("Enter the limit: ") # num is set as * num="*" # nested for to printing each line for i in range(1,n+1): for j in range(1,i+1): # print num in each line and "," is important to print next output in saame line print num, # "/n" is next line print "\n"
true
f12cdacf9eab3fd38dda8cdaf1212a19593822fa
abhinavprasad47/KTU-S1-S2-CS-IT-Python_C-programs
/Python Programmes/9_max_of_3_nos.py
290
4.25
4
#Max of 3 Numbers n1=input("Enter the 1st number: ") n2=input("Enter the 2nd number: ") n3=input("Enter the 3rd number: ") #Using The Max Function m1=max(n1,n2) m2=max(n2,n3) m3=max(n1,n3) #Conditional Block if m1>m2: print(m1) elif m2>m3: print(m2) elif m3>m1 or m3>m2: print(m3)
false
b2a860a30eeb87e16285331b583de5194420a669
abhinavprasad47/KTU-S1-S2-CS-IT-Python_C-programs
/Python Programmes/21_Armstrong_or_not.py
494
4.28125
4
# Program to check whether given number is amstrong or not # x is to input the number to be checked num=input("Enter the number: ") sum=0 #temp=num is to use first value of num at line 11 temp=num # while loop to check for amstrong while num>0: digit=num%10 # the cube of the last digit of num is added in each execution of loop sum+=digit**3 num=num/10 # if statement checks whether the sum is equal to the first num if sum==temp: print "Number is Armstrong" else: print "Not Armstrong"
true
6a4e293b0eed78f50912ae3b540f992ce7d1c62d
ProgramSalamander/AlgorithmLesson
/管道网络.py
2,316
4.125
4
# 管道网络 # 描述 # # Every house in the colony has at most one pipe going into it and at most one pipe going out of it. # Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap. # Find the efficient way for the construction of the network of pipes. # # # 输入 # # The first line contains an integer T denoting the number of test cases. # For each test case, the first line contains two integer n & p denoting the number of houses and number of pipes respectively. # Next, p lines contain 3 integer inputs a, b & d, d denoting the diameter of the pipe from the house a to house b. # Constraints: # 1<=T<=50,1<=n<=20,1<=p<=50,1<=a, b<=20,1<=d<=100 # # # 输出 # # For each test case, the output is the number of pairs of tanks and taps installed i.e n followed by n lines that contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. # # # 输入样例 1 # # 1 # 9 6 # 7 4 98 # 5 9 72 # 4 6 10 # 2 8 22 # 9 7 17 # 3 1 66 # 输出样例 1 # # 3 # 2 8 22 # 3 1 66 # 5 6 10 import sys if __name__ == '__main__': case_num = int(input()) for _ in range(case_num): houses_num, pipes_num = [int(_) for _ in input().split(' ')] tanks = [] taps = [] froms = [] tos = [] diameters = [] for _ in range(pipes_num): from_house, to_house, diameter = [int(_) for _ in input().split(' ')] froms.append(from_house) tos.append(to_house) diameters.append(diameter) for i in range(1, houses_num + 1): if i in froms and i in tos: pass elif i in froms: tanks.append(i) elif i in tos: taps.append(i) # print(tanks) # print(taps) print(len(tanks)) for tank in tanks: cur = tank min_diameter = sys.maxsize while cur in froms: idx = froms.index(cur) min_diameter = min(diameters[idx], min_diameter) cur = tos[froms.index(cur)] print('%d %d %d'%(tank, cur, min_diameter))
true
9a74718bee4880fad25c0c6734fbe3dca0074a93
Mortr0n/functionsBasic2
/functionsBasic2.py
2,661
4.40625
4
# 1. Countdown - Create a function that accepts a number as an input. # Return a new list that counts down by one, from the number # (as the 0th element) down to 0 (as the last element). # Example: countdown(5) should return [5,4,3,2,1,0] # numList=[] # def countdown(num): # for x in range(num, -1, -1): # numList.append(x) # return numList # print(countdown(14)) # 2. Print and Return - Create a function that will receive a list with two numbers. # Print the first value and return the second. # Example: print_and_return([1,2]) should print 1 and return 2 # def printReturn(a,b): # print(a) # return(b) # print(printReturn(4,5)) # print(printReturn(-40,95)) # print(printReturn(0,8) + printReturn(8,8)) # 3. First Plus Length - Create a function that accepts a list and returns # the sum of the first value in the list plus the list's length. #Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5) # def firstPlusLength(someList): # return someList[0]+len(someList) # print(firstPlusLength([1,2,3,4,5,10,15])) # 4. Values Greater than Second - Write a function that accepts a list # and creates a new list containing only the values from the original # list that are greater than its 2nd value. Print how many values this is # and then return the new list. If the list has less than 2 elements, have the # function return False # Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4] # Example: values_greater_than_second([3]) should return False # def valuesGreaterthanSecond(numList): # newList = [] # if(len(numList)>2): # second = numList[1] # for num in range(0, len(numList), 1): # if(numList[num]>second): # newList.append(numList[num]) # print(len(newList)) # return newList # else: # return False # print(valuesGreaterthanSecond([5,2,3,2,1,4])) # print(valuesGreaterthanSecond([3])) # print(valuesGreaterthanSecond([52,-2,3,2,1,4,-1,0,-3,-5])) # 5. This Length, That Value - Write a function that accepts two integers # as parameters: size and value. The function should create and return a # list whose length is equal to the given size, and whose values are all # the given value. # Example: length_and_value(4,7) should return [7,7,7,7] # Example: length_and_value(6,2) should return [2,2,2,2,2,2] # def thisLengthThatValue(size, value): # newList = [] # for x in range(size): # newList.append(value) # return newList # print(thisLengthThatValue(4,7)) # print(thisLengthThatValue(6,2)) # print(thisLengthThatValue(0,3))
true
d1cd9c2d66c86a9ab321238aabc4fe4cc1feb83f
Deepakgarg2309/All_Program_helper
/Python/ArmstrongNumberCheck.py
456
4.25
4
#Program to check whether the given number is Armstrong or not from math import * n1 = int(input("Enter the number : ")) result = 0 n = 0 temp = n1r; while (temp != 0): temp =int(temp / 10) n = n + 1 #Checking if the number is armstrong temp = n1 while (temp != 0): remainder = temp % 10 result = result + pow(remainder, n) temp = int(temp/10) if(result == n1): print("Armstrong number") else: print("Not an Armstrong number")
true
1fc299d26d122aef02de7b2a75af27cac975f812
Deepakgarg2309/All_Program_helper
/Python/ques.py
786
4.25
4
"""#Day 8 Question - You are painting a wall. The instructions on the paint can says that 1 can of paint can cover 5 square meters of wall. - Given a random height and width of wall, calculate how many cans of paint you'll need to buy. - number of cans = (wall height ✖️ wall width) ÷ coverage per can. - e.g. Height = 2, Width = 4, Coverage = 5 number of cans = (2 ✖️ 4) ÷ 5 = 1.6 = 1.6 - But because you can't buy 0.6 of a can of paint, the result should be rounded up to 2 cans.""" import math def paint(height, width, cover): area = height*width cans = area/cover print(math.ceil(cans)) h = int(input("Height of wall: ")) w = int(input("Width of wall: ")) coverage = 5 paint(height=h, width=w, cover=coverage)
true
e277dbea3cbc0636058ade141bc42b72f18f25fa
hoangrandy/Python
/learningpython/ex30.py
788
4.46875
4
# ----------------------------------------------------------------------------- # Name: Using else and If # Purpose: Practice using Else and If # # Author: Randy Hoang # Date: 1/16/2018 # ----------------------------------------------------------------------------- people = 30 cars = 40 buses = 15 # If statements ends with a : and next lines starts with an indent if cars > people: print "We should take the cars." elif cars < people: print "We should not take the cars." else: print "We can't decide" if buses > cars: print "That's too many buses." elif buses < cars: print "Maybe we could take the buses." else: print "We still can't decide" if people > buses: print "Alright, let's just take the buses." else: print "Fine, let's stay home then."
true
982441d44a6941034e338892045a27d3d6dd4d5f
huioo/Mega-Project-List
/Python3.6.5/Classic_Algorithms/Sorting/merge.py
1,755
4.21875
4
# 合并两个有序列表 """ 合并两个有序列表 分解成多个一个元素的列表时,类似归并排序。 https://github.com/taizilongxu/interview_python#8-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%9C%89%E5%BA%8F%E5%88%97%E8%A1%A8 """ # 1 尾递归 def _recursion_merge_sort2(l1, l2, tmp): """ 递归合并排序 递归对2个列表进行操作,每次取各列表第一个元素插入到传递的中间列表中 """ if len(l1) == 0 or len(l2) == 0: tmp.extend(l1) tmp.extend(l2) return tmp else: if l1[0] < l2[0]: tmp.append(l1[0]) del l1[0] else: tmp.append(l2[0]) del l2[0] return _recursion_merge_sort2(l1, l2, tmp) def recursion_merge_sort2(l1, l2): return _recursion_merge_sort2(l1, l2, []) # 循环算法 def loop_merge_sort(l1, l2): """ 定义新的空列表存放结果; 比较2个列表第一个元素,插入小的元素到新列表中,并删除该元素 最终会出现2个列表中某个列表为空的情况,将旧列表追加到新列表的最后 """ tmp = [] while len(l1) > 0 and len(l2) > 0: if l1[0] < l2[0]: tmp.append(l1[0]) del l1[0] else: tmp.append(l2[0]) del l2[0] tmp.extend(l1) tmp.extend(l2) return tmp # pop弹出 def merge_sortedlist(a, b): c = [] while a and b: if a[0] >= b[0]: c.append(b.pop(0)) else: c.append(a.pop(0)) while a: c.append(a.pop(0)) while b: c.append(b.pop(0)) return c if __name__ == '__main__': l1 = [1, 2, 3, 7] l2 = [3, 4, 5] print(merge_sortedlist(l1, l2))
false
a9bc2f9203f321a844bc859d741a30c0d3a3247e
huioo/Mega-Project-List
/Python3.6.5/Numbers/fibonacci_number.py
1,136
4.5625
5
# Fibonacci Sequence """ Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. 斐波那契数列 referer: https://github.com/MrBlaise/learnpython/blob/master/Numbers/fibonacci.py """ def sequence_length(maximum=100): print('Enter the number of lengths of the Fibonacci sequence you want: ') while True: s = input('>>> ') try: digits = int(s) if digits >= maximum: print("Enter a number smaller than %d." % maximum) elif digits >= 0: return digits else: print("Enter a nonnegative integer.") except ValueError: print("You did not enter an integer") def fibonacci(n): """ Fibonacci number https://en.wikipedia.org/wiki/Fibonacci_number :param n: :return: """ if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) def main(): length = sequence_length() print('the %dth number:' % length, fibonacci(length)) if __name__ == '__main__': main()
true
45aaa7756c00ce8a576da714439af4d78d9f8593
meganduffy/adventure
/adventure.py
1,228
4.46875
4
# coding=utf-8 from data import locations # Each direction is a set of coordinates which, when added to a position, # # will move it in that direction. # So for instance, if we’re currently at (1, 1), moving east # will result in (1+1, 1) = (2, 1). # Moving west will result in (1-1, 1) = (0,1). directions = { "west": (-1, 0), "east": (1, 0), "north": (0, -1), "south": (0, 1) } position = (0, 0) while True: location = locations[position] print "You are at the %s" % location valid_directions = {} for k, v in directions.iteritems(): # k, v -> key, value possible_position = (position[0] + v[0], position[1] + v[1]) # generates new position for each direction possible_location = locations.get(possible_position) # .get is a dictionary method which returns None if that key doesn't exist if possible_location: print "To the %s is a %s" % (k, possible_location) valid_directions[k] = possible_position direction = raw_input("Which direction do you want to go?\n") new_position = valid_directions.get(direction) if new_position: position = new_position else: print "Sorry, that isn't a valid direction"
true
ae804eb5a09d7160e47a8fe18fc2420d02371743
ngocyen3006/learn-python
/automatetheboringstuff.com/ch04/exampleMethods.py
1,677
4.375
4
# Finding a value in a list with the "index()" method greeings = ['hello', 'hi', 'howdy', 'heyas'] print(greeings.index('hello')) # 0 print(greeings.index('heyas')) # 3 spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka'] print(spam.index('Pooka')) # 1, not return 3 animals = ['cat', 'dog', 'bat'] # Add value to lists with the "append()" and "insert()" method animals.append('moose') print(animals) # ['cat', 'dog', 'bat', 'moose'] animals.insert(2, 'chicken') print(animals) # ['cat', 'dog', 'chicken', 'bat', 'moose'] # Removing values from lists with "remove()" and "del" animals.remove('chicken') print(animals) # ['cat', 'dog', 'bat', 'moose'] animals.insert(3, 'cat') animals.insert(5, 'cat') print(animals) # ['cat', 'dog', 'bat', 'cat', 'moose', 'cat'] animals.remove('cat') print(animals) # ['dog', 'bat', 'cat', 'moose', 'cat'] del animals[2] print(animals) # ['dog', 'bat', 'moose', 'cat'] # Sorting the values in a list with the "sort()" method greeings.sort() print(greeings) # ['hello', 'heyas', 'hi', 'howdy'] number = [2, 5, 3.14, 1, -7] number.sort() print(number) # [-7, 1, 2, 3.14, 5] animals.insert(0, 'ant') animals.append('badger') animals.append('elephant') print(animals) # ['ant', 'dog', 'bat', 'moose', 'cat', 'badger', 'elephant'] animals.sort(reverse=True) print(animals) # ['moose', 'elephant', 'dog', 'cat', 'bat', 'badger', 'ant'] charSort = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats'] charSort.sort() print(charSort) # ['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats'] alphabet = ['c', 'a', 'z', 'A', 'Z', 'B'] alphabet.sort(key=str.lower) print(alphabet) # ['a', 'A', 'B', 'c', 'z', 'Z']
true
644d12914219d4ee5620399e3d2f5665eef8500e
ngocyen3006/learn-python
/automatetheboringstuff.com/ch03/TheCollatzSequence.py
363
4.21875
4
# Practice projects "The Collatz Sequence" and "Input Validation" def collatz(number): if number % 2 == 0: return number / 2 else: return 3 * number + 1 try: number = int(input()) while (number > 1): print(int(collatz(number))) number = collatz(number) except ValueError: print("Error: Invalid argument.")
true
204d5f91f06c3e5316e4a249e5cb8bd0bd71c459
SabineJulia/my-first-blog
/atomtest.py
826
4.25
4
print('Hello, Django girls!') print (1+2) if 3>2: print('it works!') if 5>2: print('5 is indeed greater than 2') else: print('5 is not greater than 2') name = 'Hola' if name == 'Hola': print('Hola Locas!') elif name == 'Buenas': print('Hey Djangogirl') else: print('ey joooo') #this is so interesting shiat volume = 1 if volume <20 or volume > 80: volume = 50 print('thats better!') #function def hi(): print('hey jo') print('que pasa?') hi() def hi(name): if name == 'Hola': print('Hola Locas!') elif name == 'Buenas': print('Hey Djangogirl') else: print('ey joooo') hi("hola") def hi(name): print('buenas' + name + '!') hi ("seniora") #LOOOOOOOOOPs girls = ['Natalie', 'Bini', 'Monica', 'Matteo'] for name in girls: hi(name) print('Next girl')
false
010e81fdbc60ee50a190f5d00b75f4d64928e6ed
T800GHB/Python_Basic
/RegExp/basic_usage.py
1,806
4.4375
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 3 22:21:42 2016 @author: T800GHB This file will demostrate how to use regular expression in python. The detial of usage will not list. When needed, learn it deeper. Basis: ^ start $ end \d a nunber \w a number or character * any longer of string include 0 + not less one character ? 0 or 1 {n} n character {n,m} n to m character A|B A or B can be matched [] scope.[0-9a-zA-Z\_] can match one of number , a character , underscore. () group """ #Python use regular expression with re model. import re def run_demo(): """ Match function will search between pattern and instance. If successfully matched, return a match object, otherwise None """ r = re.match(r'^\d{3}-\d{3,8}$', '024-883215') print('Result of re match function:', r) """ Split string with specific pattern """ s = re.split(r'[\s,\;]+','a,b;;c d') print('Result of spliting a string is: ',s) """ Use () to form more than one group, the group(0) wiil always be orignal information """ m = re.match(r'^(\d{3})-(\d{3,8}$)','010-254554') print('Group 0 :', m.group(0)) print('Group 1 :', m.group(1)) print('Group 2 :', m.group(2)) """ If you don't want to use greedy match, ? can help Groups function will return a tuple that contain a sperated group. """ g = re.match(r'^(\d+?)(0*)$','102300').groups() print('Result of un-greedy : ', g) """ Compile a regular expression when you will use a pattern frequently. """ re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$') c = re_telephone.match('022-027492').groups() print('Result of compiled pattern matched: ', c)
true
d0eeccd1dbe5d5f19bb6053a2016666ac98d434e
jc732351/Practicals
/A2/place.py
925
4.1875
4
"""...""" # Create your Place class in this file class Place: """...""" """the initial function ,initialize the name,country,priority,visited_status""" def __init__(self,name,country,priority,visited_status): self.name=name self.country=country self.priority=priority self.visited_status="" self.is_visited(visited_status) """return the information of the place""" def __str__(self): return self.name+' in '+self.country+',priority '+str(self.priority)+self.visited_status """Determine if you have already visited""" def is_visited(self,visited_status): if visited_status=='n': self.visited_status='' elif visited_status=='v': self.visited_status='(visited)' """set the importance of the place""" def is_important(self): if self.priority<=2: self.visited_status='important'
true
d95be484263dc1d1167d88f5fc073fc8edbeeac5
iFocusing/Leetcode
/98_medium_validate_binary_search_tree.py
1,488
4.15625
4
# Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. """ def isValidBST(self, root: TreeNode) -> bool: def helper(node, lower=float('-inf'), upper=float('inf')): if node is None: return True if node.val <= lower or node.val >= upper: return False if not helper(node.right, node.val, upper): return False if not helper(node.left, lower, node.val): return False return True return helper(root) def bulid(self, l: List[int]): expand = [] head = TreeNode(l[0]) expand.append(head) if len(l) == 1: return head i = 0 while i < len(l) - 2: i += 1 node = TreeNode(l[i]) expand.append(node) expand[0].left = node i += 1 node = TreeNode(l[i]) expand.append(node) expand[0].right = node expand.pop(0) return head sol = Solution() print(sol.isValidBST(sol.bulid([5,1,4,"null","null",3,6])))
true
408b80e48ed45b3b3341ee9cdae52ab365c56695
DevEduVn/PythonOnline202004
/Session07/listDemo.py
1,704
4.1875
4
# List in python """ Python list có khả năng lưu trữ các kiểu dữ liệu khác nhau Bạn có thể thay đổi phần tử trong list Thứ tự trong List bắt đầu từ 0 Giá trị lưu trong List được phân cách bởi dấu phẩy """ # Khai báo một list các phần tử, sử dụng cặp dấu [] lst = ["Táo", "Lê", "Đào", "Mận", "Quýt", "Mơ"] # In print(lst) # Khai báo list hỗn hợp kiểu lst1 = ["Táo", 10, "Lê", 20] print(lst1) # Duyệt mảng thông qua vòng lặp for x in lst: print(x) # //=End # Truy cập thông qua chỉ số mảng (Chỉ số bắt đầu từ 0) for i in range(0, len(lst)): print(lst[i]) # //=End # Truy cập đến tập con trong danh sách => thông qua chỉ số print(lst) print(lst[1:4]) # Tập con có chỉ số 1,2,3 # Truy cập thông qua chỉ số âm print(lst) print("lst[-1]=>", lst[-1]) print("lst[-2]=>", lst[-2]) print("lst[-4:]=>", lst[-4:]) print("lst[-5:-3]=>", lst[-5:-3]) print("lst[-3:-1]=>", lst[-3:-1]) # Thay đổi giá trị của list thông qua chỉ số years = [2001, 2002, 2005, 2008, 2009, 2010, 2018, 2019] print(years) years[0] = 2000 # Thay đổi giá trị trong list tại chỉ số 0 print(years) # Thay đổi một đoạn years[2:6] = [2010, 2015] print(years) # Thêm giá trị vào cuối danh sách years.append(2020) print(years) # Thêm vào đầu danh sách 2 phần tử # years[0] = [1998, 1999] # print(years) # Xóa del (years[0]) print(years) del years[0:2] print(years) years.remove(2019) print(years) years1 = [2020, 2030, 2040] lstNew = years+years1 print(lstNew) cuoi = ["Ha", "Ha", "Ha"] print(cuoi) cuoi = ["Ha"] print(cuoi*3)
false
9e8898760dd94769ff305f91157ac4b370c04e8a
lgallez/csClasses
/python/p6.py
515
4.34375
4
# p6.py # Layla Gallez # 2/14/2021 # Python 3.8.1 # Description: Program to show output in Python print('Enter your height') feet = float(input('feet:')) inches = float(input('inches:')) totalInches = feet*12 + inches print('%.0f feet %.0f inch(es) = %.0f inches'%(feet,inches,totalInches)) ''' /Users/layla.gallez/Desktop/Gavilan/PythonClass/venv/bin/python /Users/layla.gallez/Desktop/Gavilan/PythonClass/main.py Enter your height feet:5 inches:6 5 feet 6 inch(es) = 66 inches Process finished with exit code 0 '''
false
a777925146ed93e5a102014a590e8c63857461fc
lgallez/csClasses
/python/p7.py
591
4.125
4
# p7.py # Layla Gallez # 2/14/2021 # Python 3.8.1 # Description: Program to show output in Python PI = 3.1415 radius = float(input('enter radius:')) if radius < 0: print('error, radius cannot be negative') else: area = PI * radius * radius print('a circle with radius %.1f inches has' % radius) print('area: %.1f square inches' % area) ''' /Users/layla.gallez/Desktop/Gavilan/PythonClass/venv/bin/python /Users/layla.gallez/Desktop/Gavilan/PythonClass/main.py enter radius:9 a circle with radius 9.0 inches has area: 254.5 square inches Process finished with exit code 0 '''
true
0ddca7b9d7588b008c3725f8f0571e5df2a73f8d
morganwells/Coding-Challenges
/PythonFiles/PalindromeChallenge.py
1,850
4.46875
4
# Palindrome Challenge By Morgan Wells # Input: User enters a word that they want to know if its a palindrome (entry of word) # Output: 1) A palindrome ("This is a palindrome") # 2) Not a palindrome ("This word is not a pallindrome") # 3) Error # Reference: Reverse a string in Python, (n.d.) Available At: https://stackoverflow.com/questions/931092/reverse-a-string-in-python Accessed: 30-3-19 # Data Tests: # Bad Tests (Not a palindrome): Cat, Nap, hello, goodbye # Good Tests (a palindrome): rotor, Rotor # Error (somethings wrong): Hell o # Imported Modules: import re # This is a module that has a set of commands to help you with regular expressions # Setting Variables: input_word = "" # input_word is the variable to store the users word to test # Getting the user input: input_word = input("Enter a word: ") # Capturing the word that the user is typing and putting it into the input_word container # Checking for spaces or non A to Z characters: pattern = re.compile('[^a-zA-Z]') # Here I am creating a regular expreesion that tests for anything that inst a letter if (pattern.findall(input_word)): print('The word must contain only letters not numbers, spaces or characters') # Converting all to lowercase letters: lowercase_word = input_word.lower() # Taking the input_word changing this to lower case and then putting it into the lowercase_ word # Reversing the input: reverse_word = lowercase_word[::-1] # Reversing the characters of the word in the string lowercase_word # Testing to see if input equals reverse of input: if (lowercase_word == reverse_word): # Comparing whats in the lowercase_word container and the reverse_word container to see if its a palindrome print("This word is a pallindrome") else: print("This word is not a pallindrome")
true
46336546e2d521b68f38689b27124ddd9c2ed79f
JiayingWei/SoftwareDesign
/midterm/reverse.py
370
4.4375
4
def reverse_text(input_text): """ Takes in some text and returns the text in reversed order (character by character) """ new_name = '' for i in range(len(input_text)-1, -1, -1): new_name += input_text[i] return new_name def main(): my_name = "abut ttub A" print reverse_text(my_name) if __name__ == "__main__": main()
true
9e231338ad06feddb431c9d79c94084a3aa5ffc1
connorjayr/AdventOfCode
/archive/2015/01/main.py
1,088
4.1875
4
import collections import functools import itertools import operator import re import typing def first_basement_position(instructions: str) -> int: """Finds the first character position which results in Santa entering the basement. Arguments: instructions -- the instructions that tell Santa to go up or down one floor """ floor = 0 for pos, char in enumerate(instructions): if char == '(': floor += 1 else: floor -= 1 if floor == -1: return pos + 1 def solve(input_file: typing.IO) -> typing.Generator[str, None, None]: """Generates solutions to the problem. Arguments: input_file -- the file containing the input """ data = [line.strip() for line in input_file if line.strip()] yield str(sum([1 if char == '(' else -1 for char in data[0]])) yield str(first_basement_position(data[0])) def main() -> None: """Called when the script is run.""" with open('input.txt', 'r') as input_file: # Print each solution (parts 1 and 2) for solution in solve(input_file): print(solution) if __name__ == '__main__': main()
true
28fb803f484a7a47253357a2bfa2ff4d236f1435
PMileham/IT3038C-Scripts
/Project 2/P2.py
1,168
4.34375
4
import datetime import time print ("This will calculate exactly how old you are and display when your golden birthday is!") print("A golden birthday is when you turn the age of the day your birthday is on. So if your birthday is on the 13th, your golden birthday would be when you turn 13 on the 13th.") myName = input("What is your name? ----> ") print('Hello, ' + myName + '! ') by = int(input("Please enter the year that you were born: ")) bm = int(input("Please enter the month: ")) bd = int(input("Please enter the day: ")) this_year = datetime.date.today().year this_month = datetime.date.today().month this_day = datetime.date.today().day age_yearRN = this_year - by - 1 age_monthRN = abs(this_month-bm - 2) age_dayRN = abs(this_day-bd) print ("Your age is: ", age_yearRN, "Years, ", age_monthRN, "Months, ", age_dayRN, "Days, ") print ("Your golden birthday will be when you are", bd, "years old.") print("Which is in.........") time.sleep(2.5) print("about", bd - age_yearRN, "years!" ) if bd - age_yearRN < 0: print("Oh no! You already had your golden birthday!") elif bd - age_yearRN == 0: print("You had/have your golden birthday this year!!")
false
c73d0a7e87d0d8fa6b8904916f37113bfc6b3f4e
imanahmedy29/hello-world
/collatz.py
402
4.15625
4
numb=int(input("Enter a number: ")) def collatz(numb): print(numb) while numb>1: if numb%2==0: numb=numb//2 print(numb) else: numb=(numb*3)+1 print(numb) collatz(numb) ques=input("Would you like to input another number? ") while ques=="yes": numb=int(input("Enter a number: ")) collatz(numb) ques=input("Enter yes if you like to input another number: ")
true
b7f5044a1423cf1d989c02cf51f637a75f86e155
managorny/algorithms_python
/les01/Lesson_1/task_4.py
279
4.125
4
# y = 2x - 10, если x > 0 # y = 0, если x = 0 # y = 2 * |x| - 7, если x < 0 # x - целое число x = int(input('Введи целое число: ')) if x > 0: y = 2 * x - 10 elif x == 0: y = 0 else: y = -2 * x - 7 print(f'{y=}')
false
d74ace036532b4c6c6d39e47e3362720e5cdc249
wisteknoll/self_taught
/st_003.py
332
4.21875
4
print("above") print("and") print("behind") x = 11 if x < 10: print("x is less than 10. ") else: print("x is greater than or equal to 10") x = 2 if x <= 10: print("x is less than or equal to 10.") elif x <= 25: print("x is greater than 10, but less than or equal to 25.") else: print("x is greater than 25.")
true
dfe2bf39b174f776f2cf7ac5f6f2422716cdb2a8
swapnil-sat/helloword
/Python List_14-3-21.py
2,918
4.5625
5
# ====================================================================================|| # || Python Lists || # || || # || || # ||==================================================================================|| # mylist=["apple","banana","cherry"] # >>List<<<< # it is used to store multipale items in a single variable . # list are one of 4 built-in -data types in pyhton used to store clooecction of data ,the other 3 are Tuple,Set and Dictionary # all with different qualities and uses. # E.x # Create a list # thislist=["apple","banana","cherry"] # print(thislist) # >>>>>List Items<<<<<< # List items are ordered,changebale and allow duplicate values. # List items are indexed,the first item has index[0] the second item has index[1] etc. # >>>Ordered<<<<< # the items have a defined order,annd that order will not change . # if you add new items to a list ,the new items will be placed at the end of the list. # >>>>>>>there are some list methods thhat will change the order ,but in general the order of the items will not change # >>Changeable<<<<< # We can change ,add,and remomve items in a list after it has been created. # >>>Allow Duplicates<<< # lists are indexed ,list can have items with the same value. # E.x # thislist=["apple","banana","Cherry","apple","banana"] # print(thislist) # >>>>List Length<<<<< # to determine how many items a list has use the len() function. # E.x # thislist=["apple","banana","Cherry"] # print(len(thislist)) # >>>>>>List Items -Data types. # E.x # string,int and boolean data type # list1=["Apple","Mango","Banana","Cherry"] # list2=[1,2,3,4,5] # list3=[True,False,False] # print(list1) # print(list2) # print(list3) # A list can contain different data types: # E.x # A list with strings integers and boolean values: # list1=["abc",34,True,40,"Swapnil"] # print(list1) # >>>>type<<<<< # from python's perspective ,lists are definde as objets with the data type 'list' # <class 'list>' # E.x # list1=["Apple","Mango","Banana","Cherry"] # print(type(list1)) # >>>>The list() Constructor. # it is also possible to use the list() constructor when creating a new list . # E.x # thislist=list (("Apple","Mango","Banana","Cherry")) # print(thislist) # >>>>Python collection (Arrays) # there are four collection data types in the Python programming language. # List- it is collection which is ordered and changabel .allows duplicate members. # Tuple-it is collection which is ordered and unchageable allows duplicate members. # Set-it is collection which is unordered and unindexed .No duplicate members. # Dictionary-it is a collection which is unordered and changablle .No duplicate members. # ******
true
66d3eb4004caf3487e69ed3847050bcfc6a0ba2a
swapnil-sat/helloword
/Python Numbers_12-3-21.py
2,540
4.625
5
# ====================================================================================|| # || Python Numbers || # || || # || || # ||==================================================================================|| # >Python Numbers # >there are three numaric types in python # 1.int # 2.float # 3.complex # variables of numeric types are created when you assign a value of them # E.g # x=1 int # y=2.8 float # z=1j complex # to verify the type of any object in python use the type() function. # example #.print(type(x)) #.print(type(y)) #.print(type(z)) # >>>>>int<<<<<<<< # int or integer is a whole number positive or negative without decimals of unlimited length. # E.g # integers # x=323432423432423432423423432432 # z=-3332324324324 # print(type(x)) # print(type(y)) # >>>>>>Float<<<<<<<< # float or floating point number is a number ,positive or negative containing one or more decimals # E.g # x=1.10 # y=1.0 # z=-23213213.323123 # print(type(x)) # print(type(y)) # print(type(z)) # float can also be scientific numbers with an "e" to indicate the power of 10. # x=35e3 # y=12E4 # z=-87.7e100 # print(type(x)) # print(type(y)) # print(type(z)) # >>>>>>>>Complex<<<<<<<<<< # Complex numbers are written with a "j" as imaginary part. # E.g # x=3+5j # y=5j # z=-5j # print(type(x)) # print(type(y)) # print(type(z)) # _____________________________________________________________________________________________________________________ # Type conversion . # you can convert from one type to another with the int(),float()and complex()method. # E.g # Convert from one type to another # x=1 # y=2.8 # z=1j # convert from int to float # a=float(x) # convert from float to int # b=int(y) # convert from int to complex # c=complex(x) # print(a) # print(b) # print(c) # print(type(a)) # print(type(b)) # print(type(c)) # ______________________________________________________________________________________________________________________ # >>>>>>Random Number<<<<<<<<<< # python does not have a random() function to make a random number,but python has a built -in module called random that can be used to make random numbers. # E.g # import random module and display a random number between 1 and 9: # import random # print(random.randrange(1,10)) # *****
false
7005c1e509183b181be469ab85b6c370731dfec3
swapnil-sat/helloword
/PYHTON-UPDATE TUPLE_17-3-21.py
1,961
4.78125
5
# ====================================================================================|| # || Python- Update tuples || # || || # || || # ||==================================================================================|| # tuples are unchangable meaning that you cannt change,add or remove items once the tuple created. # but there are some workrounds. # >>>>Change a tuplevalue # once a tuple is created,you cant change its value tuples are unchangable or immutable as it also is called but there is a #workround ,you can converted tuple into list,change the list and converted the list back into a tuple. # E.x # convert the tuple into a list to be able to change it: # x=("apple","banana","cherry") # y=list(x) # y[1]="kiwi" # x=tuple(y) # print(type(x),x) # Add Items << # once a tuple created ,you cannot add items to it. # E.x # you cannt add items to a tuple. # thistuple=("apple","banana","cherry") # thistuple.append("orange") this will raise an error # print(thistuple) # >>>just like the workaround for changing a tuple you can convert it into a list ,add your item(s),and convert it back into a tuple. # E.x # convert the tuple into a list add "orange"and convert it back in to a tuple. # thistuple=("apple","banana","cherry") # y=list(thistuple) # y.append("orange") # thistuple=tuple(y) # print(thistuple) # Remove items # Note-you cannot remove items in a tuple. # E.x # thistuple=("apple","banana","cherry") # y=list(thistuple) # y.remove("apple") # thistuple=tuple(y) # print(thistuple) # or you can delete the tuple completely. # E.x # the del keyword can delet the tuple completely. # thistuple=("apple","banana","cherry") # del.thistuple this will raise an error because the tuple no longer exist. # print(thistuple)
true
4d97bac3e6ba6505859a03cc488d7bb2cb6e2e82
iigorazevedo/Desafios
/Mundo02/desafio042.py
582
4.125
4
from time import sleep r1 = int(input('Digite o valor da primeira reta: ')) r2 = int(input('Digite o valor da segunda reta: ')) r3 = int(input('Digite o valor da terceira reta: ')) print('-'*40) print('Analisando...') sleep(1) if r1 == r2 == r3: print('O triângulo é equilátero!') elif r1 == r2 or r1 == r3 or r2 == r3: print(' O triângulo é isósceles!') else: print('o triângulo é escaleno.') if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('As retas acima podem formar um triângulo!') else: print('As retas não podem formar um triângulo!')
false
bf41dfc536b11ab13b16eb411256344d2e3f1b40
SnehalSutar9823/PythonAssignments-Marvellous
/Assignment6_1.py
493
4.15625
4
def PositiveOrNegative(NO): if NO>0: return "TRUE" elif NO==0: return "ZERO" else: return "FALSE" def main(): num=int(input("Enter number")) ans=PositiveOrNegative(num) if ans=="TRUE": print("{} is Positive Number".format(num)) elif ans=="ZERO": print("{} is ZERO".format(num)) else: print("{} is Negative Number".format(num)) if __name__=="__main__": main()
false
eee13c8bae4d1a495c80549e0fdcfdf1dd6bd0af
eryilmazysf/assignments-
/ders2.py
1,048
4.1875
4
a=10 b=2 print(a/b) #tek bölme işareti float deger döndürüyor print(a//b) #iki bölme işareti int deger döndürüyor print(a%b) #yüzde işareti kalan ifadeyi gösteriyor print(a**b) #iki yıldız üzeri demek c="YUSUF try to learn python" print(c[0]) #köşeli parantez içindeki deger string ifadenin sembolünü yazdırır Y print(c[6:9]) #aralık değeri string yazdırır try print(c[5:]) #sonrakileri yazdırıyor print(c[:6]) #öncekileri yazdırıyor print(c[::2]) #ikişer atlama yapıyor # konunun özeti = [baslama:bitiş:atlama] print(c[-1]) print(len(c)) #len içine yazılan string boyutunu ifade etmektedir k="java" m="python" print(k+m) #string ifadelerde math işlemleri yapabiliriz print(k*3) x=5 y=45.4 z="500" print(y) print(int(y)) #float değeri int degere dönüştürebiliyoruz print(float(x)) print(z*3) print(int(z)*3) f=32 f=str(f) #int degeri string ifade cevirme print(len(f)) #degerimiz string cevirdigimizden uzunlugunu hesaplayabiliyoruz
false
c8448d233f737831366635ce1250748f73103822
eryilmazysf/assignments-
/dice.py
860
4.15625
4
import random print(""" ************************* DİCE SİMULATİON ************************* do not forget dice number between 1 and 8 """) x=int(input("how many dice you will use:")) while (x<1 or x>8): #for control whether valid or not print("not valid value try again") x = int(input("how many dice you will use:")) y=int(input("number of rolls:")) while (y<0): #for control whether valid or not print("not valid try again:") y = int(input("number of rolls:")) total_list=[] for m in range(1,y+1):#for counting total = 0 for n in range(1,x+1): random_number= random.randint(1,6) # for appearance number we make random number print(n,".diece: ",random_number) total+=random_number total_list.append(total) print(m,".total",total) print(total_list)
true
3e8c6528c3a7c093f3515e22c6c8c7a089b169c5
py1-10-2017/PYTHON_PROJECTS
/scores_grades.py
774
4.21875
4
'''Write a function that generates ten scores between 60 and 100. Each time a score is generated, your function should display what the grade is for a particular score. Here is the grade table: Score: 60 - 69; Grade - D Score: 70 - 79; Grade - C Score: 80 - 89; Grade - B Score: 90 - 100; Grade - A''' import random def final_grade(num): grade = "" for i in range(num): score = random.randint(60,100) if score >= 60 and score < 70: grade = "D" elif score >= 70 and score < 80: grade = "C" elif score >= 80 and score < 90: grade = "B" elif score >= 90: grade = "A" print grade print "Score: "+ str(score) + "; Your grade is " + grade final_grade(10)
true
172089abe7cdb216365597d7c1db151cc79fedcd
py1-10-2017/PYTHON_PROJECTS
/finding_chars.py
443
4.34375
4
# Write a program that takes a list of strings # and a string containing a single character, and # prints a new list of all the strings containing # that character. def find_char_words(char, list): char_words = [] for word in list: if char in word: char_words.append(word) print char_words word_list = ['hello','world','my','name','is','Anna'] char = 'o' find_char_words(char, word_list)
true
246348e97c8bad6fa5d9e4ce9ba9615e235fd93b
Environmental-Informatics/building-more-complex-programs-with-python-ekong44
/kong4_program_7.1.py
822
4.375
4
"""" Eric Kong 1/23/2020 Chapter 7 Exercise 7.1 """ # importing math library so that math.sqrt() function can be used import math # copied loop from section 7.5 of the book def mysqrt(a): epsilon = 0.001 x = a/2 # initial estimate while True: # infinite loop y = (x + a/x) / 2 # Newton's method if abs(y-x) < epsilon: return y break # break the loop x = y # a function that prints a table for numbers 1 to 10 def test_square_root(): print("a mysqrt(a) math.sqrt(a) |Difference|") print("- --------- ------------ ------------") for a in range(1, 10): print("%.1f %.9f %.9f %.9f" % (a,mysqrt(a), math.sqrt(a), abs(mysqrt(a)-math.sqrt(a)))) # call the function so it runs test_square_root()
true
1c8e33514736dd6506736336c13f64752ccb3510
Redoxfox/python_algoritmos
/ejemplos/bluces.py
2,256
4.25
4
"""2.2.5. Estructuras de control iterativasEste bucle, se encarga de ejecutar una misma acción "mientras que" una determinada condición se cumpla. Ejemplo: Mientras que año sea menor o igual a 2012, imprimir la frase "Informes del Año año".""" # -*- coding: utf-8 -*- anio = 2001 while anio <= 2012: print ("Informes del Año", str(anio)) anio += 1 """Podrás notar que en cada iteración, incrementamos el valor de la variable que condiciona el bucle (anio). Si no lo hiciéramos, esta variable siempre sería igual a 2001 y el bucle se ejecutaría de forma infinita, ya que la condición (anio <= 2012) siempre se estaría cumpliendo.Pero ¿Qué sucede si el valor que condiciona la iteración no es numérico y no puede incrementarse? En ese caso, podremos utilizar una estructura de control condicional, anidada dentro del bucle, y frenar la ejecución cuando el condicional deje de cumplirse, con la palabra clave reservada break:""" while True: nombre = input("Indique su nombre: ") if nombre: break """El bucle anterior, incluye un condicional anidado que verifica si la variable nombre es verdadera (solo será verdadera si el usuario tipea un texto en pantalla cuando el nombre le es solicitado). Si es verdadera, el bucle para (break). Sino, seguirá ejecutándose hasta que el usuario, ingrese un texto en pantalla. 2.2.5.2. Bucle for El bucle for, en Python, es aquel que nos permitirá iterar sobre una variable compleja, del tipo lista o tupla: 1) Por cada nombre en mi_lista, imprimir nombre""" mi_lista = ['Juan', 'Antonio', 'Pedro', 'Herminio'] for nombre in mi_lista: print (nombre) # 2) Por cada color en mi_tupla, imprimir color: mi_tupla = ('rosa', 'verde', 'celeste', 'amarillo') for color in mi_tupla: print (color) """En los ejemplos anteriores, nombre y color, son dos variables declaradas en tiempo de ejecución (es decir, se declaran dinámicamente durante el bucle), asumiendo como valor, el de cada elemento de la lista (o tupla) en cada iteración. Otra forma de iterar con el bucle for, puede emular a while: 3) Por cada año en el rango 2001 a 2013, imprimir la frase "Informes del Año año":""" for anio in range(2001, 2013): print ("Informes del Año", str(anio))
false
98c8c59ee3da63166c469cef0b8f1d6bcb410bf9
SwathiChennamaneni/repo1
/Assignments/Assignment_4.py
350
4.25
4
#4. take a number from the user and check whether it is prime num = input("Enter Number:") if num > 1: for i in range(2,num): if (num % i) == 0: print "{0} is not a prime number".format(num) break else: print "{0} is a prime number".format(num) else: print "{0} is not a prime number".format(num)
true
1df5cfbb5f127db214410283f9ccdd32674465ab
SwathiChennamaneni/repo1
/Assignments/Assignment_9.py
616
4.625
5
#9. take a string from the user and check contains only small letters or not import re # Considering the scenario for only small letters without digits user_string = raw_input("Enter String:") print "Without Regular Expressions" for i in user_string: if not i.islower(): flag = 0 break else: flag = 1 if flag == 1: print "\nString contains only Small letters" else: print "\nNot a Small Only String" user_string1= raw_input("Enter String:") res = re.match('[a-z].', user_string) if res: print "\nContains only Small letters" else: print "\nNot a Small letter Only String"
true
66588c5fe8d43308221d430049071e657bc86504
SwathiChennamaneni/repo1
/Assignments/Assignment_80.py
304
4.125
4
#80 WAP to remove perticular element from a given list for all occurancers list1 = [1,2,2,3,3,4,3,5,6,6,3,3] print "Available List:",list1 n = raw_input("Enter an element to remove all occurences of it:") list2 = [] for i in list1: if i !=int(n): list2.append(i) print "Update List:",list2
true
7e268442adad880bb011aa62276010289b583628
SwathiChennamaneni/repo1
/Assignments/Assignment_75/Method_Types.py
872
4.46875
4
""" 75. implement class method and instance method and static method in a class with an example. Create a instance and call all the methods.""" import math class Calculation(object): def __init__(self, radius, height): self.radius = radius self.height = height @staticmethod def compute_area(radius): return math.pi *(radius ** 2) @classmethod def compute_volume(cls, height, radius): return height * cls.compute_area(radius) def get_volume(self): return self.compute_volume(self.height, self.radius) c = Calculation(2,3) #Static Method print "**Static Method**" print Calculation.compute_area(2) print c.compute_area(2) #Class Method print "\n**Class Method**" print Calculation.compute_volume(3,4) print c.compute_volume(3,4) # Instance Method print "\n**Instance Method**" print c.get_volume()
true
21d589ad139e45e6ac43533247f223f0f79c2c80
SwathiChennamaneni/repo1
/Assignments/Assignment_5.py
298
4.40625
4
#5. take a string from the user and check contains only digits or not user_string = raw_input("Enter String:") for i in user_string: if not i.isdigit(): flag = 0 else: flag = 1 if flag == 1: print "String contains only digits" else: print "Not a Digit only string"
true
2890c14d7b2a5cac2172af90a3e955bc56af7871
sonmezbaris/python-exercises
/simple_calculator.py
657
4.15625
4
def get_number(): number=int(input("Please enter a number: ")) return number def get_operator(): operator=input("Do you want to sum/multiply: ") return operator def should_continue(): decision=input("Do you want to continue yes/no: ") return decision decision="yes" sum=0 multiply=1 while decision=="yes": number=get_number() operator=get_operator() if operator=="sum": sum=sum+number elif operator=="multiply": multiply=multiply*number else: print("operator ",operator," not supported ") decision=should_continue() print("sum=",sum,"multiply",multiply)
true
b16cbab26e4c62c1b2455a8649fd2424976e5808
Akki-Developer/Akki-Developer
/star.py
2,308
4.25
4
def triangle(n): # number of spaces k = n # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") # Driver Code n = 5 triangle(n) def pypart(n): # outer loop to handle number of rows # n in this case for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ",end="") # ending line after each row print("\r") # Driver Code n = 5 pypart(n) def pattr(n): k=2*n-2 for i in range(0,n): for j in range(0,k): print(end=" ") k=k-2 for j in range(0,i+1): print("* ", end="") print("\r") pattr(5) #star def pattr(n): k=n for i in range(0,n): for j in range(0,k): print(end=" ") k=k-1 for j in range(0,i+1): print("* ", end="") print("\r") pattr(5) def pypart2(n): # number of spaces k = 2*n - 2 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 2 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") # Driver Code n = 5 pypart2(n)
true
651e3c3b56a1fb5eae6131f54ea3671fd19ae6d9
SB1996/Python
/Object Otiented/Class & Object/ClassMembers.py
1,730
4.5625
5
# Changing Class Members in Python ...! # we have seen that Python doesn’t have static keyword. All variables that are assigned # a value in class declaration are class variables. # We should be careful when changing value of class variable. # If we try to change class variable using object, a new instance (or non-static) variable for that particular # object is created and this variable shadows the class variables. class Student: Stream = "Information Technology" # Class Variable... # Constructor ... def __init__(self, name, id): self.Name = name self.Id = id obj00 = Student("Santanu Banik", "IT007") obj01 = Student("Atanu Banik", "CSE003") # Before Changing Class Variable.......... print("Before Changing Class Variable...") print(f"obj00.Stream : {obj00.Stream}") print(f"obj01.Stream : {obj01.Stream}") # print("####_id_####") # print(f"id of (obj00.Stream) : {id(obj00.Stream)} ") # print(f"id of (obj01.Stream) : {id(obj01.Stream)} ") # print(f"id of (Student.Stream) : {id(Student.Stream)} ") # print("####_id_####") print("___________________________________________") # After Changing Class Variable.......... # It change only for 'obj00' object and for other object it's still unchanged obj00.Stream = "Computer Science & Engineering" # It's a new instance variable with same name print("After Changing Class Variable...") print(f"obj00.Stream : {obj00.Stream}") print(f"obj01.Stream : {obj01.Stream}") # Access by class name print(f"Student.Stream : {Student.Stream}") # print("####_id_####") # print(f"id of (obj00.Stream) : {id(obj00.Stream)} ") # print(f"id of (obj01.Stream) : {id(obj01.Stream)} ") # print(f"id of (Student.Stream) : {id(Student.Stream)} ") # print("####_id_####")
true
2c122354a91f3ed7d0c2fa07154546e41845eebf
SB1996/Python
/Function/FunctionDecorator.py
832
4.40625
4
# Function Decorator in Python. # A decorator is a function that takes a function as its only parameter and returns a function. # This is helpful to “wrap” functionality with the same code over and over again # For example, below code can be re-written as following. # Adds a welcome message to the string returned by callback(). # Takes callback() as parameter and returns welcome(). def decorateMessage(callback): # Nested function ... def welcomeMassage(_massage): return "Welcome in " + callback(_massage) # Decorator returns a function return welcomeMassage @decorateMessage def showMassage(_massage): return _massage; # Driver code # This call is equivalent to call to decorateMessage() with function # showMassage("GeeksforGeeks") as parameter print(showMassage("Python Language"))
true
7a5c734db735069ec9dc2138fd1816744f95797b
SB1996/Python
/Object Otiented/Constructors/Constructors.py
1,292
4.5625
5
# Constructors in Python ...! # # Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) # to the data members of the class when an object of class is created.In Python the __init__() method is called # the constructor and is always called when an object is created. # Types of constructors : 1. default constructor : The default constructor is simple constructor which doesn’t accept # any arguments.It’s definition has only one argument which is a reference to the instance # being constructed. # # 2. parameterized constructor : constructor with parameters is known as parameterized # constructor. The parameterized constructor take its first argument as a reference # to the instance being constructed known as self and the rest of the arguments are # provided by the programmer. class Details: Name = "Banti" # Constructors (parameterized constructor)... def __init__(self, name): print("Constructor call ....") print(f"Name : {self.Name}") self.Name = name print(f"Name : {self.Name}") obj = Details("Santanu")
true
17aa108c7056dd40404935d6dfb11862b64ee7a0
SB1996/Python
/Operaters/LogicalOperators.py
368
4.34375
4
# 3. Logical operators: Logical operators perform Logical AND, Logical OR and Logical NOT operations. data00 = True data01 = False # and Operator ...! print(f"AND Operatot[data00 and data01] : {data00 and data01}") # or Operator ...! print(f"OR Operatot[data00 or data01] : {data00 or data01}") # not Operator ...! print(f"NOT Operatot[not data01] : {not data01}")
true
5a9e019869e192d18e66738ae652f4b7c881184c
SB1996/Python
/Function/ClosuresFunction.py
967
4.25
4
# Closures in Python ...! # A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory. # A closure : unlike a plain function allows the function to access those captured variables through # the closure’s copies of their values or references, even when the function is invoked outside their scope. # Python program to illustrate closures # Outer function def outerFunction(_text): print("Outer Function Call ...") text = _text print(f"Before Modify Data : {text}") # Inner function def innerFunction(_anotherText): print("Inner Function Call ...") text = _anotherText # Modify the Outer scope variable print(f"inner Function Modify Data : {text}") # print(f"After Modify Data : {text}") return innerFunction # Note we are returning function WITHOUT parenthesis myFunction = outerFunction("Hey! i'm Santanu") myFunction("Hello Mr. Santanu")
true
cf6eaad8b31dc7ec3b4213568efa629b44176c97
SB1996/Python
/Object Otiented/Polymorphism/OperatorOverloading.py
2,030
4.1875
4
# Operator Overloading in Python ...! # Behind the seen in Python # print(f"Addition : {10+20}") # # --or-- # print(f"Addition : {int.__add__(10, 20)}") # # print(f"Result : {'Santanu' + ' Banik'}") # # --or-- # print(f"Result : {str.__add__('Santanu', ' Banik')}") class OverloadOperator: def __init__(self, arg): self.Data = arg # adding two objects ... def __add__(self, other): return self.Data + other.Data obj00 = OverloadOperator(100) obj01 = OverloadOperator(200) print(obj00 + obj01) strObj00 = OverloadOperator("Santanu ") strObj01 = OverloadOperator("Banik") print(strObj00 + strObj01) ########################################## class complex: def __init__(self, arg00, arg01): self.arg00 = arg00 self.arg01 = arg01 # adding two objects ... # Overload '+' Operator def __add__(self, other): return self.arg00 + other.arg00, self.arg01 + other.arg01 def __str__(self): return self.arg00, self.arg01 object00 = complex(10, 20) object01 = complex(50, 60) result = object00 + object01 # Behind the seen....in python .... # # object00 = complex(10, 20) ==> object00.arg00 = 10 # object00.arg01 = 20 #____________________________________________________ # object01 = complex(50, 60) ==> object01.arg00 = 50 # object01.arg01 = 60 #____________________________________________________ # object00 + object01 ==> __add__(object00, object01): # return (object00.arg00 + object01.arg00, object00.arg01 + object01.arg01) # [(10 + 50), (20 + 60)] ==> (60, 80) print(f"Result : {result}") obj00 = complex("A", "B") # obj00 = complex("A", "B") ==> obj00.arg00 = "A" # obj00.arg01 = "B" obj01 = complex("Z", "Y") # obj01 = complex("Z", "Y") ==> obj01.arg00 = "Z" # obj01.arg01 = "Y" result00 = obj00 + obj01 print(f"Result : {result00}")
false
a650637468f3d55953ad068d4ffbf1e722d30260
ariawanzero/numpy_and_pandas
/thebasics_6.py
1,722
4.375
4
# Indexing, Slicing and Iterating # one dimensional array import numpy as np a = np.arange(10)**3 print "a = ", a print "a[2] = ", a[2] print "a[2:5] = ", a[2:5] a[:6:3] = -1000 # sama dengan a[0:6:2] = 1000; dari start position sampai posisi ke 6, terutama setiap element ke2 diganti dengan -10000 print "a[:6:2] = -1000 > ", a print "a [ : :-1] = ", a[ : :-1] # reverse a for i in a: print(i ** (1/3.)) # multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas: def f(x,y): return 10 * x + y b = np.fromfunction(f,(5,4),dtype=int) print "b = ", b print "b[2,3] = ", b[2,3] print "b[0:5, 1] = ", b[0:5, 1] # mengambil data pada tiap row, kolom ke dua dari b print "b[ : , 1] = ", b[ : , 1] # sama dengan contoh sebelumnya print "b[1:3, : ] = ", b[1:3, : ] # tiap kolom pada baris kedua dan ketiga dari b print "b[-1] = ", b[-1] # row terakhir sama dengan row index -1 # Ekspresi dalam tanda kurung di b [i] diperlakukan sebagai i diikuti sebanyak dari : yang diperlukan untuk mewakili axes yang tersisa. NumPy juga memungkinkan Anda untuk menulis ini menggunakan titik sebagai b [i, ...]. # Dots (...) mewakili banyak kolom yang dibutuhkan untuk menghasilkan sebuah index tuple yang lengkap # contoh jika sebuah array mempunyai 5 tingkat maka: # x[1,2,...] setara dengan x[1,2,:,:,:] # x[...,3] setara dengan x[:,:,:,:,3] dan # x[4,...,5,:] setara dengan x[4,:,:,5,:]. c = np.array([[[0, 1, 2],[10, 12, 13]], [[100, 101, 102],[110,112,113]]]) print "shape = ", c.shape print "c[1,...] = ", c[1,...] # same as c[1,:,:] or c[1] print "c[...,2] = ", c[...,2] # same as c[:,:,2] for row in b: print(row) for element in b.flat: print (element)
false
458cee6b1a9992ab16dcafd8906809bdd2ca226e
Yulionok2/Netologia
/1.Fundamentals Python/Python.Знакомство с консолью/DZ_3.py
1,058
4.15625
4
# Нужно разработать приложение для финансового планирования.Приложение учитывает, какой процент от заработной # платы уходит на ипотеку и ежемесячные расходы. Программа подсчитывает и выводит, сколько денег тратит # пользователь на ипотеку и сколько он накопит за год (остаток от заработанной платы). pay=int(input('Введите заработную плату в месяц:')) mortgage=int(input('Введите, какой процент(%) уходит на ипотеку:')) life=int(input('Введите, какой процент(%) уходит на жизнь:')) mortgage_1=pay*mortgage//100*12 life_1=pay*life//100*12 moneybox=pay*12-mortgage_1-life_1 print('Вывод:') print('На ипотеку было потрачено:', mortgage_1) print('Было накоплено:', moneybox)
false
102a37754d2bfa2293151ef6524ae817aabb4dd7
eocampo421/python
/thousandsWithCommas.py
476
4.375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- #Problema 1: #Implementar la funcion “thousands_with_commas” que toma un #integer y devuelve un string con el número con comas cada 3 dígitos. #Returns the number with commas. def thousands_with_commas(i): i =('{0:,}'.format(i)) return str(i) if __name__ == '__main__': assert thousands_with_commas(1234) == '1,234' assert thousands_with_commas(123456789) == '123,456,789' assert thousands_with_commas(12) == '12'
false
c44787144a165cb0578155ee3d5deb6cb9474c3b
renhl/learn
/class.py
2,329
4.15625
4
# class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # # def print_score(self): # print("%s:%s" % (self.name, self.score)) # # bart = Student('zhangsan', 98) # # print(bart.print_score()) #!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) print('bart.name =', bart.name) print('bart.score =', bart.score) bart.print_score() lisa.print_score() print('grade of Bart:', bart.get_grade()) print('grade of Lisa:', lisa.get_grade()) class Animal(object): def run(self): print("Animal is running") class Dog(Animal): # 当子类和父类都存在相同的run()方法时,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run() def run(self): print("dog is running") def eat(self): print("dog eating") class Cat(Animal): pass dog = Dog() cat = Cat() dog.run() dog.eat() cat.run() print(isinstance(dog,Dog)) # 判断变量dog是否为Dog类型 print(isinstance(dog,Animal)) # 因Dog()从Animal()继承下来。 def run_twice(Animal): # 多态 编写一个函数,这个函数接受一个Animal类型的变量 Animal.run() Animal.run() run_twice(Animal()) run_twice(Dog()) run_twice(Cat()) print(type(dog)) # 变量的类型 # 实例属性和类属性 class Student(object): name = "xxx" # 定义类属性 rex = Student() # 创建实例rex print(rex.name) # 打印name属性,因为实例中没有name属性,会继续查找class的name属性 print(Student.name) # 打印类的name属性 rex.name = "123" # 给实例绑定name属性 print(rex.name) # 实例的属性优先级高于类的属性 print(Student.name) # 打印类的name属性 del rex.name # 删除实例的属性 print(rex.name) # 再次调用实例属性时,未找到就会显示类的属性
false
9092947c948d52cadfe68a44571bb446e4acaff6
bakog/practicepython
/exercise_10_list_over_comprehensions.py
2,609
4.21875
4
# coding=utf-8 """ List Overlap Comprehensions Exercise 10 (and Solution) This week’s exercise is going to be revisiting an old exercise (see Exercise 5), except require the solution in a different way. Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. Write this in one line of Python using at least one list comprehension. (Hint: Remember list comprehensions from Exercise 7). The original formulation of this exercise said to write the solution using one line of Python, but a few readers pointed out that this was impossible to do without using sets that I had not yet discussed on the blog, so you can either choose to use the original directive and read about the set command in Python 3.3, or try to implement this on your own and use at least one list comprehension in the solution. Extra: Randomly generate two lists to test this Discussion Concepts for this week: List comprehensions Random numbers, continued List comprehensions We already discussed list comprehensions in Exercise 7, but they can be made much more complicated. For example: x = [1, 2, 3] y = [5, 10, 15] allproducts = [a*b for a in x for b in y] At the end of this piece of code, allproducts will contain the list [5, 10, 15, 10, 20, 30, 15, 30, 45]. So you can put multiple for loops inside the comprehension. But you can also add more complicated conditionals: x = [1, 2, 3] y = [5, 10, 15] customlist = [a*b for a in x for b in y if a*b%2 != 0] Now customlist contains [5, 15, 15, 45] because only the odd products are added to the list. In general, the list comprehension takes the form: [EXPRESSION FOR_LOOPS CONDITIONALS] as shown in the examples above. Random numbers, continued Try to use the Python random documentation to figure out how to generate a random list. As a hint look below: a = random.sample(range(100), 5) This line of code will leave a containing a list of 5 random numbers from 0 to 99. """ import random import os import sys if sys.platform=="linux": _=os.system("clear") else: _=os.system("cls") alist = [] blist = [] for i in range(random.randint(1,10)): alist.append(random.randint(0,20)) for i in range(random.randint(1,15)): blist.append(random.randint(0,20)) print(alist) print(blist) clist=set(y for y in alist if y in blist) print(sorted(clist))
true
4c53258a331122e358d1591e9847a571fdac9735
bakog/practicepython
/exercise_04_divisors.py
2,013
4.375
4
# -*- coding: utf-8 -*- """ Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.) The topics that you need for this exercise combine lists, conditionals, and user input. There is a new concept of creating lists. There is an easy way to programmatically create lists of numbers in Python. To create a list of numbers from 2 to 10, just use the following code: x = range(2, 11) Then the variable x will contain the list [2, 3, 4, 5, 6, 7, 8, 9, 10]. Note that the second number in the range() function is not included in the original list. Now that x is a list of numbers, the same for loop can be used with the list: for elem in x: print elem Will yield the result: 2 3 4 5 6 7 8 9 10 """ from timeit import default_timer as timer t1, t2, t3 = [],[], [] N=1000 szam=int(input("Adjon meg egy számot! ")) #Az adott számot osztjuk 2-vel, mert ennél csak kisebbek lehetnek az osztói, kivéve saját maga... fel=int(szam/2) #print(fel) #lista alkalmazása nélküli megoldás start1 = timer() for i in range(N): print ("-"*20) print("A szám osztói:") for x in range (1,fel+1): if szam%x==0: print(x) print(szam) end1 = timer() #print("Idő: ", end-start) #lista alkalmazásával felezve a számot start2 = timer() for i in range(N): print ("-"*20) print("A szám osztói:") lista = [x for x in range(1,fel+1) if szam%x==0] lista.append(szam) print(lista) end2 = timer() #print("Idő: ", end-start) #lista alkalmazásával start3 = timer() for i in range(N): print ("-"*20) print("A szám osztói:") lista = [x for x in range(1,szam+1) if szam%x==0] print(lista) end3 = timer() print("Idő1: ", end1-start1) print("Idő2: ", end2-start2) print("Idő3: ", end3-start3)
true
2b3c094f6aa7d0c26736f8210ddc318643b1d37f
DharanitharanG/PythonWorkspace
/fundamentals/04 Operators.py
2,039
4.53125
5
''' Python Operators Operators are used to perform operations on variables and values. Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators # Arithmetic operators + - * / % ** Exponentiation // Floor division # Assignment operators = x = 5 x = 5 += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 # Comparison operators > Greater that - True if left operand is greater than the right, x > y < Less that - True if left operand is less than the right, x < y == Equal to - True if both operands are equal, x == y != Not equal to - True if operands are not equal, x != y >= Greater than or equal to - True if left operand is greater than or equal to the right, x >= y <= Less than or equal to - True if left operand is less than or equal to the right, x <= y # Logical operators and True if both the operands are true, x and y or True if either of the operands is true, x or y not True if operand is false (complements the operand), not x # Identity operators is True if the operands are identical (refer to the same object) x is True is not True if the operands are not identical (do not refer to the same object) x is not True x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1,2,3] y3 = [1,2,3] # Output: False print(x1 is not y1) # Output: True print(x2 is y2) # Output: False print(x3 is y3) # Membership operators in True if value/variable is found in the sequence 5 in x not in True if value/variable is not found in the sequence 5 not in x x = 'Hello world' # Output: True print('H' in x) # Output: True print('hello' not in x) # Bitwise operators & Bitwise AND x& y = 0 (0000 0000) | Bitwise OR x | y = 14 (0000 1110) ~ Bitwise NOT ~x = -11 (1111 0101) ^ Bitwise XOR x ^ y = 14 (0000 1110) >> Bitwise right shift x>> 2 = 2 (0000 0010) << Bitwise left shift x<< 2 = 40 (0010 1000) '''
true
4649c4f2517ef183e1d0593febefd6fd40548727
kjiango/code-sandbox
/PythonSandbox/src/misc/three_largest_nums.py
2,355
4.375
4
""" Write a function that takes in an array of integers and returns a sorted array of the three largest integers in the input array. Note that the function should return duplicate integers if necessary; for example, it should return [10, 10, 12] for an input array of [10, 5, 9, 10, 12]. """ from utils.sorting_utils import SortingUtils from utils.number_utils import NumberUtils class ThreeLargestNums: @staticmethod def threeLargestNums(array): # isolate negatives negs, poss = NumberUtils.isolateNegatives(array) #print("negs: {}\nposs:{}".format(negs, poss)) negsSorted = ThreeLargestNums.sortNegatives(negs) #print("negsSorted:", negsSorted) possSorted = SortingUtils.countingSort(poss) array = negsSorted + possSorted return array[-3:] @staticmethod def sortNegatives(array): a = [abs(x) for x in array] sa = SortingUtils.countingSort(a) array = [] for x in sa: array.insert(0, -x) return array #all positives @staticmethod def test_threeLargestNums1(): a = [10, 5, 9, 10, 12] result = ThreeLargestNums.threeLargestNums(a) print("result: ", result) @staticmethod def test_sortNegatives(): a = [-1, -2, -3, -7, -17, -27, -18, -541, -8, -7] result = ThreeLargestNums.sortNegatives(a) print("test_sortNegatives:", result) @staticmethod def test_isolateNegatives(): a = [-1, -2, -3, -7, -17, -27, -18, -541, -8, -7, 7] result = NumberUtils.isolateNegatives(a) print("test_isolateNegatives:", result) # positives and negatives @staticmethod def test_threeLargestNums2(): a = [-1, -2, -3, -7, -17, 56,3,2,4,3,2,12,-27, -18, -541, -8, -7, 7] result = ThreeLargestNums.threeLargestNums(a) print("result: ", result) @staticmethod def test_threeLargestNums3(): a = [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7] result = ThreeLargestNums.threeLargestNums(a) print("result: ", result) if __name__ == "__main__": #ThreeLargestNums.test_isolateNegatives() #ThreeLargestNums.test_sortNegatives() #ThreeLargestNums.test_threeLargestNums2() ThreeLargestNums.test_threeLargestNums3()
true
53e94df57417975347730eda25998f205aa8de0f
juneyc/ptyhon-class1_2020
/variables.py
716
4.1875
4
myName = "june" myAge = "16" myCash = "100.50" print(myName) # string indexing- accessing a specific character in a string aNumber ="10" aName ="Toyota" aDrink = 'fanta' x = aName [0] print (x) print(aName [2]) # string slicing- getting a range character newVar ="programming" slicedChars = newVar[3:7] slicedChars = newVar[3:] slicedChars = newVar[3:] slicedChars = newVar[-4:-8] #wrong way slicedChars = newVar[-8:-4] #right way slicedChars = newVar[3:7] #same as above print(slicedChars) # string concatenate- joining two words (add two strings) str1 = "Mwai" str2 = "Kibaki" full_name = str1+ str2 print(full_name) print(str1.count(str1)) # print mwai in lowercase print(str1.lower()) print(str1.upper())
true
80415e82b97fa16242162f1f059b6d4f1c4b04bd
xubing88/python_study
/python_study/com/bing/sort.py
386
4.125
4
''' quick sort ''' def quickSqort(arr): if len(arr)<=1: return arr pivot =arr[len(arr)/2] left=[x for x in arr if x < pivot] right=[x for x in arr if x > pivot] midle=[x for x in arr if x==pivot] return quickSqort(left)+midle+quickSqort(right) if __name__ == '__main__': print quickSqort([1,2,6,3])
true
843cd7bd35ae37303f820728b350c1c164ed0d70
emilyylam18/testrepo
/ex18.py
879
4.625
5
# Functions do three things: # they name pieces of code the way variables name # strings and numbers # they take arguments the way the script takes argv # using 1 and 2, they let you make your own mini-script # or tiny command # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok that *args was pointless, just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1 #this one taks no arguments def print_none(): print "I got nothin'." print_two("Zed", "Shaw") print_two_again("Zed", "Shaw") print_one("First!") print_none() #this defines a printing command so you can type print() without # the usual print command # function = mini script
true
d96f27cfec3969306d5f2a5aaaad3a08d807996a
baruatamio0106/python_programiz_exercise
/quadratic_equation_root_finding.py
1,153
4.4375
4
""" This is a program about to finding roots of a quadratic equation. A quadratic equation like as 'ax^2 + bx + c =0' where 'a','b','c' are some arbitary constant values. The roots could be real or complex value. This program could calculate this roots""" #Taking the values of a,b,c a = float(input("Enter value of a: ")) b = float(input("Enter value of b: ")) c = float(input("Enter value of c: ")) #calculating discriminat discriminat = (b**2) - (4*a*c) #determiniing and calculating roots if discriminat == 0: print("Roots are real and equal!") x = (-b)/(2*a) print("Root will be {}".format(x)) elif discriminat > 0: print("Roots are real and unequal!") x1 = (-b+(discriminat**0.5))/(2*a) x2 = (-b-(discriminat**0.5))/(2*a) print("First root will be {}".format(x1)) print("second root will be {}".format(x2)) elif discriminat < 0: print("Roots are complex and conjugate!") x1 = (-b+(discriminat**0.5))/(2*a) x2 = (-b-(discriminat**0.5))/(2*a) print("First root will be {}".format(x1)) print("second root will be {}".format(x2)) else: print("invaild input")
true
26f413d3af69df597d613b4d8904ef084a36c8c7
geraldinnebohr/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,358
4.28125
4
#!/usr/bin/python3 """ function that divides a matrix in an integer Args: matrix and integer Return: new matrix divided """ def matrix_divided(matrix, div): """ function that divides a matrix in an integer """ if type(div) is not int and type(div) is not float: raise TypeError("div must be a number") elif div is 0: raise ZeroDivisionError("division by zero") if len(matrix) == 0 or len(matrix[0]) == 0: raise TypeError("matrix must be a matrix (list of lists)" + "of integers/floats") for x in matrix: if type(x) is not list: raise TypeError("matrix must be a matrix (list of lists)" + "of integers/floats") new_matrix = [x[:] for x in matrix] length = len(matrix[0]) for i in range(len(matrix)): if len(new_matrix[i]) is not length: raise TypeError("Each row of the matrix must have the same size") for j in range(len(matrix[i])): if type(new_matrix[i][j]) is not int and type(new_matrix[i][j]) + is not float or type(new_matrix[i][j]) is None: raise TypeError("matrix must be a matrix (list of lists)" + "of integers/floats") new_matrix[i][j] = round((matrix[i][j] / div), 2) return new_matrix
true
3b2ad434a24ef050a0e12ebf59aa98ee7771ade1
spuddie1984/Python3-Basics-Book-My-Solutions
/OOP/review_exercises_oop.py
1,998
4.59375
5
''' 1. Modify the Dog class to include a third instance attribute called coat_color , which stores the color of the dog’s coat as a string. Store your new class in a file and test it out by adding the following code at the bottom of the code: philo = Dog("Philo", 5, "brown") print(f"{philo.name}'s coat is {philo.coat_color}.") The output of your program should be the following: Philo's coat is brown. ''' class Dog: species = "Canis familiaris" def __init__(self, name, age, coat_color): self.name = name self.age = age self.coat_color = coat_color # Instance method def description(self): return f"{self.name} is {self.age} years old" # Another instance method def speak(self, sound): return f"{self.name} says {sound}" philo = Dog("Philo", 5, "brown") print(f"{philo.name}'s coat is {philo.coat_color}.") ''' 2. Create a Car class with two instance attributes: .color , which stores the name of the car’s color as a string, and .mileage , which stores the number of miles on the car as an integer. Then instantiate two Car objects—a blue car with 20,000 miles and a red car with 30,000 miles—and print out their colors and mileage. Your output should look like this: The blue car has 20,000 miles. The red car has 30,000 miles. 3. Modify the Car class with an instance method called .drive() , which takes a number as an argument and adds that number to the .mileage attribute. Test that your solution works by instantiat- ing a car with 0 miles, then call .drive(100) and print the .mileage attribute to check that it is set to 100 . ''' class Car(object): def __init__(self, color, mileage): self.color = color self.mileage = mileage def drive(self,add_miles): self.mileage += add_miles red_car = Car('blue', 20_000) blue_car = Car('red', 30_000) blue_car.drive(100) for car in (red_car,blue_car): print(f'The {car.color} car has {car.mileage:,} miles.')
true
580b924f8a532d849a7282e9958297ab46005f2e
spuddie1984/Python3-Basics-Book-My-Solutions
/File input and output/review_exercises_csv.py
1,809
4.28125
4
import csv import pathlib ''' 1. Write a program that writes the following list of lists to a file in your home directory called numbers.csv: ''' numbers = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], ] file_path = pathlib.Path.home() / 'numbers.csv' with file_path.open(mode="w", encoding="utf-8", newline="") as file: writer = csv.writer(file) for number in numbers: writer.writerow(number) ''' 2. Write a program that reads the numbers in the numbers.csv file from exercise 1 into a list of lists of integers called numbers. Print the list of lists. Your output should look like this: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] ''' list_of_lists = [] with file_path.open(mode="r", encoding="utf-8", newline="") as file: reader = csv.reader(file) for row in reader: list_of_lists.append([value for value in row]) print(list_of_lists) ''' 3. Write a program that writes the following list of dictionaries to a file in your home directory called favorite_colors.csv: favorite_colors = [ {"name": "Joe", "favorite_color": "blue"}, {"name": "Anne", "favorite_color": "green"}, {"name": "Bailey", "favorite_color": "red"}, ] The output CSV file should have the following format: name,favorite color Joe,blue Anne,green Bailey,red ''' fav_col_file_path = pathlib.Path.home() / 'favourite_colors.csv' with fav_col_file_path.open(mode="w", encoding="utf-8", newline="") as file: pass ''' 4. Write a program that reads the data from the favorite_colors.csv file from exercise 3 into a list of dictionaries called favorite_colors. Print the list of dictionaries. The output should look something like this: [{"name": "Joe", "favorite_color": "blue"}, {"name": "Anne", "favorite_color": "green"}, {"name": "Bailey", "favorite_color": "red"}] '''
true
6f94c8f5a51051090e5471f03bacd611b7955943
spuddie1984/Python3-Basics-Book-My-Solutions
/OOP/challenge_model_a_farm.py
1,781
4.25
4
''' Before you write any code, grab a pen and paper and sketch out a model of your farm, identifying classes, attributes, and methods. Think about inheritance. How can you prevent code duplication? Take the time to work through as many iterations as you feel are necessary. The actual requirements are open to interpretation, but try to adhere to these guidelines: 1. You should have at least four classes: the parent Animal class and at least three child animal classes that inherit from Animal . 2. Each class should have a few attributes and at least one method that models some behavior appropriate for a specific animal or all animals—walking, running, eating, sleeping, and so on. 3. Keep it simple. Utilize inheritance. Make sure you output details about the animals and their behaviors. ''' class Animal(object): def __init__(self,name, feet_type): self.name = name self.feet_type = feet_type def __str__(self): return f"I'm {self.name} and I have {self.feet_type}s!" def speak(self, sound): return f'{self.name} says {sound}' def sleep(self, where): return f'{self.name} likes to sleep in the {where}' class Dog(Animal): def speak(sound="Woof"): return super().speak(sound) def sleep(self,where="Kennel"): return super().sleep(where) class Pig(Animal): def speak(self,sound="Oink"): return super().speak(sound) def sleep(self,where="Barn"): return super().sleep(where) class Sheep(Animal): def speak(self,sound="Bleat"): return super().speak(sound) def sleep(self,where="Paddock"): return super().sleep(where) joey = Dog('Joey','Paw') peppy = Pig('Peppy','Hoof') bashful = Sheep('Bashful','Hoof') print(joey.sleep()) print(joey)
true
e4ab7556524cc56d7abaab46a89145c986f46ad4
cocoon333/leetcode
/639_decode_ways_2.py
2,492
4.25
4
""" A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent. Given a string s containing digits and the '*' character, return the number of ways to decode it. Since the answer may be very large, return it modulo 109 + 7. """ class Solution: def numDecodings(self, s): if not s: return 0 dp = [] dp.append(1) dp.append(self.oneDecoding(s[0])) for i in range(2, len(s)+1): single = self.oneDecoding(s[i-1]) * dp[i-1] double = self.twoDecoding(s[i-1], s[i-2]) * dp[i-2] dp.append((single + double) % (10 ** 9 + 7)) print(dp) return dp[-1] def oneDecoding(self, curr): if (curr == "*"): return 9 if (curr == "0"): return 0 return 1 def twoDecoding(self, curr, prev): if (prev == "*"): if (curr == "*"): return 15 elif (int(curr) > 6): return 1 return 2 elif (prev == "1"): if (curr == "*"): return 9 return 1 elif (prev == "2"): if (curr == "*"): return 6 return int(int(curr) <= 6) else: return 0 if (__name__ == "__main__"): S = Solution() assert(S.numDecodings('11106') == 2) assert(S.numDecodings('2839') == 1) assert(S.numDecodings('1*') == 18) assert(S.numDecodings('*') == 9) assert(S.numDecodings('2*') == 15) assert(S.numDecodings('11111') == 8) assert(S.numDecodings('1*09') == 2) assert(S.numDecodings('*9') == 10) print(S.numDecodings('1*9'))
true
8638a9a93e21eed13b1af255847e9bc38de61867
cocoon333/leetcode
/3_solution.py
1,448
4.125
4
""" 3. Longest Substring Without Repeating Characters Medium Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class Solution: def lengthOfLongestSubstring(self, s): count = 0 max_count = 0 current_substring = {} i = 0 while i < len(s): if s[i] in current_substring: i = current_substring[s[i]]+1 if i >= len(s): break current_substring = {s[i]:i} if count > max_count: max_count = count count = 1 else: current_substring[s[i]] = i count += 1 i += 1 return max(count, max_count) if __name__ == "__main__": s = Solution() assert(s.lengthOfLongestSubstring("dvdf") == 3) assert(s.lengthOfLongestSubstring(" ") == 1) assert(s.lengthOfLongestSubstring("abcabcbb") == 3) assert(s.lengthOfLongestSubstring("bbbbb") == 1) assert(s.lengthOfLongestSubstring("pwwkew") == 3)
true
3418f337fbc92ba26d2d670597b244f9cb5d1198
Mguysin/PythonProjects
/Week 2/For loops and dictionaries/while loop 1.py
735
4.1875
4
cars=['Ferrari', 'Fiat Panda', 'Fiat Panda 4*4', 'Skoda Felicia Fun'] max_size_list=len(cars) counter=-1 number=-1 while counter<max_size_list -1: counter=-1 number=1 while counter < max_size_list -1: counter +=1 print(str(number) + ' ~ ' + cars[counter]) number+=1 while True: user_input = input("Please input a value") if user_input == 'exit': break elif user_input=='cute': print('jigglypuff...<3') else: print('JIGGLYPUUUFFF') #keep asking for user input #break if user types in exit #Pseudo Code # We have a list of cars # Its in a variable called cars # I can access using the index # Let's start by printing each car using the index
true
eca4935a6e50b3a140e73b7b03df0974a04609d5
Mguysin/PythonProjects
/Week 2/Booleans variables numbers/Booleans.py
508
4.21875
4
# #Booleans are true or fasle # print(True) # print(False) # print(True ==False) #Logical NOT Equal print(True != False) #Logical And and Or operators #Logical AND --> Checks the two sides and for it to be true both sides have to be true print("Logical and") print(True and False) print(False==False) and (False==False) #Logical OR --> Checks the two sides and for it to be true one side has to be true print("Logical or") print(True or False) print(False==False) or (False==False) # print(True)
true
627bd3deddcd9e61fe1ea2af1d192af60fbcab46
ethanlow23/codingDojoCoursework
/01_Python/00_python_fund/multiplesSumAvg.py
745
4.25
4
# Multiples Part I for num in range(1, 1001): # for loop in range 1 to 1001 if num % 2 != 0: # checking if the num is odd print num # print num if it is odd ''' # Multiples Part II for num in range(5, 1000001): # for loop in range 5 to 1000001 if num % 5 == 0: # checking if num is a multiple of 5 print num # print num if it is a multiple of 5 # Sum List a = [1, 2, 5, 10, 255, 3] sum = 0 # create variable sum and set it to zero for num in a: # for loop going through array a sum += num # add the num to sum print sum # print the total sum after the loop # Average List avg = sum / len(a) # using the codes in sum list and making the average equal to the sum divided by the length of a print avg # print the average of the array a '''
true
4a82454ce67dca380a16a7d9fef9be186fe8d34a
cacad101/assignment-neural-network-1
/problem_2_regression/q1.py
2,468
4.21875
4
# -*- coding: utf-8 -*- ''' Question 1: Design a 3-layer feedforward neural network consisting of a hidden-layer of 30 neurons. Use mini-batch gradient descent (with batch size of 32 and learning rate alpha = 10e−4) to train the network. Use up to about 1000 epochs for this problem. a) Plot the training error against number of epochs for the 3-layer network. b) Plot the final test errors of prediction by the network. ''' import numpy as np from housing_preprocessing.preprocess import Preprocessor from housing_training.approximation import Approximation from housing_visualization.visualization import plot_graph def main(): print("Start Question 1") np.random.seed(10) k_fold = 5 hidden_neurons = [30] batch_size = 32 learning_rate = 1e-4 epochs = 1000 data_dir = "housing_data/cal_housing.data" # Preprocessing: Load data preprocessor = Preprocessor() preprocessor.load_data(data_dir) preprocessor.divide_data(3, 7) preprocessor.normalize_data() nn = Approximation() if k_fold > 0: list_train_cost, list_test_cost, list_test_accuracy, min_err = nn.select_model( train_x = preprocessor.train_x, train_y = preprocessor.train_y, k_fold = k_fold, epochs = epochs, batch_size = batch_size, hidden_neurons = hidden_neurons, learning_rate = learning_rate ) # TODO: # Plot K-fold graphs else: nn.set_x_train(preprocessor.train_x) nn.set_y_train(preprocessor.train_y) nn.set_x_test(preprocessor.test_x) nn.set_y_test(preprocessor.test_y) nn.create_model(hidden_neurons, learning_rate) train_cost, test_cost, accuracy, min_err = nn.train_model(epochs=epochs, batch_size=batch_size, verbose=True) # Plot training error against number of epoch # Plot test error of prediction against number of epoch plot_graph( title='Training and Test Errors at Alpha = %.3f'%learning_rate, x_label="Epochs", y_label="MSE", x_val=range(epochs), y_vals=[train_cost, test_cost], data_labels=["train", "test"], ) # Plot accuracy against number of epoch plot_graph( title="Test Accuracy", x_label="Epochs", y_label="Accuracy", x_val=range(epochs), y_vals=[accuracy], data_labels=["Test Accuracy"], ) if __name__ == '__main__': main()
true