blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
046bd214c938e63595f3d9fdeed82ecf1327b6b7
ayushtiwari7112001/Rolling-_dice
/Dice_Roll_Simulator.py
640
4.4375
4
#importing modual import random #range of the values of dice min_val = 1 max_val = 6 #to loop the rolling through user input roll_again = "yes" #loop while roll_again == "yes" or roll_again == "y": print("Roll the dices...") print("** The values are **") #generating and printing 1st random integer from 1 to 6 print(random.randint(min_val,max_val)) #generating and printing 2nd random integer from 1 to 6 print(random.randint(min_val, max_val)) #asking user to roll the dice again. Any input other than yes or y will terminate the loop roll_again=input("Roll the dices again (yes/no) or (y/n) ")
true
93278240e775bbba67da1572331d7a1d3cb279db
YeomeoR/codewars-python
/sum_of_cubes.py
656
4.25
4
# Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum. # Assume that the input n will always be a positive integer. # Examples: # sum_cubes(2) # > 9 # # sum of the cubes of 1 and 2 is 1 + 8 ### from cs50 video python, lecture 2 # def sum_cubes(n): # cubed = [] # i = 1 # while (i <= n): # cubed.append(i**3) # i+=1 # print(sum(cubed)) def sum_cubes(n): return sum(i**3 for i in range(0,n+1)) print(sum_cubes(1), 1) print(sum_cubes(2), 9) print(sum_cubes(3), 36) print(sum_cubes(4), 100) print(sum_cubes(10), 3025) print(sum_cubes(123), 58155876)
true
4f481dd9a6205e9979b2f9f17103dd3816a226ab
YeomeoR/codewars-python
/count_by_step.py
827
4.21875
4
# Implement a function named generateRange(min, max, step), which takes three arguments and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step. (min < max) # def generate_range(min, max, step): # listed = [] # rangey = range(min,max +1,step) # for n in rangey: # listed.append(n) # return listed def generate_range(min, max, step): return list(range(min, max + 1, step)) print(generate_range(1, 10, 1), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(generate_range(-10, 1, 1), [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]) # print(generate_range(1, 15, 20), [1]) # print(generate_range(1, 7, 2), [1, 3, 5, 7]) # print(generate_range(0, 20, 3), [0, 3, 6, 9, 12, 15, 18])
true
3d40b4229c78f200c882547349bf5ad433a87908
goruma/CTI110
/P2HW1_PoundsKilograms_AdrianGorum.py
586
4.40625
4
# Program converts pounds value to kilograms for users. # 2-12-2019 # CTI-110 P2HW1 - Pounds to Kilograms Converter # Adrian Gorum # #Pseudocode #input pound amount > calculate pound amount divided by 2.2046 > display #conversion in kilograms #Get user input for pound amount. poundAmount = float(input('Enter the pound amount to be converted: ')) #Calculate the kilogram amount as pound amount / 2.2046. kilogramAmount = poundAmount / 2.2046 #Display the pound amount as kilograms. print('The pound amount converted to kilograms is: ', format(kilogramAmount, ',.3f'))
true
1ef83617a069d51eb924275376f133f4c323d375
goruma/CTI110
/P4HW4_Gorum.py
796
4.3125
4
# This programs draws a polygonal shape using nested for loops # 3-18-19 # P4HW4 - Nested Loops # Adrian Gorum # def main(): #Enable turtle graphics import turtle #Set screen variable window = turtle.Screen() #Set screen color window.bgcolor("red") #Pen Settings myPen = turtle.Turtle() myPen.shape("arrow") myPen.speed(10) myPen.pensize(8) myPen.color("yellow") #Nested loop to create square and then iterate the square 8 times at 45 degree angle for x in range(8): for y in range(4): #Create square shape myPen.forward(100) myPen.left(90) #Turn square 45 degrees to the left to start next iteration myPen.left(45) #Program Start main()
true
f3de93f96f4247c3bccba5f699eadd168e4439d0
vincent1879/Python
/MITCourse/ps1_Finance/PS1-1.py
844
4.125
4
#PS1-1.py balance = float(raw_input("Enter Balance:")) AnnualInterest = float(raw_input("Enter annual interest rate as decimal:")) MinMonthPayRate = float(raw_input("Enter minimum monthly payment rate as decimal:")) MonthInterest = float(AnnualInterest / 12.0) TotalPaid = 0 for month in range(1,13): print "Month", str(month) MinMonthPay = float(balance * MinMonthPayRate) print "Minimum monthly payment: $", str(round(MinMonthPay, 2)) InterestPaid = float(balance * MonthInterest) PrincipalPaid = float(MinMonthPay - InterestPaid) print "Principle paid:$", str(round(PrincipalPaid, 2)) TotalPaid += MinMonthPay balance = balance - PrincipalPaid print "Remaining balance: $", str(round(balance, 2)) print "RESULT:" print "Total amount paid:$", str(round(TotalPaid, 2)) print "Remaining balance:$", str(round(balance, 2))
true
b272382f80edeabc91c1a33ba847e34ebff32ac0
Holly-E/Matplotlib_Practice
/Dealing_with_files.py
1,051
4.125
4
# -*- coding: utf-8 -*- """ Spyder Editor Master Data Visualization with Python Course """ #open pre-existing file or create and open new file to write to # you can only write strings to txt files- must cast #'s to str( ) file = open('MyFile.txt', 'w') file.write('Hello') file.close() # can reuse file variable name after you close it. 'a' appends to file, vs 'w' which overwrites file file = open('MyFile.txt', 'a') file.write(' World') # \n makes a new line file.write('\n') file.write(str(123)) file.close() # open in reading mode file = open('MyFile.txt', 'r') # line = first line, if you call twice it will read the second line if there was one line = file.readline().split() print(line) line = file.readline() print(int(line) + 2) # .strip() to remove string .split() to make lists file.close() #The WITH method allows you to perfomr the same actions but without needing to close the file #The file is automatically closed outside the indentation with open('MyFile.txt', 'r') as file: line = file.readline() print(line)
true
39818a02bdab25b77dbfbc76cba087baecbd55d8
nibbletobits/nibbletobits
/python/day 6 in class.py
624
4.21875
4
# ******************************************** # Program Name: Day 5, in class # Programmer: Jordan P. Nolin # CSC-119: Summer 2021 # Date: June 21, 2021 # Purpose: A program to add the sum of all square roots # Modules used: # Input Variables: number() ect # Output: print statements, that output variable answer # ******************************************** def main(): myNumber = 1 stopNumber = 50 total = 0 while myNumber <= stopNumber: x = myNumber**2 total = total + x myNumber = myNumber + 1 print("the total is", total) main() input("press enter to end")
true
3431a14f55b66f3f0c4f9a2010534957f510bd2f
liyi0206/leetcode-python
/225 implement stack using queues.py
821
4.15625
4
class Stack(object): def __init__(self): """ initialize your data structure here. """ self.queue=[] def push(self, x): """ :type x: int :rtype: nothing """ self.queue.append(x) def pop(self): """ :rtype: nothing """ for i in range(len(self.queue)-1): tmp = self.queue.pop(0) self.queue.append(tmp) return self.queue.pop(0) def top(self): """ :rtype: int """ for i in range(len(self.queue)): top = self.queue.pop(0) self.queue.append(top) return top def empty(self): """ :rtype: bool """ return len(self.queue)==0 a=Stack() a.push(1) a.push(2) print a.top()
false
dd9873e3979fc3621a89d469d273f830371d757a
kingamal/OddOrEven
/main.py
500
4.1875
4
print('What number are you thinking?') number = int(input()) while number: if number >=1 and number <= 1000: if number % 2 != 0: print("That's an odd number! Have another?") number = int(input()) elif number % 2 == 0: print("That's an even number! Have another?") number = int(input()) else: print("Thanks for playing") else: print("That's a wrong number! Try it again") number = int(input())
true
d6a5f32aea3864aea415514dad886b81d434a8cc
sahilbnsll/Python
/Inheritence/Program01.py
949
4.25
4
# Basics of Inheritance class Employee: company= "Google Inc." def showDetails(self): print("This is a employee") class Programmer(Employee): language="Python" company= "Youtube" def getLanguage(self): print(f"The Language is {self.language}") def showDetails(self): print("This is Programmer Class.") e = Employee() e.showDetails() p = Programmer() p.showDetails() # Prints same content as e.showDetails because Programmer class doesn't have showDetails() so programmer class inherit showDetails() function from Base class Employee. print(p.company) # Prints "Google Inc." as Programmer class doesn't have company, so programmer class inherit company from Base class Employee. p.showDetails() # Prints "This is Programmer Class" as this time showDetails() is present in Programmer Class. print(p.company) # Prints "Youtube" as this time company is present in Programmer Class.
true
6e0f7759356bbfbf474fc5af93eb902e8a875661
sahilbnsll/Python
/Projects/Basic_Number_Game.py
406
4.15625
4
# Basic Number Game while(True): print("Press 'q' to quit.") num =input("Enter a Number: ") if num == 'q': break try: print("Trying...") num = int(num) if num >= 6: print("Your Entered Number is Greater than or equal to 6\n") except Exception as e: print(f"Your Input Resulted in an Error:{e}") print("Thanks For Playing.")
true
029de1a6a99a93e8b0cf273c51675120a3bcaad6
kashifusmani/interview_prep
/recursion/reverse_string.py
213
4.125
4
def reverse(s): if len(s) == 1 or len(s) == 0: return s return s[len(s)-1] + reverse(s[0: len(s)-1]) # or return reverse(s[1:]) + s[0] if __name__ == '__main__': print(reverse('hello world'))
false
09a14e49b6bb2b7944bc5ec177586a40761ca6f7
kashifusmani/interview_prep
/fahecom/interview.py
2,489
4.125
4
""" Write Python code to find 3 words that occur together most often? Given input: There is the variable input that contains words separated by a space. The task is to find out the three words that occur together most often (order does not matter) input = "cats milk jump bill jump milk cats dog cats jump milk" """ from collections import defaultdict def algo(input, words_len=3): result = {} if len(input) < words_len: pass if len(input) == words_len: result = {make_key(input): 1} else: start = 0 while start+words_len < len(input): current_set = sorted(input[start:start+words_len]) our_key = make_key(current_set) if our_key in result: start += 1 continue else: result[our_key] = 1 print(current_set) inner_start = start + 1 while inner_start+words_len < len(input): observation_set = sorted(input[inner_start:inner_start+ words_len]) if current_set == observation_set: check(our_key, result) inner_start += 1 observation_set = sorted(input[inner_start:]) if current_set == observation_set: check(our_key, result) start += 1 return result def make_key(input): return ','.join(input) def check(our_key, result): if our_key in result: result[our_key] += 1 else: result[our_key] = 1 if __name__ == '__main__': input = "cats milk jump bill jump milk cats dog cats jump milk" print(algo(input.split(" "))) # Difference between tuple and list # What is a generator and why is it efficient # What is a decorator, how it works. # select player_id, min(event_date) as first_login from activity group by player_id order by player_id asc # with x as (select count(*) as total_logins, month-year(login_date) as month_year from logins group by month_year order by month_year asc), # with y as (select total_logins, month_year, row_number() as row), # select month_year, (b.total_logins - a.total_logins)/a.total_logins from # ( select total_logins, month_year, row from y) as a, ( select total_logins, month_year, row from y) as b where a.row + 1 = b.row # # with x as (select count(*) as num_direct_report, manager_id from employee group by manager_id where num_direct_report >=5) # select name from employee join x on employee.id=x.manager_id
true
b1da56330aaed2070bd2a2cf71e7905f800f11db
LaytonAvery/DigitalCraftsWeek1
/Day4/todolist.py
1,089
4.21875
4
choice = "" task = {} def add_task(choice): task = [{"title": name, "priority": priority}] task.append("") for key, value in task.append(""): print(key, value) # print(task) def delete_task(choice): del task def view_all(): for key, value in task.items(): print(key, value) choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) while True: choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) if choice == "1": name = input("Enter a task: ") priority = input("Enter task priority: ") add_task(choice) elif choice == "2": for items in task(): print(items) deletion = input("What would you like deleted? ") delete_task(choice) elif choice == "3": view_all() elif choice == "q": break
true
00aec8932d5749f9f5af478ebb9dbeff183a5c11
krizo/checkio
/quests/singleton.py
874
4.125
4
''' https://py.checkio.org/en/mission/capital-city/ You are an active traveler who have visited a lot of countries. The main city in the every country is its capital and each country can have only one capital city. So your task is to create the class Capital which has some special properties: the first created instance of this class will be unique and single, and all of the other instances should be the same as the very first one. Also you should add the name() method which returns the name of the capital. In this mission you should use the Singleton design pattern. ''' class Capital(object): __instance = None def __new__(cls, city): if Capital.__instance is None: Capital.__instance = object.__new__(cls) Capital.__instance.city = city return Capital.__instance def name(self): return self.city
true
f5c9eb271fbd7da172fa9af87960faff1bd5f675
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/fibfunctions.py
267
4.15625
4
def fibonacci(num): print("printing fibonacci numbers till ", num) v = 1 v1 = 1 v2 = v + v1 print(v) print(v1) while v2 < num: print(v2) v = v1 v1 = v2 v2 = v + v1 fibonacci(10) fibonacci(20) fibonacci(500)
false
68e086044625f54a75bf362a4dd6d63c4632cff6
NALM98/Homework-Course-1
/HW3/HW1.py
1,689
4.125
4
print("Введите, пожалуйста,три любых числа") a = int(input()) b = int(input()) c = int(input()) #1. a и b в сумме дают c #2. a умножить на b равно c #3. a даёт остаток c при делении на b #4. c является решением линейного уравнения ax + b = 0 #5. a разделить на b равно c #6. a в степени b равно c. #1 if a+b == c: print("Сумма чисел a и b равна числу c") else: print("Сумма чисел a и b не равна числу c") #2 if a*b == c: print("Произведение чисел a и b равно числу c") else: print("Произведение чисел a и b не равно числу c") #3 if a%b == c: print ("Число a даёт остаток, равный числу c при делении на число b") else: print ("Число a не даёт остаток, равный числу c при делении на число b") #4 if -1*b/a == c: print("Число c является решением линейного уравнения ax+b") else: print("Число c не является решением линейного уравнения ax+b") #5 if a/b == c: print("Частное от деления числа a на число b равно числу c") else: print("Частное от деления числа a на число b не равно числу c") #6 if a**b == c: print("Число a в степени b равно числу с") else: print("Число a в степени b не равно числу c")
false
2c4041af39e9c050adb9f1aa6352a6b9c25c8436
SwethaGullapalli/PythonTasks
/PrintFileNameHavingPy.py
866
4.375
4
#program to print the file extension having py """give input as list of file names iterate each file name in file names list declare one variable for holding file extension declare variables for index and dot index iterate each character in the file name increment the index by 1 if Character is equal to "." assign index to dot index if index is greater than or equal to dot index concatenate the character to file extension variable if .py== file extension variable print file name""" FileNameList = ["blue.py","black.txt","orange.log","red.py"] for FileName in FileNameList: FileExtension="" Index =0 DotIndex = -1 for Character in FileName: if Character == ".": DotIndex = Index if Index>=DotIndex and DotIndex!=-1: FileExtension=FileExtension+Character Index+=1 if".py" == FileExtension: print FileName
true
012065e8a85e1ac86c2e563e5df3d7feab87101a
Exodus76/aoc19
/day1.py
759
4.125
4
#day 1 part 1 #find the fuel required for a module, take its mass, divide by three, round down, and subtract 2 #part1 function def fuel_required(mass): if(mass < 0): return 0 else: return (mass/3 - 2) #part2 fucntion def total_fuel(mass): total = 0 while(fuel_required(mass) >= 0): total += fuel_required(mass) mass = fuel_required(mass) return total input_file = open('input.txt','r') total_fuel_1 = 0 total_fuel_requirement = 0 list_of_masses = input_file.readlines() for i in list_of_masses: total_fuel_1 += fuel_required(int(i)) print("part1 = " + str(total_fuel_1)) for i in list_of_masses: total_fuel_requirement += total_fuel(int(i)) print("part2 = " + str(total_fuel_requirement))
true
eb78d593489b33d1a5cd3cb14268aef27b553962
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/50.py
897
4.1875
4
import re student_id = input("Enter student id : ") if(re.search("[^0-9]", student_id)): print("Sorry! Student ID can only contains digit") else: student_name = input("Enter student name : ") if re.search("[^a-zA-Z]", student_name): print("Name can only contain alphabets") else: print("Hello",student_name.capitalize()) fees_amount = input("Enter Fees Amount : ") if re.search("^\d+(\.\d{1,2})?$", fees_amount): college_name = "akgec" email_id = student_name.lower()+"@"+college_name+".com" print("\nStudent ID : ",student_id) print("Student Name : ",student_name) print("Student Fees : ",fees_amount) print("Student Email ID : ",email_id) else: print("Sorry! Only two digits are allowed after decimal point")
false
50807cca27c1d9b15e8a43d36a3fe2249529c96c
alixoallen/todos.py
/adivinhação.py
327
4.15625
4
from random import randint computer=randint(0,5) print('pensei no numero{}'.format(computer))#gera um numero aleatorio, ou faz o computador """"""pensar""""""""""""""" escolha=int(input('digite um numero:')) if escolha == computer: print('parabens voce acertou!') else: print('ora ora voce é meio pessimo nisso!')
false
9eb137a3f310eeb8c6d006bfd72fce5e035e06b2
mansiagnihotrii/Data-Structures-in-python
/Linked List/4_linkedlist_partition.py
851
4.125
4
''' Given a linked list and an element , say 'x'. Divide the same list so that the left part of the list has all the elements less that 'x' and right part has all elements greater than or equal to 'x'. ''' #!/usr/bin/env python3 import linkedlist from linkedlist import LinkedList,Node def partition_list(head,element): start = head new = LinkedList() new.head = Node(start.data) start = start.next while start: if start.data >= element: linkedlist.insert_end(new.head,start.data) else: new.head = linkedlist.insert_beg(new.head,start.data) start = start.next return new.head list1 = LinkedList() head = linkedlist.create_list(list1) element = input("Enter partition element: ") if head is None: print("List is empty") else: new_head = partition_list(head,element) linkedlist.printlist(new_head)
true
c696a2980ffe52412000a0f0deda444cea00badf
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/funny_string.py
1,059
4.34375
4
def funny_string(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/funny-string/problem In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. abc -> cba. Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny. Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny. Args: s (str): String to check Returns: str: Returns "Funny" or "Not Funny" based on the results of the string """ for i in range(len(s)//2): if abs(ord(s[i]) - ord(s[i+1])) != abs(ord(s[len(s)-i-1]) - ord(s[len(s)-i-2])): return "Not Funny" return "Funny" if __name__ == "__main__": assert funny_string("acxz") == "Funny" assert funny_string("bcxz") == "Not Funny"
true
0562ecb6074ee2c8d62d863db65a1c5a5325fd66
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/mars_exploration.py
919
4.34375
4
def mars_exploration(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help. Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, s, determine how many letters of Sami's SOS have been changed by radiation. For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed in transit. Args: s (str): string to compare with SOS message (must be divisible by 3) Returns: int: the number of characters that differ between the message and "SOS" """ sos = int(len(s)/3) * "SOS" return sum(sos[i] != s[i] for i in range(len(s))) if __name__ == "__main__": assert mars_exploration("SOSSPSSQSSOR") == 3
true
ff2f6d4c31e79e2249438839b9e85049e4f2c4e0
kcc3/hackerrank-solutions
/python/python_functionals/validating_email_addresses_with_filter.py
1,146
4.15625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain letters, digits, dashes and underscores [a-z], [A-Z], [0-9], [_-]. The website name can only have letters and digits [a-z][A-Z][0-9] The extension can only contain letters [a-z][A-Z]. The maximum length of the extension is 3. Args: s (str): Email address to check Returns: (bool): Whether email is valid or not """ if s.count("@") == 1: if s.count(".") == 1: user, domain = s.split("@") website, extension = domain.split(".") if user.replace("-", "").replace("_", "").isalnum(): if website.isalnum(): if extension.isalnum(): if len(extension) <= 3: return True return False if __name__ == "__main__": test = "itsallcrap" print(fun(test))
true
10a395af6ac6efa71d38074c2d88adff4665435e
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/bit_manipulation/maximizing_xor.py
932
4.3125
4
def maximizing_xor(l, r): """Hackerrank Problem: https://www.hackerrank.com/challenges/maximizing-xor/problem Given two integers, l and r, find the maximal value of a xor b, written a @ b, where a and b satisfy the following condition: l <= a <= b <= r Solve: We XOR the l and r bound and find the length of that integer in binary form. That gives us the binary from which we can create the highest value of a xor b, because that falls within l and r. Args: l (int): an integer, the lower bound inclusive r (int): an integer, the upper bound inclusive Returns: int: maximum value of the xor operations for all permutations of the integers from l to r inclusive """ xor = l ^ r xor_binary = "{0:b}".format(xor) return pow(2, len(xor_binary)) - 1 if __name__ == "__main__": print(maximizing_xor(10, 15)) print(maximizing_xor(11, 100))
true
6d15fcd0279049189d9a54c882f0b27a46034a59
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/the_grid_search.py
2,824
4.21875
4
def grid_search(g, p): """Hackerrank Problem: https://www.hackerrank.com/challenges/the-grid-search/problem Given a 2D array of digits or grid, try to find the occurrence of a given 2D pattern of digits. For example: Grid ---------- 1234567890 0987654321 1111111111 1111111111 2222222222 Pattern ------ 876543 111111 111111 The 2D pattern begins at the second row and the third column of the grid. The pattern is said to be present in the grid. Args: g (list): The grid to search, an array of strings p (list): The pattern to search for, an array of strings Returns: str: "YES" or "NO" depending on whether the pattern is found or not """ for i in range(len(g)-len(p)+1): # If we find a match for the first line, store the indices to search for match = [x for x in range(len(g[i])) if g[i].startswith(p[0], x)] if match: # Iterate through the list of indices where the first line of the pattern matched for j in match: found = True # Now see if the rest of the pattern matches within the same column / index for k in range(1, len(p)): if p[k] == g[i+k][j:j+len(p[k])]: continue else: found = False break if found: return "YES" return "NO" if __name__ == "__main__": g = ["7283455864", "6731158619", "8988242643", "3830589324", "2229505813", "5633845374", "6473530293", "7053106601", "0834282956", "4607924137"] p = ["9505", "3845", "3530"] assert grid_search(g, p) == "YES" g2 = ["7652157548860692421022503", "9283597467877865303553675", "4160389485250089289309493", "2583470721457150497569300", "3220130778636571709490905", "3588873017660047694725749", "9288991387848870159567061", "4840101673383478700737237", "8430916536880190158229898", "8986106490042260460547150", "2591460395957631878779378", "1816190871689680423501920", "0704047294563387014281341", "8544774664056811258209321", "9609294756392563447060526", "0170173859593369054590795", "6088985673796975810221577", "7738800757919472437622349", "5474120045253009653348388", "3930491401877849249410013", "1486477041403746396925337", "2955579022827592919878713", "2625547961868100985291514", "3673299809851325174555652", "4533398973801647859680907"] p2 = ["5250", "1457", "8636", "7660", "7848"] assert grid_search(g2, p2) == "YES" g3 = ["111111111111111", "111111111111111", "111111011111111", "111111111111111", "111111111111111"] p3 = ["11111", "11111", "11110"] assert grid_search(g3, p3) == "YES"
true
6eba8809d2c6d10aadc221ea78cf0d08d458d967
kcc3/hackerrank-solutions
/data_structures/python/stacks/maximum_element.py
1,176
4.34375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/maximum-element/problem You have an empty sequence, and you will be given queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. """ # Enter your code here. Read input from STDIN. Print output to STDOUT # Setup the list which will act as our stack stack = [-1] # Read in the total number of commands num_commands = int(input()) # For each command, append, pop, or return the max value as specified. When we push to the stack, we can compare # with the current highest value so that the stack always has the max value at the tail of the list, and because when # we pop, we are removing the last added item, so it is either the last added value, or a copy of the last max value # when it was added for _ in range(num_commands): query = input().split(" ") if query[0] == "1": stack.append(max(int(query[1]), stack[-1])) elif query[0] == "2": stack.pop() elif query[0] == "3": print(stack[-1]) else: print("Unknown command")
true
54e29a17af6dfcb36c102bba527a588a533d29f3
kcc3/hackerrank-solutions
/python/built_ins/any_or_all.py
548
4.15625
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/any-or-all/problem Given a space separated list of integers, check to see if all the integers are positive, and if so, check if any integer is a palindromic integer. """ n = int(input()) ints = list(input().split(" ")) # Check to see if all integers in the list are positive if all(int(i) >= 0 for i in ints): # Check if any of the integers are a palindrome - where the digit number is the same if digits are reversed print(any(j == j[-1] for j in ints)) else: print(False)
true
048f4a1843a7cb34f846a62ff3cc70225a74c763
kcc3/hackerrank-solutions
/data_structures/python/stacks/balanced_brackets.py
2,594
4.40625
4
def is_balanced(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. By this logic, we say a sequence of brackets is balanced if the following conditions are met: - It contains no unmatched brackets. - The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. Args: s (str): The string to compare Returns: (str): "YES" or "NO" based on whether the brackets in the string are balanced """ open_closed = {"(": ")", "[": "]", "{": "}"} balanced = [] for i in s: if i in open_closed.keys(): balanced.append(i) else: # If the stack is empty, we have a closed bracket without any corresponding open bracket so not balanced if len(balanced) == 0: return "NO" # Compare the brackets to see if they correspond, and if not, not balanced if i != open_closed[balanced.pop()]: return "NO" # If the stack is empty, every open bracket has been closed with a corresponding closed bracket if not balanced: return "YES" # If there's still something in the stack, then return NO because it's not balanced return "NO" if __name__ == "__main__": assert is_balanced("}}}") == "NO" assert is_balanced("{[()]}") == "YES" assert is_balanced("{[(])}") == "NO" assert is_balanced("{{[[(())]]}}") == "YES" assert is_balanced("{{([])}}") == "YES" assert is_balanced("{{)[](}}") == "NO" assert is_balanced("{(([])[])[]}") == "YES" assert is_balanced("{(([])[])[]]}") == "NO" assert is_balanced("{(([])[])[]}[]") == "YES"
true
93d2c4f2eb3485d73051a93cfa531070aa46a563
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/bigger_is_greater.py
1,021
4.28125
4
def bigger_is_greater(w): """Hackerrank Problem: https://www.hackerrank.com/challenges/bigger-is-greater/problem Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria: - It must be greater than the original word - It must be the smallest word that meets the first condition Args: w (str): The word to swap Returns: str: Return the next highest lexicographical word or "no answer" """ # Find non-increasing suffix arr = [c for c in w] i = len(arr) - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 if i <= 0: return "no answer" # Find successor to pivot j = len(arr) - 1 while arr[j] <= arr[i - 1]: j -= 1 arr[i - 1], arr[j] = arr[j], arr[i - 1] # Reverse suffix arr[i:] = arr[len(arr) - 1: i - 1: -1] return "".join(arr) if __name__ == "__main__": print(bigger_is_greater("zzzayybbaa")) print(bigger_is_greater("zyyxwwtrrnmlggfeb"))
true
49f4e08c38d8f2429e77d4af1d29e4010c381208
archeranimesh/pythonFundamentals
/code/pyworkshop/02_list/list_sort.py
556
4.21875
4
# Two ways to sort a list. lottery_numbers = [1, 3, 345, 123, 789, 12341] # 1st method does not modify the original list, # returns a shallow copy of original list. print("sorted list: ", sorted(lottery_numbers)) # reverse the list. print("reverse list: ", sorted(lottery_numbers, reverse=True)) x = sorted(lottery_numbers) # returns a list. print("x = ", x, "\ntypeof(x): ", type(x)) # In place list sorting. lottery_numbers.sort() print("list sort: ", lottery_numbers) # reverse lottery_numbers.reverse() print("list reverse: ", lottery_numbers)
true
63a6c50f451fd165eeff0b514a9c5e87b44b531d
michalecki/codewars
/sum_of_intervals.py
1,528
4.1875
4
''' Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. List containing overlapping intervals: [ [1,4], [7, 10], [3, 5] ] The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. ''' def sum_intervals(inp_arr): ''' :param array: array of intervals :return: sum of lengths of the intervals ''' # sort the intervals over the first digit inp_arr.sort() # loop and merge if overlap i = 0 while i < len(inp_arr) - 1: while inp_arr[i][1] >= inp_arr[i + 1][0]: inp_arr[i] = [inp_arr[i][0], max(inp_arr[i + 1][1], inp_arr[i][1])] del inp_arr[i + 1] if i == len(inp_arr) - 1: break i += 1 # calculate the sum total = sum([inp_arr[x][1] - inp_arr[x][0] for x in range(len(inp_arr))]) return total # testing sum_intervals([ [1, 2], [6, 10], [11, 15] ]) # \; // => 9 sum_intervals([ [1, 4], [7, 10], [3, 5] ]) # ; // => 7 sum_intervals([ [1, 5], [10, 20], [1, 6], [16, 19], [5, 11] ]) # ; // => 19
true
aa970b317af5316d42807008efbc5b41e8347486
michalecki/codewars
/sum_of_numbers.py
582
4.34375
4
def get_sum(a,b): ''' Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. Note: a and b are not ordered! :param a: int :param b: int :return: int ''' if a == b: return a ab = [a, b] ab.sort() return sum(range(ab[0],ab[1]+1)) #testing print(get_sum(0,1)) # ok print(get_sum(4,4)) # ok print(get_sum(0,-1)) print(get_sum(-2,0)) print(get_sum(-3,-2)) print(get_sum(4,2)) print(get_sum(-3,5))#ok
true
a72af4074104f47c32f8714796c4a1f6948bc8d1
ShreyanGoswami/coding-contests
/Leetcode weekly contest 189/rearrange_words_in_sentence.py
860
4.25
4
''' Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. ''' class Solution: def arrangeWords(self, text: str) -> str: ''' Time complexity: O(nlogn) Space complexity: O(n*m) where n is the number of words and m is the maximum number of letters in a word ''' words = text.split() words[0] = words[0].lower() words.sort(key = lambda x: len(x)) words[0] = words[0].capitalize() return " ".join(x for x in words)
true
1eb433504868fbaa75faaa7bac81000f9431dee6
cwang-armani/learn-python
/09 数据结构与算法/5 栈.py
699
4.1875
4
class Queue(object): '''定义一个栈''' def __init__(self): self.__item = [] def is_empty(self): # 判断列表是否为空 return self.__item == [] def enqueue(self,item): # 入队 self.__item.append(item) return item def dequeue(self): # 出队 return self.__item .pop(0) def size(self): return len(self.__item) if __name__ == "__main__": q = Queue() print(q.enqueue(1)) print(q.enqueue(2)) print(q.enqueue(3)) print(q.enqueue(4)) print("-"*20) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue())
false
985bb44337d98dcf1b07803b84ae7417f48c0015
pragatij17/General-Coding
/Day 6/python/sum_of_numbers.py
256
4.25
4
# Write a program that asks the user for a number n and prints the sum of the numbers 1 to n. def sum_of_number(n): sum = 0 for i in range(1,n+1): sum =sum + i return sum n = int(input('Last digit of sum:')) print(sum_of_number(n))
true
c84859d03e6df77d8575dddd7192f2f36852ba31
RojieEmanuel/intro-python
/102.py
2,170
4.1875
4
weekdays = ['mon','tues','wed','thurs','fri'] print(weekdays) print(type(weekdays)) days = weekdays[0] # elemento 0 days = weekdays[0:3] # elementos 0, 1, 2 days = weekdays[:3] # elementos 0, 1, 2 days = weekdays[-1] # ultimo elemento test = weekdays[3:] # elementos 3, 4 weekdays days = weekdays[-2] # ultimo elemento (elemento 4 days = weekdays[::] # all elementos days = weekdays[::2] # cada segundo elemento (0, 2, 4) days = weekdays[::-1] # reverso (4, 3, 2, 1, 0) all_days = weekdays + ['sat','sun'] # concatenar print(all_days) # Usando append days_list = ['mon','tues','wed','thurs','fri'] days_list.append('sat') days_list.append('sun') print(days_list) print(days_list == all_days) list = ['a', 1, 3.14159265359] print(list) print(type(list)) print('\n\t') # list.reverse() # print(list) ######### print('#############################################################################################################################') print( 'Exercicios - Listas') # Faca sem usar loops ######### # Como selecionar 'wed' pelo indice? print('\n1') print(days_list[2]) # Como verificar o tipo de 'mon'? print('\n2') print(type(days_list[0])) # Como separar 'wed' até 'fri'? print('\n3') print(days_list[2:5]) # Quais as maneiras de selecionar 'fri' por indice? print('\n4') print(days_list[4]) print(days_list[4:5]) # Qual eh o tamanho dos dias e days_list? print('\n5') dias = len(days) listaD= len(days_list) print('tamanho de dias: ', dias) print('tamanho de days_list: ', listaD) # Como inverter a ordem dos dias? print('\n6') print(weekdays[::-1]) # Como atribuir o ultimo elemento de list na variavel ultimo_elemento e remove-lo de list? print('\n 10') ultimo_elemento = list[-1] print(ultimo_elemento) list.remove(list[-1]) print(list) # Como inserir a palavra 'zero' entre 'a' e 1 de list? print('\n7') list.insert(1,'zero') print(list) # Como limpar list? print('\n8') print(list.clear()) # Como deletar list? print('\n9') print() print('######################################### FIM ##############################################################################')
false
dcf7913f53b7ea31ba263c2a26ecd5a52334846e
SaidRem/algorithms
/find_biggest_(recursion).py
404
4.21875
4
# Finds the biggest element using recursion def the_biggest(arr): # Base case if length of array equals 2 . if len(arr) == 2: return arr[0] if arr[0] > arr[1] else arr[1] # Recursion case. sub_max = the_biggest(arr[1:]) return arr[0] if arr[0] > sub_max else sub_max if __name__ == '__main__': arr = list(map(int, input().strip().split())) print(the_biggest(arr))
true
6af4513c000f0bf8ae449e915e146515187fed08
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab07-rock_paper_scissors.py
1,327
4.25
4
#lab07-rockpaperscissors.py import random user_input = 'yes' while user_input == 'yes': print('Let\'s play rock-paper-scissors!') print('The computer will ask the user for their choice of rock, paper or scissors, and then the computer will randomly make a selection.') #computer tell user how the game will work user = input ('rock, paper or scissors:') choices = ('rock', 'paper', 'scissors') #the user will have to choose one of these options computer = random.choice(choices) #the computer will select a random choice if user == computer: print('It\'s a tie') elif user == 'rock': if computer == 'paper': print('Computer wins, the computer chose paper') if computer =='scissors': print('Computer loses, the computer chose scissors' ) elif user == 'paper': if computer =='scissors': print('Computer wins, the computer chose scissors' ) if computer == 'rock': print('Computer loses, the computer chose rock') elif user == 'rock': if computer =='scissors': print('Computer loses, the computer chose scissors' ) if computer == 'rock': print('Computer wins, the computer chose rock') user = input('Would you like to play again?')
true
4885b4212545ee9f635fed82f045478503adc865
PdxCodeGuild/class_mudpuppy
/Reviewed/Brea/python/lab17/lab17_version2_checked.py
1,009
4.125
4
#Lab 17, Version 2 Anagram def split(word): return list(word) # good practice, but generally don't make a function # that calls a single function, especially one that's already well-known like list() def remove_spaces(str): new_str = '' for i in range(len(str)): if(str[i] != ' '): new_str += str[i] return new_str # I like that you did this the hard way (you learn more that way) # but you could just do str.replace('', ' ') # Also, don't use the parameter str, that overwrites a builtin function user_input1 = input("What is the first input you'd like to compare? : ") user_input1 = user_input1.lower() list_inp1 = split(remove_spaces(user_input1)) user_input2 = input("What is the second input to compare? : ") user_input2 = user_input2.lower() list_inp2 = split(remove_spaces(user_input2)) list_inp1.sort() list_inp2.sort() if list_inp1 == list_inp2: print("These two inputs are anagrams!") else: print("These two inputs are not anagrams!") # Nice!
true
37675d15d25aa51006258ff94564fbc04ff6e685
PdxCodeGuild/class_mudpuppy
/1 Python/class_demos/function-lecture/add-number-words-ultimate-solution.py
986
4.125
4
import operator def get_valid_input(): valid_input = False while not valid_input: num1 = input("Spell out a number with letters: ") if num1 in number_dict: return num1 else: print(f"{num1} is not supported. Try entering a different number: ") def reduce_list_to_value(fn, starting_value, values): accumulator = starting_value for val in values: accumulator = fn(accumulator, val) return accumulator def square_and_add(x,y): return x + y**2 number_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} numbers = [] for _ in range(4): inp = get_valid_input() numbers.append(number_dict[inp]) number_sum = reduce_list_to_value(operator.add, 0, numbers) product = reduce_list_to_value(operator.mul, 1, numbers) sum_squares = reduce_list_to_value(square_and_add, 0, numbers) print(f"The sum is {number_sum}, the product is {product}, the sum of squares is {sum_squares}")
true
096d0dc863ab7739debf8e8000545f4e7f7f3cda
PdxCodeGuild/class_mudpuppy
/Assignments/Devan/1 Python/labs/lab11-simple_calculator.py
1,098
4.21875
4
# Lab 11: Simple Calculator Version 3 def get_operator(op): return operators[op] def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def eval(fn, n1, n2): return fn(n1, n2) operators = {'+': add, '-': subtract, '*': multiply, '/': divide} while True: try: operator = input('Enter your operator (+, -, *, /) or done: ') if operator == 'done': print('\nThanks for using the calculator.') break if operator not in operators: print('Not a vaild operator...') else: # todo: validate user entered number n1 = input('Enter the first number: ') if n1 is not int: print('Enter a vaild number. ') n2 = int(input('Enter the second number: ')) if n2 is not int: print('Enter a valid number. ') print(eval(get_operator(operator), int(n1), int(n2))) except KeyboardInterrupt: print('\nThank You') break
true
50962379cef04f28b24854aeeaccc11e9f673a9b
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/labs06.py
1,170
4.21875
4
# Lab 6: Password Generator """ Let's generate a password of length `n` using a `while` loop and `random.choice`, this will be a string of random characters. """ import random import string # string._file_ = random.choice('string.ascii_letters + string.punctuation + string.digits') # #print((string._file_)) # pass_num = input ("How many characters? ") # pass_num = int(pass_num) # out_num = '' # for piece in range(pass_num): # out_num = out_num + random.choice(string.ascii_letters + string.punctuation + string.digits) # print(out_num) string._file_ = random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) pass_low = input("How many lowercase? ") pass_low = int(pass_low) pass_high = input("How many uppercase? ") pass_high = int(pass_high) pass_dig = input("How many numbers? ") pass_dig = int(pass_dig) out_num = '' for piece in range(pass_low): out_num = out_num + random.choice(string.ascii_lowercase) for piece in range(pass_high): out_num = out_num + random.choice(string.ascii_uppercase) for piece in range(pass_dig): out_num = out_num + random.choice(string.digits) print(out_num)
true
2874845c72626487f96500a7aac40ba91891870e
PdxCodeGuild/class_mudpuppy
/1 Python/solutions/lab09-v2.5.py
617
4.34375
4
# Supported unit types supported_units = ["ft", "mi", "m", "km"] # Ask the user for the unit they want unit = input("What unit do you want: ") # If an invalid unit is specified, alert the user and exit if unit not in supported_units: print("Please enter a valid unit! Options are ft, mi, m, km...") exit() # Get the amount of units amount = float(input("How many units: ")) # Check to see if the unit matches one we know if unit == "ft": print(amount * 0.3048) elif unit == "mi": print(amount * 1609.34) elif unit == "m": print(amount * 1 * 1 * 1) # Extra spicy elif unit == "km": print(amount * 1000)
true
7d22fbd58d09e95c2ab94e8adb567da9c3932b36
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab18.py
439
4.125
4
import string input_string = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] #change variable name #create an empty list for index in range(1,len(input_string)-1): left_side = input_string[index-1] middle = input_string[index] right_side = input_string[index + 1] if left_side < middle and right_side < middle: print(index) elif left_side > middle and right_side > middle: print(index)
true
91c7e627278fe3386b9db69c2bf8636072abbeaf
PdxCodeGuild/class_mudpuppy
/Assignments/Eboni/lab09-unit_converter.py
1,154
4.46875
4
""" Ask the user for the number of feet, and print out the equivalent distance in meters. Hint: 1 ft is 0.3048 m. So we can get the output in meters by multiplying the input distance by 0.3048. Below is some sample input/output. """ # import decimal # print("Enter number of feet ") # number_feet = float(input('')) # meters = 0.3048 # print(f" that equals {number_feet * meters} meters ") """ Allow the user to also enter the units. Then depending on the units, convert the distance into meters. The units we'll allow are feet, miles, meters, and kilometers. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ") """ Add support for yards, and inches. """ # import math # distance = 11 # user = input("Choose a unit: ") # unit_dict = { 'feet' : 0.3048, 'miles': 1609.3, 'meter': 1, 'kilometer': 1000, 'yard' : 0.9144, 'inch' : 0.254 } # user_int = unit_dict[user] # conversion = user_int * distance # print(f"(The conversion is {conversion} ")
true
c5d508427ca54175b9b640d81d451807aa07ac21
PdxCodeGuild/class_mudpuppy
/Assignments/Racheal/python/test.py
1,247
4.34375
4
import random #Twinkle, twinkle, little star, #How I wonder what you are! #Up above the world so high, #Like a diamond in the sky. # little = input("Enter adjective:") # wonder = input("Enter verb:") # world = input("Enter noun:") # high = input("Enter adjective:") # diamond = input("Enter noun:") # sky =input("Enter noun:") # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") # list1 = [] user_input = input('enter a plural noun, an adjective, a verb, a noun, and another adjective:' ) # list1 = user_input.append(user_input) # print(f"twinkle, twinkle,{little} star, how I {wonder} what you are! Up above the {world} so {high} like a {diamond}in the {sky}. Twinkle twinkle little start, how I wonder what you are") user_input_list = user_input.split() print(len(user_input_list)) print(f"twinkle, twinkle,{user_input_list[0]} star, how I {user_input_list[1]} what you are! Up above the {user_input_list[2]} so {user_input_list[3]} like a {user_input_list[4]}in the. Twinkle twinkle little start, how I wonder what you are") word = "" for i in range(): word += random.choice() print(word)
true
a8dd0814e6f3294f7c65ed85b0c49311589f6fb8
PdxCodeGuild/class_mudpuppy
/Assignments/Terrance/Python/lab25-atm.py
2,171
4.15625
4
#lab25-atm.py class ATM: def __init__(self, balance=0, interest_rate=.01): self.balance = balance self.interest_rate = interest_rate self.transactions = [] def check_balance(self): '''returns the account balance''' print(f"Your balance is {self.balance}") return self.balance def deposit(self, amount): '''deposits the given amount in the account''' print(f"Your deposit is {amount}") self.balance += amount self.transactions.append(f'User deposited ${amount}') print(f"Your balance is {self.balance}") def check_withdrawal(self, amount): '''returns true if the withdrawn amount won't put the account in the negative''' if self.balance >= amount: return True else: return False def withdrawl(self, amount): '''withdraw(amount) withdraws the amount from the account and returns it''' if self.balance >= amount: self.balance -= amount print(f"Your balance is {self.balance}") self.transactions.append(f'User withdrew ${amount}') else: print("You do not have enough money") def print_transactions(self): print(f"Here is your list of transactions {self.transactions}") '''printing out the list of transactions''' def calc_interest(self): '''returns the amount of interest calculated on the account''' interest = self.balance * self.interest_rate print(f"Your balance is {interest}") my_atm = ATM(balance=100) while True: user_choice = input('Choose (d)eposit, (w)ithdrawl, (cb)alance, (h)istory, (q)uit: ') if 'd' == user_choice: amount = input(f'How much would you like to deposit?') my_atm.deposit(int(amount)) if 'w' == user_choice: amount = input(f'How much would you like to withdrawl?') my_atm.withdrawl(int(amount)) if 'cb' == user_choice: my_atm.check_balance() if 'h' == user_choice: my_atm.print_transactions() elif 'q' == user_choice: break print(f'Thank you, please come again!')
true
4e17ad1e21e211e490a7e0b4ef34b71052415dc9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_042220.py
225
4.1875
4
#Test Examples, April 22nd, 2020 data1 = {'a': 1} data2 = {'a': {'b': 1}} #if we call 'a', it'll return the dictionary data3 = {'a': {'b': 1}, 'z': ['Portland', 'Seattle', 'LA']} #if we call data3['z'][0], returns 'Portland'
false
a35cffa0ab2b6c4424709cf8693ef70106688eb9
PdxCodeGuild/class_mudpuppy
/Assignments/Brea/Class Examples/Test_042120.py
1,464
4.1875
4
#Test Examples April 21st, 2020 #average numbers lab re-do # nums = [5, 0, 8, 3, 4, 1, 6] # running_sum = 0 # for num in nums: # running_sum = running_sum + num # print(running_sum) # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") #--------REPL Version of average numbers lab # nums = [] # running_sum = 0 # while True: # user_input = int(input("Enter a number (or, '0' for done) : ")) # if user_input == 0: # aver = running_sum / len(nums) # print(f"The average of your numbers is {aver}.") # break # nums.append(user_input) # running_sum += user_input # print(nums) #-----------class version of average numbers # class NumList: # def __init__(self): # self.nums = [] # def append(self, in_num): # self.nums.append(int(in_num)) # def average(self): # return sum(self.nums) / len(self.nums) # me = NumList() # while True: # user_input = input("Enter a number or 'done': ") # if user_input == 'done': # break # me.append(user_input) # print(me.nums) # print(me.average()) #--------------------- #Tic Tac Toe Tests board = [[' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' '], [' ', '|', ' ', '|', ' ']] board2 = [] # for inner_list in board: # board2.append(''.join(inner_list)) board2 = '\n'.join([''.join(inner_list) for inner_list in board]) print(board2)
true
750437c3c078315b3a3ee1981aa1173e2dfaeefe
charlotteviner/project
/land.py
1,632
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 28 17:37:12 2017 @author: charlotteviner Credit: Code written by Andrew Evans. Create elevation data for use in the project. Provided for background on how the artificial environment 'land' was created. Returns: land (list) -- List containing land elevation data. land (.txt) -- File containing data for the land elevation. """ import matplotlib import csv w = 100 # Set width to 100. h = 100 # Set height to 100. land = [] # Create empty list called 'land'. # Plot a 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. row = [] # Create empty list called 'row'. for x in range(0, w): row.append(0) # Append 0 to 'row' at (0, w) until w = 100. land.append(row) # Append each row created to the 'land' list. # Add relief to the 100 x 100 square. for y in range(0, h): # Cycle through coordinates (0, h) until h = 100. for x in range(0, w): # Cycle through (0, w) until w = 100. if (x + y) < w: # If (x + y) < w, then the coordinate will = x + y. land[y][x] = x + y else : # If not, the coordinate will = (w - x) + (h - y). land[y][x] = (w - x) + (h - y) # Plot 'land' on a graph. matplotlib.pyplot.ylim(0, h) # Limit of y axis. matplotlib.pyplot.xlim(0, w) # Limit of x axis. matplotlib.pyplot.imshow(land) print(land) # Create a new file 'land.txt' which contains the coordinate data. f = open('land.txt', 'w', newline='') writer = csv.writer(f, delimiter=',') for row in land: writer.writerow(row) f.close()
true
a13f132c3ac6e87e313570bcc86e470c096ae0b5
koushik-chandra-sarker/PythonLearn
/a_script/o_Built-in Functions.py
1,608
4.125
4
""" Python Built-in Functions: https://docs.python.org/3/library/functions.html or https://www.javatpoint.com/python-built-in-functions """ # abs() # abs() function is used to return the absolute value of a number. i = -12 print("Absolute value of -40 is:", abs(i)) # Output: Absolute value of -40 is: 12 # bin() # Convert an integer number to a binary string prefixed with “0b”. i = 5 print(bin(i)) # Output: 0b101 # sum() x = sum([2, 5, 3]) print(x) # Output: 10 x = sum((5, 5, 3)) print(x) # Output: 13 x = sum((5, 5, 3), 10) print(x) # Output: 23 x = sum((3 + 5j, 4 + 3j)) print(x) # Output: (7+8j) # pow() """ pow(x, y, z) x: It is a number, a base y: It is a number, an exponent. z (optional): It is a number and the modulus. """ print(pow(2, 3)) # Output: 8 print(pow(4, 2)) # Output: 16 print(pow(-4, 2)) # Output: 16 print(pow(-2, 3)) # Output: -8 # min() function is used to get the smallest element from the collection. s = min(123, 2, 5, 3, 6, 35) print(s) # Output: 2 s = min([10, 12], [12, 21], [13, 15]) print(s) # Output: 2[10, 12] s = min("Python", "Java", "Scala") print(s) # Output: java s = min([10, 12, 33], [12, 21, 55], [13, 15], key=len) print(s) # Output:[13,15] # max() function is used to get the highest element from the collection. s = max(123, 2, 5, 3, 6, 35) print(s) # Output: 123 s = max([10, 12], [12, 21], [13, 15]) print(s) # Output: [13, 15] s = max("Python", "Java", "Scala") print(s) # Output: scala s = max([10, 12, 33], [12, 21, 55, 9], [13, 15], key=len) print(s) # Output:[12, 21, 55, 9]
true
681879f34aefef0a7ad1737bffab3fae05566bd1
victorboneto/Python
/src/sqc/exe9.py
266
4.1875
4
#Faça um Programa que peça a temperatura em graus Fahrenheit, #transforme e mostre a temperatura em graus Celsius. #C = 5 * ((F-32) / 9). graus = int(input("Digite o graus Fahrenheit aqui: ")) celsius = 5 * ((graus - 32) / 9) print("Tem {}ºc" .format(celsius))
false
19c94192bbd45a17858bd0b0348a077042c144b7
gibsonn/MTH420teststudent
/Exceptions_FileIO/exceptions_fileIO.py
2,762
4.25
4
# exceptions_fileIO.py """Python Essentials: Exceptions and File Input/Output. <Name> <Class> <Date> """ from random import choice # Problem 1 def arithmagic(): """ Takes in user input to perform a magic trick and prints the result. Verifies the user's input at each step and raises a ValueError with an informative error message if any of the following occur: The first number step_1 is not a 3-digit number. The first number's first and last digits differ by less than $2$. The second number step_2 is not the reverse of the first number. The third number step_3 is not the positive difference of the first two numbers. The fourth number step_4 is not the reverse of the third number. """ step_1 = input("Enter a 3-digit number where the first and last " "digits differ by 2 or more: ") step_2 = input("Enter the reverse of the first number, obtained " "by reading it backwards: ") step_3 = input("Enter the positive difference of these numbers: ") step_4 = input("Enter the reverse of the previous result: ") print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)") # Problem 2 def random_walk(max_iters=1e12): """ If the user raises a KeyboardInterrupt by pressing ctrl+c while the program is running, the function should catch the exception and print "Process interrupted at iteration $i$". If no KeyboardInterrupt is raised, print "Process completed". Return walk. """ walk = 0 directions = [1, -1] for i in range(int(max_iters)): walk += choice(directions) return walk # Problems 3 and 4: Write a 'ContentFilter' class. """Class for reading in file Attributes: filename (str): The name of the file contents (str): the contents of the file """ class ContentFilter(object): # Problem 3 def __init__(self, filename): """Read from the specified file. If the filename is invalid, prompt the user until a valid filename is given. """ # Problem 4 --------------------------------------------------------------- def check_mode(self, mode): """Raise a ValueError if the mode is invalid.""" def uniform(self, outfile, mode='w', case='upper'): """Write the data ot the outfile in uniform case.""" def reverse(self, outfile, mode='w', unit='word'): """Write the data to the outfile in reverse order.""" def transpose(self, outfile, mode='w'): """Write the transposed version of the data to the outfile.""" def __str__(self): """String representation: info about the contents of the file."""
true
577e6159eadade42ea06061c3fbe1a16536644f1
Rayff-de-Souza/Python_Geek-University
/SECAO-6-EXERCICIO-2/index.py
408
4.15625
4
""" GEEK UNIVERSITY - Exercício - Faça um programa que escreva de 1 até 100 duas vezes, sendo a primeira vez com o loop FOR e a segunda com o loop WHILE. """ print('FOR'.center(20, '_')) for n in range(1, 101): print(n) print('FOR'.center(20, '_')) print('\n') contador = 1 print('WHILE'.center(20, '_')) while contador < 101: print(contador) contador = contador + 1 print('WHILE'.center(20, '_'))
false
cd11542b28904b0865526267ec5db987183b714d
Yu4n/Algorithms
/CLRS/bubblesort.py
647
4.25
4
# In bubble sort algorithm, after each iteration of the loop # largest element of the array is always placed at right most position. # Therefore, the loop invariant condition is that at the end of i iteration # right most i elements are sorted and in place. def bubbleSort(ls): for i in range(len(ls) - 1): for j in range(0, len(ls) - 1 - i): if ls[j] > ls[j + 1]: ls[j], ls[j + 1] = ls[j + 1], ls[j] '''for j in range(len(ls) - 1, i, -1): if ls[j] < ls[j - 1]: ls[j], ls[j - 1] = ls[j - 1], ls[j]''' a = [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5] bubbleSort(a) print(a)
false
69fe06f4d308eca042f3bf0c30f4a207d65473ac
Yu4n/Algorithms
/CLRS/insertion_sort.py
1,175
4.3125
4
# Loop invariant is that the subarray A[0 to i-1] is always sorted. def insertionSort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key # Driver code to test above def insertionSortRecursive(arr, n): # base case if n <= 1: return # Sort first n-1 elements insertionSortRecursive(arr, n - 1) '''Insert last element at its correct position in sorted array.''' key = arr[n - 1] j = n - 2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key if __name__ == '__main__': arr = [12, 11, 13, 5, 6] insertionSort(arr) print(arr) arr2 = [6, 5, 4, 3, 2, 1, 0, -1] insertionSortRecursive(arr2, len(arr2)) print(arr2)
true
46fd209659f3dd4ca466d6ca7e7af8f23c661238
mverini94/PythonProjects
/DesignWithFunctions.py
2,401
4.65625
5
''' Author....: Matt Verini Assignment: HW05 Date......: 3/23/2020 Program...: Notes from Chapter 6 on Design With Functions ''' ''' Objectives for this Chapter 1.) Explain why functions are useful in structuring code in a program 2.) Employ a top-down design design to assign tasks to functions 3.) Define a recursive function 4.) Explain the use of the namespace in a program and exploit it effectively 5.) Define a function with required and optional parameters 6.) Use higher-order fuctions for mapping, filtering, and reducing - A function packages an algorithm in a chunk of code that you can call by name - A function can be called from anywhere in a program's code, including code within other functions - A function can receive data from its caller via arguments - When a function is called, any expression supplied as arguments are first evaluated - A function may have one or more return statements ''' def summation(lower, upper): result = 0 while lower <= upper: result += lower #result = result + lower lower += 1 #lower = lower + 1 print(result) summation(1, 4) ''' - An algorithm is a general method for solving a class of problems - The individual problems that make up a class of problems are known as problem instances - What are the problem instances of our summation algorithm? - Algorithms should be general enough to provide a solution to many problem instances - A function should provide a general method with systematic variations - Each function should perform a single coherent task - Such as how we just computed a summation ''' ''' TOP-DOWN Design starts with a global view of the entire problem and breaks the problem into smaller, more manageable subproblems - Process known as problem decomposition - As each subproblem is isolated, its solution is assigned to a function - As functions are developed to solve subproblems, the solution to the overall problem is gradually filled ot. - Process is also called STEPWISE REFINEMENT - STRUCTURE CHART - A diagram that shows the relationship among a program's functions and the passage of data between them. - Each box in the structure is labeled with a function name - The main function at the top is where the design begins - Lines connecting the boxes are labeled with data type names - Arrows indicate the flow of data between them '''
true
caaceae86ca5f9ac137756c98fccecba86b05c88
mverini94/PythonProjects
/__repr__example.py
540
4.34375
4
import datetime class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __repr__(self): return '__repr__ for Car' def __str__(self): return '__str__ for Car' myCar = Car('red', 37281) print(myCar) '{}'.format(myCar) print(str([myCar])) print(repr(myCar)) today = datetime.date.today() print() '''str is used for clear representation for someone to read''' print(str(today)) print() '''repr is used for debugging for developers''' print(repr(today))
true
2e0c3573ed6698fa45e56983fb5940dc57daeb94
odai1990/madlib-cli
/madlib_cli/madlib.py
2,673
4.3125
4
import re def print_wecome_mesage(): """ Print wilcome and explane the game and how to play it and waht the result Arguments: No Arguments Returns: No return just printing """ print('\n\n"Welcome To The Game" \n\n In this game you will been asked for enter several adjectives,nouns,numbers and names and collect these and put them in a funny paragraph.\n\n Be Ready ') def read_template(file_name): """ Reading file and return it to other function Arguments: n:string --- ptha file Returns: String of all countent of ifle """ try: with open(file_name) as file: content_text=file.read() except Exception: raise FileNotFoundError("missing.txt") return content_text def parse_template(content_text): """ Saprate text form each location will replace it inputs user Arguments: content_text:string --- test Returns: list contane stripted text and what we stripted in tuple """ all_changes=re.findall('{(.+?)}',content_text) all_text_stripted=re.sub("{(.+?)}", "{}",content_text) return all_text_stripted,tuple(all_changes) def read_from_user(input_user): """ Reaing inputs from user Arguments: input_user:string --- to let users knows waht he should insert Returns: string of waht user input """ return input(f'> Please Enter {input_user}: ') def merge(*args): """ put every thing toguther what user input and stripted text Arguments: args:list --- list of wat user input and stripted text Returns: return text merged with user inputs """ return args[0].format(*args[1]) def save(final_content): """ save the file to specifec location with final content Arguments: path:string --- the path where you whant to add final_content:string --- final text Returns: none/ just print result """ with open('assets/result.txt','w') as file: file.write(final_content) print(final_content) def start_game(): """ Strating the game and mangae the order of calling functions Arguments: none Returns: none """ print_wecome_mesage() content_of_file=parse_template(read_template('assets/sample.txt')) save(merge(content_of_file[0],map(read_from_user,content_of_file[1]))) def test_prompt(capsys, monkeypatch): monkeypatch.setattr('path.to.yourmodule.input', lambda: 'no') val = start_game() assert not val if __name__ == '__main__': start_game()
true
0dbfe08ed9fd0f87544d12239ca9505083c85986
mpsacademico/pythonizacao
/parte1/m004_lacos.py
1,641
4.15625
4
# codig=UTF-8 print("FOR") # repete de forma estática ou dinâmica animais = ['Cachorro', 'Gato', 'Papagaio'] # o for pode iterar sobre uma coleção (com interador) de forma sequencial for animal in animais: # a referência animal é atualizada a cada iteração print(animal) else: # executado ao final do laço (exceto com break) print("A lista de animais terminou no ELSE") # contando pares: passando para a próxima iteração em caso de ímpar for numero in range(0, 11, 1): if numero % 2 != 0: #print(numero, "é ímpar") continue # passa para a próxima iteração print(numero) else: print("A contagem de pares terminou no ELSE") ''' range(m, n, p) = retorna uma lista de inteiros - começa em m - menores que n - passos de comprimento p ''' # saldo negativo: parando o laço em caso de valor negativo saldo = 100 for saque in range(1, 101, 1): resto = saldo - saque if resto < 0: break # interrompe o laço, o ELSE não é executado saldo = resto print("Saque:", saque, "| Saldo", saldo) else: print("ELSE não é executado, pois o laço sofreu um break") # -------------------------------------------------------------------- print("WHILE") # repete enquanto a codição for verdadeira idade = 0 while idade < 18: escopo = "escopo" # variável definida dentro do while idade += 1 # incrementar unitariamente assim if idade == 4: print(idade, "anos: tomar vacina") continue # pula o resto e vai para próxima iteração if idade == 15: print("Ops! :( ") break # interrompe o laço completamente!!! print(idade) else: print("ELSE: Você já é maior de idade | ESCOPOS:", idade, escopo)
false
5cc5a1970d143188e1168d521fac27f4534f3032
fastestmk/python_basics
/dictionaries.py
441
4.375
4
# students = {"Bob": 12, "Rachel": 15, "Anu": 14} # print(students["Bob"]) #length of dictionary # print(len(students)) #updating values # students["Rachel"] = 13 # print(students) #deleting values # del students["Anu"] # print(students) my_dict = {'age': 24, 'country':'India', 'pm':'NAMO'} for key, val in my_dict.items(): print("My {} is {}".format(key, val)) for key in my_dict: print(key) for val in my_dict.values(): print(val)
false
07cd0f2a3208e04dd0c34a501b68de19f692c35a
Temesgenswe/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
364
4.3125
4
#!/usr/bin/python3 """Module defines append_write() function""" def append_write(filename="", text=""): """Appends a string to a text file Return: the number of characters written Param: filename: name of text file text: string to append """ with open(filename, 'a', encoding="UTF8") as f: return f.write(str(text))
true
86e76c7aa9c052b23b404c05f57420750a5029b7
Temesgenswe/holbertonschool-higher_level_programming
/0x06-python-classes/103-magic_class.py
751
4.4375
4
#!/usr/bin/python3 import math class MagicClass: """Magic class that does the same as given bytecode (Circle)""" def __init__(self, radius=0): """Initialize radius Args: radius: radius of circle Raises: TypeError: If radius is not an int nor a float """ self.__radius = 0 if type(radius) is not int and type(radius) is not float: raise TypeError('radius must be a number') self.__radius = radius def area(self): """Returns the calculated area of circle""" return self.__radius ** 2 * math.pi def circumference(self): """Returns the calculated circumference of circle""" return 2 * math.pi * self.__radius
true
d3e203ffb4eac1ffe1bd1776de5f06220b81b6c1
LorenzoChavez/CodingBat-Exercises
/Warmup-1/sum_double.py
231
4.15625
4
# Given two int values, return their sum. Unless the two values are the same, then return double their sum. def sum_double(a, b): result = 0 if a == b: result = (a+b) * 2 else: result = a+b return result
true
7ce2d175697104c3df72fd437f9fe01fc0ed5053
alxanderapollo/HackerRank
/WarmUp/salesByMatchHR.py
1,435
4.3125
4
# There is a large pile of socks that must be paired by color. Given an array of integers # representing the color of each sock, determine how many pairs of socks with matching colors there are. # Example # There is one pair of color and one of color . There are three odd socks left, one of each color. # The number of pairs is . # Function Description # Complete the sockMerchant function in the editor below. # sockMerchant has the following parameter(s): # int n: the number of socks in the pile # int ar[n]: the colors of each sock # Returns # int: the number of pairs # Input Format # The first line contains an integer , the number of socks represented in . # The second line contains space-separated integers, , the colors of the socks in the pile. def sockMerchant(n, ar): mySet = set() #hold all the values will see count = 0 #everytime we a see a number we first check if it is already in the set #if it is delete the number for i in range(n): if ar[i] in mySet: mySet.remove(ar[i]) count+=1 else: mySet.add(ar[i]) return count #add one to the count #otherwise if we've never seen the number before add it to the set and continue #once we are done with the array #return the count n = 9 ar = [10,20 ,20, 10, 10, 30, 50, 10, 20] print(sockMerchant(n, ar))
true
3b38c1507501d451d741da0daa812a4f63152941
kushagra65/Python-CLock-Project
/ANALOG CLOCK.py
2,034
4.28125
4
#import the essential modules import time# importing the time module import turtle #importing the turtle module from the LOGO days #---------------------------------------------------------------- #creating the screen of the clock wn = turtle.Screen()#creating a screen wn.bgcolor("black")#setting the backgroung color wn.setup(width=600, height=600)#setting the size of the screen wn.title("analog clock @ kushagra verma") wn.tracer(0)#sets the animation time ,see in the while loop #--------------------------------------------------------------------------- #creating our drawing pen pen = turtle.Turtle()# create objects pen.hideturtle() pen.speed(0) # animation speed pen.pensize(5) # widht of the pens the pen is drawing def DrawC(h,m,s,pen):# creates min,hr,sec hands #drawing a clock face pen.penup() #means dont draw a line pen.goto(0, 210) pen.setheading(180)#pen facing to the left pen.color("orange")#color of the circle pen.pendown() pen.circle(210) #now drawing lines for the hours pen.penup() pen.goto(0, 0) pen.setheading(90) for _ in range(12): pen.fd(190) pen.pendown() pen.fd(20) pen.penup() pen.goto(0,0) pen.rt(30) # Drawing the hour hand pen.penup() pen.goto(0,0) pen.color("blue") pen.setheading(90) angle = (h / 12) * 360 pen.rt(angle) pen.pendown() pen.fd(100) #drawing the minite hand pen.penup() pen.goto(0,0) pen.color("gold") pen.setheading(90) angle=( m / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(180) # Drawing the sec hand pen.penup() pen.goto(0,0) pen.color("yellow") pen.setheading(90) angle=( s / 60 ) * 360 pen.rt(angle) pen.pendown() pen.fd(50) while True: h=int(time.strftime("%I")) m=int(time.strftime("%M")) s=int(time.strftime("%S")) DrawC(h,m,s,pen) wn.update() time.sleep(1) pen.clear() #after exiting the loop a error will show ignore the error
true
e783154304256165ff443159d4181209454d2e08
kanishk333gupta/Elementary-Signals-in-continuous-and-discrete-time
/Exponential signal.py
1,765
4.34375
4
#EXPONENTIAL SIGNAL import numpy as np #Importing all definitions from the module and shortening as np import matplotlib.pyplot as mplot #Shortening as mplot ,an alias to call the library name ###CONTINUOUS x = np.linspace(-1, 2, 100) # 100 linearly spaced numbers from -1 to 2 xCT = np.exp(x) # Exponent function mplot.plot(x , xCT) # Plot a exponential signal mplot.xlabel('x') # Give X-axis label for the Exponential signal plot mplot.ylabel('exp(x)') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Continuous Time')#Give a title for the Exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the Exponential signal ###DISCRETE #Defining a function to generate DISCRETE Exponential signal # Initializing exponential variable as an empty list # Using for loop in range # and entering new values in the list # Ends execution and return the exponential value def exp_DT(a, n): exp = [] for range in n: exp.append(np.exp(a*range)) return exp a = 2 # Input the value of constant n = np.arange(-1, 1, 0.1) #Returns an array with evenly spaced elements as per the interval(start,stop,step ) x = exp_DT(a, n) # Calling Exponential function mplot.stem(n, x) # Plot the stem plot for exponential wave mplot.xlabel('n') # Give X-axis label for the Exponential signal plot mplot.ylabel('x[n]') # Give Y-axis label for the Exponential signal plot mplot.title('Exponential Signal in Discrete Time') # Give a title for the exponential signal plot mplot.grid() # Showing grid mplot.show() # Display the exponential signal
true
26864be554f52e6a3dc2cee5455de74599228579
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
355
4.15625
4
#!/usr/bin/python3 """ number_of_lines function module """ def number_of_lines(filename=""): """Get the numbers of lines into a text file Keyword Arguments: filename {str} -- [text file] """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: lines += 1 return lines
true
687e728de6afc1a57f322db9204a20957055b25c
angellovc/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
1,770
4.125
4
#!/usr/bin/python3 """ Matrix_divided functions module """ def matrix_divided(matrix, div): """ Make a division of all the elements into the matrix by a div number returns a new result list Args: matrix: matrix of dividends, just floats or integers are allowed div: that's represent the divisor, you cannot use 0, because division by zero in imposible """ is_matrix = all(isinstance(element, list) for element in matrix) if is_matrix is False: # check if matrix is really a matrix errors("no_matrix_error") length = len(matrix[0]) # check the corrent length for row in matrix: if length != len(row): errors("len_error") for row in matrix: # check if the elements into the matrix are numbers if len(row) == 0: errors("no_number_error") for element in row: if type(element) not in [int, float]: errors("no_number_error") if div == 0: errors("zero_error") if type(div) not in [int, float]: errors("div_not_number") new_matrix = [] def division(dividend): return round((dividend / div), 2) for i in range(0, len(matrix)): # make the matrix division new_matrix.append(list(map(division, matrix[i]))) return new_matrix def errors(error): # errors list if error == "len_error": raise TypeError("Each row of the matrix must have the same size") if error in ["no_number_error", "no_matrix_error"]: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") if error == "zero_error": raise ZeroDivisionError("division by zero") if error == "div_not_number": raise TypeError("div must be a number")
true
f0c1ca32d74b47203d48ebe82b5520069a1bdacc
angellovc/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
515
4.21875
4
#!/usr/bin/python3 """ read_lines module """ def read_lines(filename="", nb_lines=0): """read and print n number of lines into a text file Keyword Arguments: filename {str} -- [text file] (default: {""}) nb_lines {int} -- [n lines to read] (default: {0}) """ with open(filename, mode="r", encoding="UTF8") as f: lines = 0 for line in f: print(line, end="") lines += 1 if nb_lines > 0 and lines >= nb_lines: break
true
13ecec23ce620311c11f33da1ba3bba90cbd7fec
angellovc/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/100-print_tebahpla.py
241
4.4375
4
#!/usr/bin/python3 """ print the ascii alphabet in reverse using upper and lower characters""" for lower, upper in zip(range(122, 96, -2), range(89, 64, -2)): print("{}{}".format(chr(lower), chr(upper)), end='') # print ascii numbers
true
70a97b65e8cb2c963b0ae981b52ae5b191743d57
emmaAU/CSC280
/Random.py
575
4.125
4
#import random #print(random.random) import math print(math) a = int(input('enter coefficient for x**2 ')) b = int(input('enter b: ')) c = int(input('what is c?: ')) disc = b**2 - 4*a*c if disc > 0: root1 = -b + math.sqrt(disc) / 2*2 print(root1) root2 = -b - math.sqrt(disc) / 2*2 print(root2) elif disc == 0: root1 = root2 = -b / 2*2 else: print('no roots') product = 1 n = int(input('please enter a value you want to compute its factorial')) for i in range(2, n+1): product = product * i print('the factorial of', n, 'is, product')
true
57eb63f9f063deda592db8a58ebf420737f5f37c
etridenour/digitalCrafts
/classNotes/python/class7-2.py
2,516
4.3125
4
# class MyClass: # def SayHello(): # print("Hello there!") # MyClass.SayHello() class Person: def greet (self): #self points to object you are creating (ex. me, matt) print("Hello") me = Person() me.greet() matt = Person() matt.greet() # class MyClass: # Greeting = " " # lcass variable, available to all objects # def __init__(self): # print("Upon Initialization: Hello!") # def instance_method(self): #creates space to be filled in, self has to be there to let it know what to reference # print("Hello {0}".format(self.Greeting)) # def class_method(): # this is a class method because it doesn't have self # print("Hello {0}".format(self.Greeting)) # digitalCrafts = MyClass() # flatIrons = MyClass() # flatIrons.instance_method() # MyClass.Greeting = 'Eric' #set global variable equal to greeting, can change the name and will change in output # digitalCrafts.instance_method() # utAustin = MyClass() # utAustin.instance_method() # # digitalCrafts.instance_method() # # # MyClass.class_method() #calling a class method, this needs myClass before # # test.class_method() # class Person: # GlobalPerson = "Zelda" # global variable # def __init__ (self, name): # self.name = name #set instance variable # print(name) # def greet (self, friend): # instance method # print("Hello {} and {} and {}".format(self.name, friend, self.GlobalPerson)) # matt = Person('Fisher') # matt.greet("Travis") # person1 = Person('Hussein') # person1.greet("Skyler") # Person.GlobalPerson = 'Eric' # matt.greet('Travis') # person1.greet('Skyler') # class Person: # def __init__ (self, name): #constructor # self.name = name # self.count = 0 # def greet (self): # self._greet() # def _greet (self): # self.count += 1 # if self.count > 1: # print("Stop being so nice") # self.__reset_count() # else: # print("Hello", self.name) # def __reset_count(self): # self.count = 0 # matt = Person('Fisher') # matt.greet() #calling function # matt.greet() # matt.greet() # travis = Person('Ramos') #only prints hello ramos because it is it's own thing, even though went through same class # travis.greet() # class Animal: # def __init__ (self, name): # self.name = name # class Dog (Animal): #what you inherit goes in (), in this case animal # def woof (self): # print("Woof") # class Cat (Animal): # def meow (self): # print("Meow") super().__init__(power, health)
true
4f7ff64e0ec87b80e8689e8d484f9c0cefd3fbdf
ParkerCS/ch18-19-exceptions-and-recursions-aotoole55
/recursion_lab.py
1,152
4.78125
5
''' Using the turtle library, create a fractal pattern. You may use heading/forward/backward or goto and fill commands to draw your fractal. Ideas for your fractal pattern might include examples from the chapter. You can find many fractal examples online, but please make your fractal unique. Experiment with the variables to change the appearance and behavior. Give your fractal a depth of at least 5. Ensure the fractal is contained on the screen (at whatever size you set it). Have fun. (35pts) ''' import turtle color_list = ['red', 'yellow', 'orange', 'blue'] def circle(x, y, radius, iteration): my_turtle = turtle.Turtle() my_turtle.speed(0) my_turtle.showturtle() my_screen = turtle.Screen() #Color my_turtle.pencolor(color_list[iteration % (len(color_list[0:4]))]) my_screen.bgcolor('purple') #Drawing my_turtle.penup() my_turtle.setposition(x, y) my_turtle.pendown() my_turtle.circle(radius) #Recursion if radius <= 200 and radius > 1: radius = radius * 0.75 circle(25, -200, radius, iteration + 1) my_screen.exitonclick() circle(25, -200, 200, 0)
true
6efd603459989c8fa85b848c52d05a96a2ff8a74
peluza/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
719
4.5625
5
#!/usr/bin/python3 """3-say_my_name """ def say_my_name(first_name, last_name=""): """say_my_name Arguments: first_name {str} -- the value is the first_name Keyword Arguments: last_name {str} -- the value is the las_name (default: {""}) Raises: TypeError: first_name must be a string TypeError: last_name must be a string Returns: str -- My name is <first name> <last name> """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") result = print("My name is {} {}".format(first_name, last_name)) return result
true
bbd1072f2a5f859b44c7b4acd7daa5a7ae8b6c48
misaka-umi/Software-Foundamentals
/07 stacks/64 stacks-reverse sentence.py
1,846
4.125
4
class Stack: def __init__(self): self.__items = [] def pop(self): if len(self.__items) > 0 : a= self.__items.pop() return a else: raise IndexError ("ERROR: The stack is empty!") def peek(self): if len(self.__items) > 0 : return self.__items[len(self.__items)-1] else: raise IndexError("ERROR: The stack is empty!") def __str__(self): return "Stack: {}".format(self.__items) def __len__(self): return len(self.__items) def clear(self): self.__items = [] def push(self,item): self.__items.append(item) def push_list(self,a_list): self.__items = self.__items + a_list def multi_pop(self, number): if number > len(self.__items): return "False" else: for i in range(0,number): self.__items.pop() return "True" def copy(self): a=Stack() for i in self.__items: a.push(i) return a def __eq__(self,other): if not isinstance(other,Stack): return "False" else: if len(other) != len(self): return "False" else: a = other.copy() b = self.copy() #self调用的就是栈本身 for i in range(len(a)): if a.pop() != b.pop(): return "False" return "True" def reverse_sentence(sentence): a = Stack() b = sentence.split(" ") c = '' for i in range(len(b)): a.push(b[i]) for i in range(len(b)): if c == '': c= a.peek() else: c = c+" " + a.peek() a.pop() return c print(reverse_sentence('Python programming is fun '))
false
428fd8714cd7c2542af1000822bf90da9dd58847
linleysanders/algorithms
/Homework Week One (Average of Averages)/Linley Sanders Week One Homework.py
2,609
4.28125
4
# coding: utf-8 # # Lede Algorithms -- Assignment 1 # # In this assignment you will use a little algebra to figure out how to take the average of averages. # In[1]: import pandas as pd import matplotlib.pyplot as plt import requests get_ipython().run_line_magic('matplotlib', 'inline') # First, read in the titanic.csv data set. # In[2]: df = pd.read_csv("titanic.csv") df.head() # Compute the average survival rate (mean of the `survived` column) # In[3]: df['survived'].mean() # Now compute the average survival rates of the male and female 1st, 2nd, and 3rd class passengers (six groups in total) # In[31]: df.groupby(by='gender')['survived'].count() # In[32]: df.groupby(by='gender')['survived'].value_counts() # ## Male Survival Rate: 16.70% # ## Female Survival Rate: 66.30% # In[35]: 142/850 # In[34]: 307/463 # In[37]: df.groupby(by='pclass')['survived'].count() # In[36]: df.groupby(by='pclass')['survived'].value_counts() # ## First Class Survival Rate: 59.93% # ## Second Class Survival Rate: 42.5% # ## Third Class Survival Rate: 19.26% # In[38]: 193/322 # In[39]: 119/280 # In[40]: 137/711 # Compute the average of these six averages. Is it the same as the the overall average? # In[43]: #It's not the same as the overall average—it is higher (34.19+16.70+66.30+59.93+42.5+19.26)/(6) # How would you compute the overall average from the average of averages? Start with the formulas # # $$mean = \frac{\sum_{i=1}^N x_i}{N}$$ # # for the overall mean, where $x_i$ is data value $i$ and $N$ is the total number of values, and # # $$mean_k = \frac{\sum_{i=1}^{N_k} xk_i}{N_k}$$ # # is the mean of group $k$, where $xk_i$ is value $i$ of group $k$ and $N_k$ is the number of values in group $k$, and # # $$N = \sum_{i=1}^M N_k$$ # # relates the total number of values $N$ to the number of values in each of the $M$ groups. # # Your task is to derive a formula that computes $mean$ using only $mean_k$, the $N_k$, and $N$. Note: this question is not asking you to write code! Rather, you must answer two questions: # # - What is the correct formula? # - How can we derive this formula starting from the formulas above? # ## Answer / Response: # # The first formula is the calculation overall for mean. The second formula is the calculation for a group (a column), as the extra variable K. Big N is equal to the sum of the values, and Nk would give the total number of people in a column. I think the solution would be to take 1/6 of each percentage and # Now use this formula to calculate the overall mean. Does it match?
true
d333b5c8fa654a867c5e54f599f2ca5a5c68746d
zhezhe825/api_test
/cases/test_1.py
1,297
4.5
4
''' unittest框架:单元测试框架,也可做自动化测试,python自带的 unittest:管理测试用例,执行用例,查看结果,生成 html 报告(多少通过,多少失败 ) 自动化:自己的代码,验证别人的代码 大驼峰命名:PrintEmployeePaychecks() 小驼峰:printEmployeePaychecks() 下划线命名:print_employee_paychecks() 类:大驼峰命名 其他:小驼峰,下划线命名 class:测试的集合,一个集合又是一个类 unittest.TestCase:继承 继承的作用:子类继承父类(TestExample 继承 TestCase),父类有的,子类都有 ''' ''' self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") 断言失败可用:msg="。。。" 给出提示信息 .通过 F 失败:开发的BUG E:你自己的代码的BUG ''' import unittest # print(help(unittest)) # help:查看帮助文档 class TestExample(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) # self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main()
false
cbd8f93e9f6e1adbeebe0d612865c3d306ada0a1
ritaly/python-6-instrukcje-warunkowe
/Odpowiedzi/2.py
988
4.125
4
# -*- coding: utf8 -*- """ Do kalkulatora BMI z lekcji "Python 1 zabawy w konsoli" dodaj sprawdzanie czy BMI jest prawidłowe Niedowaga | < 18,5 Waga normaln | 18,5 – 24 Lekka nadwaga | 24 – 26,5 Nadwaga | > 26,5 W przypadku nadwagi sprawdź czy występuje otyłość: Otyłość I stopnia | 30 – 35 Otyłość II stopnia | 30 – 40 Otyłość III stopnia | > 40 """ print("Podaj wagę w kg: ") weight = float(input()) print("Podaj wzrost w cm: ") height = float(input())/100 BMI = weight / (height ** 2) print("Twoje bmi wynosi:", round(BMI, 2)) if (BMI < 18.5): print("Niedowaga") elif (18.5 <= BMI < 24): print("Waga prawidłowa") elif (24 <= BMI < 26.5): print("Lekka nadwaga") else: print("Nadwaga") if (30 >= BMI > 35): print("Otyłość I stopnia") elif (35 >= BMI > 40): print("Otyłość II stopnia") else: print("Otyłość III stopnia")
false
61a496dde5f1d6faa1dfb14a79420f3730c0727f
DMRathod/_RDPython_
/Coding Practice/Basic Maths/LeapYear.py
441
4.21875
4
# leap year is after every 4 years, divisible by 4. # Every Century years are not leap years means if it is divisible by 100. # we need to confirm if it is divisible by 400 or not. year = int(input("Enter The Year :")) if(year%4 == 0): if(year%100 == 0): if(year%400 == 0): print(str(year) + "is Leap Year") else: print(str(year)+ "is Leap Year") else: print(str(year) + " is NOT Leap Year")
false
fbb3938b667cba8afe5144c023cacbd833028f03
crashtack/exercism
/python/clock/clock.py
1,144
4.34375
4
class Clock(object): """ A Clock class that ignores date """ def __init__(self, hours=0, minutes=0): """ Initialize the Clock object """ self.hours = hours % 24 self.minutes = minutes self.time_min = (self.hours * 60) + self.minutes self.time_min = self.time_min % 1440 def add(self, minute=0): """ Add minutes to the time and check for overflow """ self.time_min += minute self.time_min = self.time_min % 1440 return self.__str__() def __eq__(self, other): """ Check if time_min is equal """ if isinstance(other, self.__class__): return self.time_min == other.time_min else: return False def __ne__(self, other): """ Check if time_min is not equal """ return not self.__eq__(other) def __hash__(self): """ Return a hash of the time value """ return hash(self.time_min) def __str__(self): """ Returns the hh:mm time format """ return '{:02d}:{:02d}'.format( int(self.time_min / 60) % 24, self.time_min % 60 )
true
deb0106dadea39101d8c40357c3f41f9383a9937
GarryK97/Python
/Hashtable/Task5.py
2,715
4.4375
4
from Task3 import HashTable def read_file_removesp(file_name): """ Read a text file and convert it to a list of words without any special characters. :param file_name: File to read :return: the list of words """ f = open(file_name, 'rt', encoding='UTF8') file_list = [] for line in f: line = line.strip() # Remove whitespaces line = line.split(" ") # Split by words for i in range(len(line)): word_nosp = "" # String that will store word with no special character line[i] = line[i].lower() # Lower the word to make search easy for char in line[i]: # for each character in word, if char.isalpha(): # if the character is not special character (if it is alphabet), word_nosp += char # Add it to word_nosp if word_nosp != "": # To prevent adding white spaces and already existing words file_list.append(word_nosp) # Append the word with no special character f.close() return file_list book1 = read_file_removesp("Book1.txt") book2 = read_file_removesp("Book2.txt") book3 = read_file_removesp("Book3.txt") book_hashtable = HashTable(399989, 1091) # Making a hash table for books in [book1, book2, book3]: for word in books: try: count = book_hashtable[word] # if the word exists in hash table, count will store the value of it book_hashtable[word] = count + 1 # + 1 count except KeyError: book_hashtable[word] = 1 # If the word does not exist in hash table, it means a new word needs to be added # Making a non-duplicate words list words_list = [] for books in [book1, book2, book3]: for word in books: if word not in words_list: words_list.append(word) # Finding Maximum max_count = 0 max_word = "" for word in words_list: if book_hashtable[word] > max_count: # if word count > current maximum word count, max_count = book_hashtable[word] # Change to new max count and word max_word = word # Finding common, uncommon, rare words common_words = [] uncommon_words = [] rare_words = [] for word in words_list: # Zipf's law in simple python code if book_hashtable[word] > (max_count / 100): common_words.append(word) elif book_hashtable[word] > (max_count / 1000): uncommon_words.append(word) else: rare_words.append(word) print("Number of common words : " + str(len(common_words))) # Prints the result print("Number of uncommon words : " + str(len(uncommon_words))) print("Number of rare words : " + str(len(rare_words)))
true
606de1aa9e681af56f022880698088b3ea58904d
nidakhawar/PracticePythonExcercises
/AverageOfSubjects.py
510
4.1875
4
biology=float(input("Please input your Biology score:")) chemistry=float(input("Please input your Chemistry score:")) physics=float(input("Please input your Physics score:")) if biology<40: print("Fail") if chemistry<40: print("Fail") if physics<40: print("Fail") else: score=((biology+chemistry+physics)/3) if score >=70: print("first") elif score>=60: print("2.1") elif score>=50: print("pass") elif score>=40: print("pass") else: print("fail")
true
976cc8ab3327128b679d3d205e8c2dc1b2daae0b
zacharykaczor/Small-Programs
/odd_numbers.py
535
4.1875
4
# Based on https://www.youtube.com/watch?v=LkIK8f4yvOU. # The Difference of Two Squares. number = int(input("Please enter a positive odd number: ")) while number % 2 == 0 or number < 0: number = int(input( "Please enter a positive number: " if number < 0 else "Please enter an odd number: " )) root_2 = number // 2 root_1 = root_2 + 1 print(f"The roots are { root_1 } and { root_2 }.") print(f"The squares are { root_1 ** 2 } and { root_2 ** 2 }.") print(f"{ root_1 ** 2 } - { root_2 ** 2 } = { number }.")
true
cc84abe6637d76e56a7ac2c958ebd7c8a808c1c1
ProspePrim/PythonGB
/Lesson 2/task_2_1.py
628
4.125
4
#Создать список и заполнить его элементами различных типов данных. #Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. #Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. list_a = [5, "asdv", 15, None, 10, "asdv", False] def type_list(i): for i in range(len(list_a)): print(type(list_a[i])) return type_list(list_a)
false
bce8bf614aca3883f2ac618caa8f00bc32a5dd73
costacoz/python_design_patterns
/behavioral/iterator.py
1,296
4.5
4
# Iterators are built into Python. # It can be engaged, using 'iter(arg*)' function # arg* - can be list, tuple, dic, set and string. # Below is the example of using it. # fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'} # fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') # fruits_tuple = ['apple', 'blueberry', 'cherry', 'pineapple'] fruits_tuple = 'apples' fruits_iterator = iter(fruits_tuple) print(next(fruits_iterator)) print(next(fruits_iterator)) print(next(fruits_iterator)) print(fruits_iterator.__next__()) # Loop through an iterator fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') for f in fruits_tuple: print(f) # # To create an iterator manually we need to implement iter and next # in __iter__ we initialize iterator, same as in __init__, and return iterator class Iterator: def __iter__(self): self.a = 2 return self # must always return iterator object def __next__(self): if self.a < 10: x = self.a self.a += 1 return x else: raise StopIteration # to stop iterator in loop iterable_obj = Iterator() # iterator = iter(iterable_obj) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) for i in iterable_obj: print(i)
true
2724d92157d61f930c089931f2b55042dcfe9f0e
plaer182/Python3
/FizzBuzz(1-100)(hw2).py
354
4.15625
4
number = int(input('Enter the number: ')) if 0 <= number <= 100: if number % 15 == 0: print("Fizz Buzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) elif number < 0: print("Error: unknown symbol") else: print("Error: unknown symbol")
false
db6a67f488a152ccc2768d3d24728afb318f10de
CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles
/comprehension.py
2,101
4.3125
4
"""Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what number was choosen by the bot.""" import random #import the random module guessesTaken = 0 #assign 0 to guessesTaken variable print('Hello! What is your name?') #print out this sentence myName = input() #assign a user input to myName variable number = random.randint(1, 20) #assign a randomly choosen integer(between 1 and 20) to number variable print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #printing out this sentence with the given name while guessesTaken < 6: #loop while the guessesTaken variable is less then 6 print('Take a guess.') #print out this sentence guess = input() #assign a user input to guess variable guess = int(guess) #making type conversion changing the value of the guess variable to integer from string guessesTaken += 1 #increasing the value of the guessesTaken by 1 if guess < number: #doing something if guess value is lower than number value print('Your guess is too low.') #if its true print out this sentence if guess > number: #doing something if the guess value is higher than the number value print('Your guess is too high.') #if its true print out this sentence if guess == number: #doing something if the guess value is equal with the number value break #if its true the loop is immediately stop if guess == number: #doing something if the guess value is equal with the number value guessesTaken = str(guessesTaken) #making type conversion changing the value of the guessesTaken variable to string from integer print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') #print out how many try needed to the user to guess out if guess != number: #doing something if guess value is not equal with number value number = str(number) #making type conversion changing the value of the number variable to string from integer print('Nope. The number I was thinking of was ' + number) #print out the randomly choosen number
true
07bd3a329eafee4c2398a08943aeb985a282b6f2
onionmccabbage/pythonTrainingMar2021
/using_ternary.py
474
4.40625
4
# Python has one ternary operator # i.e. an operator that takes THREE parts # all other operators are binary, i.e. they take TWO parts # e.g. a = 1 or 3+2 # the ternary operator works like this # 'value if true' 'logical condition' 'value if false' x = 6 y = 5 print("x" if x>y else "y") # alternative syntax for the ternary operator nice = False personality = ("horrid", "lovely")[nice] # spot the index 0 or 1 print("My cat is {}".format(personality)) #
true
375b0579cdbe45e4a66d954f8d5e767f8ef70546
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 2/Task 5.py
261
4.28125
4
# Write a list comprehension which, from a list, generates a lowercased version of each string # that has length greater than five strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence'] for x in strings: if len(x) > 5: print(x.lower())
true
23d0b02ba64c2aca3becf467d88c692109aab9f8
patnaik89/string_python.py
/condition.py
1,696
4.125
4
""" Types of conditional statements:- comparision operators (==,!=,>,<,<=,>=) logical operators (and,or,not) identity operators (is, is not) membership operators (in, not in) """ x, y = 2,9 print("Adition", x + y) print("multiplication", x * y) print("subtraction", x - y) print("division", x/y) print("Modular", x%y) print("floor division", x//y) print("power: ", x ** y) # finding a 'number' is there in given list or not list1 = [22,24,36,89,99] if 24 in list1: print(True) else:print(False) # examples on if elif and else conditions if x>y: print("x is maximum") elif y>x: print("y is maximum") else: print("both are equal") # Finding the odd and even numbers in given list list1 = [1,2,3,5,6,33,24,67,4,22,90,99] for num in range(len(list1)): if num % 2 == 0: print("Even Numbers are:", num,end=", ") else: print("The Odd Numbers are:", num) # Dynamic list using loops list2 = [] for number in range(10): if number % 2 == 0: # finding Even numbers in given range list2.append(number) print("Even numbers are:", list2) # finding all odd numbers within range 40 list1=[] for num in range(40): if num % 2 != 0: list1.append(num) print("odd numbers are", list1) # Dynamic set set1 = set() for number in range(10): set1.add(number) print("numbers in given range are:",set1) # printing duplicate elements list1=[1,1,2,4,4,5,44,56,2,99,49,99] l=sorted(set(list1)) # removing duplicate elements print(l) dup_list=[] for number in range(len(l)): if (list1.count(l[number]) > 1): dup_list.append(l[number]) print("duplicate elements in a list are: ",dup_list)
false
f21b75948484cc34cea7d9d166dc47e72611749d
liadbiz/Leetcode-Solutions
/src/python/degree_of_array.py
1,373
4.15625
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. """ class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ import collections import operator fre_dict = collections.Counter(nums).most_common() max_fre = max(fre_dict, key = operator.itemgetter(1))[1] def fre_sub(i): return len(nums) - nums.index(i) - nums[::-1].index(i) return min(fre_sub(i[0]) for i in fre_dict if i[1] == max_fre) if __name__ == "__main__": nums1 = [1, 2, 2, 3, 1] nums2 = [1,2,2,3,1,4,2] print(Solution().findShortestSubArray(nums1)) print(Solution().findShortestSubArray(nums2))
true
ea03689b8be9bd5fab6af7d4e20d2ceae0d8e88b
reesporte/euler
/3/p3.py
534
4.125
4
""" project euler problem 3 """ def is_prime(num): if num == 1: return False i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True def get_largest_prime_factor(num): largest = 0 i = 2 while i*i <= num: if num%i == 0: if is_prime(i): largest = i i += 1 return largest def main(): print("the largest prime factor is:", get_largest_prime_factor(600851475143)) if __name__ == '__main__': main()
false
bbeb124cd35e865c17ae7a9691022031b81ba553
jonahtjandra/sudoku-solver
/Sudoku.py
2,939
4.15625
4
class Sudoku: def __init__(self, board:'list[list]') -> None: if (len(board) != 9 or len(board[0]) != 9): raise "Expected a 9 by 9 board" self.board = board self.iterations = [] # for printing out the 2d list representation of the board def display(self, board:'list[list]'): if (len(board) != 9): print("Not a valid 9x9 sudoku board!") return x = 0 for i in range(len(board)+4): if (i==0 or i==4 or i==8 or i==12): print('-------------------------') continue y = 0 for j in range(len(board)+4): if (j == 0 or j==4 or j==8): print('|', end=' ') elif (j == 12): print('|') else: print(board[x][y], end=' ') y += 1 x += 1 # method to check if a certain number, n, is valid to be # place at a certain x and y coordinate in the board def isPossible(self, x:int, y:int, n:int) -> bool: if (x > 8 and y > 8 and n >= 0 and n <= 9): return False #horizontal check for i in range(9): if (self.board[x][i] == n and i != y): return False #vertical check for i in range(9): if (self.board[i][y] == n and i != x): return False #square check square_x = x // 3 square_y = y // 3 for i in range(3): for j in range(3): if (self.board[square_x * 3 + i][square_y * 3 + j] == n and x != square_x * 3 + i and y != square_y * 3 + j): return False #possible placement return True # Method to check if solution is correct def isSolution(self) -> bool: for i in range(9): for j in range(9): if (not(self.isPossible(self.board, i, j, self.board[i][j]))): return False return True # Method to find the next empty coordinate in the board # Returns false if there are no empty space left (solved) def nextEmpty(self, loc:list) -> bool: for i in range(9): for j in range(9): if (self.board[i][j] == '.'): loc[0] = i loc[1] = j return True return False # Method to solve the board # Returns false if board is not solveable def solve(self) -> bool: loc = [0,0] if (not self.nextEmpty(loc)): return True i = loc[0] j = loc[1] for n in range(1,10): if (self.isPossible(i, j, n)): self.board[i][j] = n self.display(self.board) if (self.solve()): return True self.board[i][j] = '.' return False
true
53da6c914c6b7139abf47e3b214b47725e93c50b
comalvirdi/CPE101
/LAB4/loops/cubesTable.py
1,518
4.3125
4
# CPE 101 Lab 4 # Name: def main(): table_size = get_table_size() while table_size != 0: first = get_first() increment = get_increment() show_table(table_size, first, increment) table_size = get_table_size() # Obtain a valid table size from the user def get_table_size(): size = int(input("Enter number of rows in table (0 to end): ")) while (size) < 0: print ("Size must be non-negative.") size = int(input("Enter number of rows in table (0 to end): ")) return size; # Obtain the first table entry from the user def get_first(): first = int(input("Enter the value of the first number in the table: ")) while (first) < 0: print ("First number must be non-negative.") first = int(input("Enter the value of the first number in the table: ")) return first; def get_increment(): increment = int(input("Enter the increment between rows: ")) while (increment) < 0: print ("Increment must be non-negative.") increment = int(input("Enter the increment between rows: ")) return increment; # Display the table of cubes def show_table(size, first, increment): print ("A cube table of size %d will appear here starting with %d." % (size, first)) print ("Number Cube") sum = 0 for num in range (first, first+ size * increment, increment): print ("{0:<7} {1:<4}" .format(num, num**3)) sum += num**3 print ("\nThe sum of cubes is:", sum, "\n") if __name__ == "__main__": main()
true
e9cb86ab9b68ed4b6f0c061f48629cb0eb270316
lguychard/loispy
/src/loispy/interpreter/procedure.py
2,279
4.28125
4
from environment import Environment class Procedure(object): """ Represents a loisp procedure. A procedure encapsulates a body (sequence of instructions) and a list of arguments. A procedure may be called: the body of the procedure is evaluated in the context of an environment, and given """ def __init__(self, env, args, body, name=""): """ @param Environment env @param list[str] args @param function body @param str name """ self.env = env self.args = args # Check now if the procedure has variable arguments self.numargs = -1 if len(args) >= 1 and "..." in args[-1] else len(self.args) if self.numargs == -1: self.numpositional = len(self.args) -1 self.positional = self.args[:self.numpositional] self.vararg = self.args[-1].replace("...", "") self.body = body self.name = name def __call__(self, *argvals): """ 'the procedure body for a compound procedure has already been analyzed, so there is no need to do further analysis. Instead, we just call the execution procedure for the body on the extended environment.' [ABELSON et al., 1996] """ call_env = Environment(self.pack_args(argvals), self.env) return self.body.__call__(call_env) def pack_args(self, argvals): """ Return a dict mapping argument names to argument values at call time. """ if self.numargs == -1: if len(argvals) <= self.numpositional: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.positional, argvals[:self.numpositional])) _vars.update({self.vararg : argvals[self.numpositional:]}) else: if len(argvals) != self.numargs: raise Exception("Wrong number of arguments for '%s' (%d)" % (self.name, len(argvals))) _vars = dict(zip(self.args, argvals)) return _vars def __str__(self): return "<Procedure %s>" % self.name if self.name else "<Procedure>" def __repr__(self): return self.__str__()
true
2fa3fbd312b86064da4f77d85dd226575de9dcaf
Heisenberg27074/Web-Scraping-with-Python3
/lists/maxmin.py
724
4.3125
4
#Rewrite the program that prompts the user for a list of #numbers and prints out the maximum and minimum of the numbers at #the end when the user enters “done”. Write the program to store the #numbers the user enters in a list and use the max() and min() functions to #compute the maximum and minimum numbers after the loop completes. lst=list() while(1): snum=input("Enter a number") if snum =='done': break try: num=float(snum) lst.append(num) except:print('Please enter a number not anything else!!!') if len(lst)<1:print("There are no items to compare inside list, please enter some data") else: print('Maximum:',max(lst)) print('Minimum',min(lst))
true