blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c42cbd069f0767ddf4080718265b98ae6c5a8c98 | viktapas/AlgoCasts_Python_JS | /exercises/fizzbuzz/index.py | 772 | 4.5625 | 5 | # --- Directions
# Write a program that console logs the numbers
# from 1 to n. But for multiples of three print
# 'fizz' instead of the number and for the multiples
# of five print 'buzz'. For numbers which are multiples
# of both three and five print 'fizzbuzz'.
# --- Example
# fizzBuzz(5);
# 1
# 2
# fizz
# 4
# buzz
def fizzbuzz (n): # n ---> whole number
a = int(n)
i = 1
while i <= a:
if i % 3 == 0 and i % 5 == 0: # check if number is divisible by 3 and 5 both
print 'fizzbuzz'
elif i % 3 == 0: # check if number is divisible by 3
print 'fizz'
elif i % 5 == 0: # check if number is divisible by 5
print 'buzz'
else:
print i
i += 1 # increment count
x = raw_input('Enter whole number: ')
result = fizzbuzz(x) | false |
8e616784d502fdcb9f874d394e8129137aaec025 | yungjas/Python-Practice | /even.py | 315 | 4.28125 | 4 | #Qn: Given a string, display only those characters which are present at an even index number.
def print_even_chars(str_input):
for i in range(0, len(str_input), 2):
print(str_input[i])
text = "pynative"
print("Original string is " + text)
print("Printing only even index chars")
print_even_chars(text) | true |
83655407a288aa3d7c0192bc936e40eaaee5e22e | not-so-daily-practice/top-80-interview-algorithms | /strings_and_arrays/reverse_array_except_special.py | 554 | 4.15625 | 4 | def reverse_except_special(arr):
"""
Given an array, reverse it without changing the positions of special characters
:param arr: array to reverse
:return: reversed array
"""
arr = list(arr)
left = 0
right = len(arr) - 1
while left < right:
if not arr[left].isalpha():
left += 1
elif not arr[right].isalpha():
right -= 1
else:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
arr = "".join(arr)
return arr
| true |
1ce26ff860b909d7f61db0e82b957103bc70519b | akshitsarin/python-files | /singlylinkedlistfinal.py | 1,587 | 4.34375 | 4 | # singly linked list final
class Node:
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
class LinkedList:
def __init__(self):
self.head = None # initialise head
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAfter(self, prev_node, new_data):
if prev_node is None:
print "The given previous node must inLinkedList."
return
new_node = Node(new_data)
new_node.next = prev_node.next
prev_node.next = new_node
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while (last.next):
last = last.next
last.next = new_node
def printList(self):
temp = self.head
while (temp):
print temp.data,
temp = temp.next
if __name__=='__main__':
llist = LinkedList()
# inserting 6, updated linked list : 6->None
llist.append(6)
# inserting 7 at the beginning, updated linked list : 7->6->None
llist.push(7)
# inserting 1 at the beginning, updated linked list : 1->7->6->None
llist.push(1)
# inserting 4 at the end, updated linked list : 1->7->6->4->None
llist.append(4)
# inserting 8 after 7, updated linked list : 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
print 'Linked List :',
llist.printList() | true |
0cce8f2b81b2b0956c2fb2dca7444a352684d6b2 | supvolume/codewars_solution | /5kyu/move_zeros.py | 389 | 4.125 | 4 | """ solution for Moving Zeros To The End challenge
move zero to the end of the array"""
def move_zeros(array):
no_zero = []
zero = []
for a in array:
if a == "0":
no_zero.append(a)
elif (str(a) == "0.0" or str(a) == "0" or a == 0) and str(a) != "False":
zero.append(a)
else:
no_zero.append(a)
return no_zero+zero | false |
68863a0fd52ddce4d306749ee22ca4e81cde8ba3 | provishalk/Python | /Linked List/LinkedList.py | 1,701 | 4.15625 | 4 | class LinkedList:
head = None
class Node:
def __init__(self, x):
self.value = x
self.next = None
def insert(self,value):
toAdd = self.Node(value)
if self.head == None:
self.head = toAdd
return
temp = self.head
while temp.next != None:
temp = temp.next
temp.next = toAdd
def display(self):
temp = self.head
if self.head == None:
print("ERROR : You are trying to Print Empty Linked List")
return
while temp.next != None:
print(temp.value)
temp = temp.next
print(temp.value)
def delete(self,x):
temp = self.head
if self.head == None:
print("ERROR : You are trying to Delete Empty Linked List")
return
if temp.value == x:
self.head = temp.next
return
while temp.next.value != x:
temp = temp.next
if temp.next == None:
return
temp.next= temp.next.next
def count(self):
x = 0
temp = self.head
if self.head == None:
return x
while temp.next != None:
x = x+1
temp = temp.next
return x+1
def help(self):
print(""" 1.Use insert(value) to Insert Value in linked list
2.Use delete(Value) to Delete from Node
3.Use count() to count Number of Elements
4.Use display() to Display all Elements of Node
""")
obj = LinkedList()
#print(obj.count())
for x in range(0,10,1):
obj.insert(x+1)
obj.help()
#obj.delete(9)
#print(obj.count())
#obj.display() | true |
76f9c27e3ddcc3afc6e800a05882ff649f7d1ac2 | tristan1049/Dungeon-for-the-Bored | /Illustrations.py | 2,859 | 4.15625 | 4 | def dice1():
"""
Purpose: To make an illustration for the 1-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| |",
"| * |",
"| |",
"|_______|"]
return rv
def dice2():
"""
Purpose: To make an illustration for the 2-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| * |",
"| |",
"| * |",
"|_______|"]
return rv
def dice3():
"""
Purpose: To make an illustration for the 3-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| * |",
"| * |",
"| * |",
"|_______|"]
return rv
def dice4():
"""
Purpose: To make an illustration for the 4-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| * * |",
"| |",
"| * * |",
"|_______|"]
return rv
def dice5():
"""
Purpose: To make an illustration for the 5-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| * * |",
"| * |",
"| * * |",
"|_______|"]
return rv
def dice6():
"""
Purpose: To make an illustration for the 6-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| * * |",
"| * * |",
"| * * |",
"|_______|"]
return rv
def match(roll_list):
"""
Inputs: Takes in a list of dice roll integers
Purpose: To match each number of a dice roll to an illustration
Output: The list of strings of the illustration
"""
rv = []
dice_list = []
for num in roll_list:
if num == 1:
dice_list.append(dice1())
elif num == 2:
dice_list.append(dice2())
elif num == 3:
dice_list.append(dice3())
elif num == 4:
dice_list.append(dice4())
elif num == 5:
dice_list.append(dice5())
elif num == 6:
dice_list.append(dice6())
# Join 10 dice strings at a time as a line
num_lines = ((len(dice_list)-1) // 10) + 1
for line in range(num_lines):
# Iterate through each row of the dice illustrations for line
for j in range(len(dice_list[10*line])):
row = ''
# Iterate through each die for current row, joining all dice strings
# for that row into one string for correct printing
for i in range(10*line, min(len(dice_list), 10*line + 10)):
row += dice_list[i][j]
row += ' '
rv.append(row)
return rv
| false |
ba7cb756981686727f4c3c2722b3ac59fbf9d608 | yossibaruch/learn_python | /learn_python_the_hard_way/ex3.py | 855 | 4.34375 | 4 | # print some output
print "I will now count my chickens:"
# order of math
print "Hens", 25+30/6
# order of math
print "Roosters", 100-25*3%4
# print something
print "Now I will count the eggs:"
# math order, first multiply/div then add/sub, also what / and % do
print 3+2+1-5+4%2-1/4+6
# print something
print "Is it true that 3 + 2 < 5 - 7?"
# output the statement
print 3 + 2 < 5 - 7
# print something with statement
print "What is 3 + 2?", 3 + 2
# print with calculation
print "What is 5 - 7?", 5 - 7
# print with calculation
print "Oh, that's why it's False."
print "How about some more."
# print something with statement
print "Is it greater?", 5 > -2
# print something with statement
print "Is it greater or equal?", 5 >= -2
# print something with statement
print "Is it less or equal?", 5 <= -2
print 7/4
print 7.0/4.0
| true |
ece25778d428f34d312ed89566a52d317d4c3bf5 | yossibaruch/learn_python | /non-programmers/13-braces.py | 1,447 | 4.3125 | 4 | import string
print("""
# Iterate on characters from string
# Find opening braces and "remember" them in order
# Find closing braces and make sure it fits the last opening braces
# If "yes", forget last opening braces
# If "no", return False
# If memory of opening braces is not empty - return False
# else return True
""")
def hebrew_braces(braces_list):
braces_work = []
for c in braces_list:
if c in '{[(':
braces_work.append(c)
if c in '}])':
try:
b = braces_work.pop()
except IndexError:
return False
if (b == '(' and c == ')') or (b == '[' and c == ']') or (b == '{' and c == '}'):
continue
else:
print("Not balanced braces")
return False
print("Balanced braces")
return True
while True:
try:
bracesWithChars = str(input("Please enter a string with braces:"))
except ValueError:
print("This value is erroneous, please mend")
continue
break
whatToRemove = string.printable
for bra in ['{', '}', '[', ']', '(', ')']:
whatToRemove = whatToRemove.replace(bra, '')
bracesOnly = bracesWithChars
for let in list(whatToRemove):
bracesOnly = bracesOnly.replace(str(let), '')
# print(bracesWithChars, bracesOnly, whatToRemove)
bracesOnly = list(bracesOnly)
print(bracesOnly)
hebrew_braces(bracesOnly)
| true |
4dbef496f2b1a7f6a40083bb1851101865b2a8f0 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/examples/VehicleManager.py | 1,723 | 4.15625 | 4 | class Vehicle(object):
def __init__(self, brand, model, km, service_date):
self.brand = brand
self.model = model
self.km = km
self.service_date = service_date
def show(self):
print "{} {} {} {}".format(self.brand, self.model, self.km, self.service_date)
if __name__ == '__main__':
All_Vehicles = [
Vehicle("Audi", "A5", "14000", "2017.01.01"),
Vehicle("Renault", "Espace", "32000", "2017.03.01")
]
while True:
answer = raw_input("Please select an option.\n"
"(1) Show vehicles\n"
"(2) Edit vehicle\n"
"(3) Add vehicles\n"
"(q) Quit Program\n")
if answer.lower() == "q":
# todo: save cars list to file
print "Exiting program..."
break
elif answer == "1":
print "Showing all vehicles..."
for vehicle in All_Vehicles:
vehicle.show
print vehicle.brand, vehicle.model, vehicle.km, vehicle.service_date
elif answer == "3":
print "Adding Vehicle..."
brand = raw_input("Please add the brand of the new vehicle.")
model = raw_input("Please enter the model of the new vehicle.")
km = raw_input("Please enter the km driven by the new vehicle.")
service_date = raw_input("Please enter the last service_date of the new vehicle.")
my_vehicle = Vehicle(brand, model, km, service_date)
All_Vehicles.append(my_vehicle)
print "Vehicle added to list"
else:
print "Please check your input, and try again.\n"
| true |
bfadef36e211fb74bc5191806e7e20577889683e | JayWebz/PythonExercises | /final/project3 - EmployeeDbCRUDapp/emp.py | 1,513 | 4.25 | 4 | class Employee:
"""employee is an object that creates and manipulates data about a particular employee such as calculating pay, printing employee info, ."""
# Initialize attributes
def __init__(self, firstName, lastName, employeeID, status, payRate):
self.firstName = firstName
self.lastName = lastName
self.employeeID = employeeID
self.status = status
self.payRate = payRate
# Create record list provided employee info
def addRecord(self, firstName, lastName, employeeID, status, payRate):
record = [self.firstName, self.lastName, self.employeeID, self.status, self.payRate]
return record
# Calculate employee pay
def calculatePay(self, status, payRate):
# Full Time
if self.status == 'ft':
self.payRate = float(self.payRate)
grossPay = self.payRate / 12
return grossPay
# Part Time
elif self.status == 'pt':
self.payRate = float(self.payRate)
classCount = input("How many classes were taught? ")
classCount = float(classCount)
grossPay = self.payRate * float(classCount)
return grossPay
# Hourly
elif self.status == 'hourly':
self.payRate = float(self.payRate)
hourCount = input("How many hours were worked? ")
grossPay = self.payRate * float(hourCount)
return grossPay
# Print current data on employee
def employeeInfo(self, firstName, lastName, employeeID, status, payRate):
return "Employee {} {}, id number {}, is {} status, at a rate of ${}.".format(self.firstName, self.lastName, self.employeeID, self.status, self.payRate) | true |
5c8978b9860f2cba173eafa34cc0315bd0fe7a12 | JayWebz/PythonExercises | /Module3/project4 - EpactCalc/hw3extraCredit.py | 1,264 | 4.40625 | 4 | #! /usr/bin/python
# Exercise No. extra credit
# File Name: hw3extraCredit.py
# Programmer: Jon Weber
# Date: Sept. 10, 2017
#
# Problem Statement: Write a user-friendly program that
# prompts the user for a 4-digit year and then outputs the value of the Gregorian epact for that year
#
# Overall Plan:
# 1. Print an initial welcoming message to the screen
# 2. Prompt the user for the year they want to find the epact for
# 3. solve for C, century
# 4. Use the epact formula to return an answer measured in days
#
#
# import the necessary python libraries
from math import * # Makes the math library available
def main():
print("Welcome to Gregorian epact Calculator.")
print("A program that is designed to calcuate how many days since the new moon come January 1st of a given year.")
print("Let's begin")
#collect user inputs
year = eval(input("What year should we find the epact for? "))
# find the century
C = year // 100
# break the formula into parts based on parentheses.
paren1 = C // 4
paren2 = 8 * C + 13
paren3 = year % 19
#plug in parenthetic variables to main equation
epact = (8 + paren1 - C + (paren2 // 25) + 11 * paren3) % 30
print("There were", epact, "days since the new moon on January 1st in", year)
main()
| true |
cd446e7ed3da381d0ad861dfebed7769a61ac211 | JayWebz/PythonExercises | /Module4/project2 - CalcSumGUI/hw4project2.py | 2,298 | 4.5 | 4 | #! /usr/bin/python
# Exercise No. 2
# File Name: hw4project2.py
# Programmer: Jon Weber
# Date: Sept. 17, 2017
#
# Problem Statement: Create a Graphical User Interface
# for a program that calculates sum and product of three numbers.
#
# Overall Plan:
# 1. Create a window for objects and print welcome message to window
# 2. Create input field for integers to be used in calculations
# 3. Calculate the sum of the integers
# 4. Calculate product of integers
# 5. Print the sum of the integers on screen with label
# 6. Print the product of the integers to screen with label
# 7. Close window when prompted by the user
#
# import the necessary python libraries
import graphics
from graphics import *
def main():
# Open white graphics window
win = graphics.GraphWin("Sum and Product Finder", 300, 300)
win.setBackground("white")
# Set coordinates to go from (0,0) lower left to (3,3) in upper right
win.setCoords(0.0, 0.0, 3.0, 3.0)
# Print a message to the window
Text(Point(1.5,2.75), "Hello!").draw(win)
Text(Point(1.5,2.5), "I can add and multiply three numbers for you").draw(win)
# Create input fields for integers used in calculations below
Text(Point(1,2), "Enter first number: ").draw(win)
num1input = Entry(Point(2,2), 5).draw(win)
Text(Point(1,1.75), "Enter second number: ").draw(win)
num2input = Entry(Point(2,1.75), 5).draw(win)
Text(Point(1,1.5), "Enter third number: ").draw(win)
num3input = Entry(Point(2,1.5), 5).draw(win)
#Create output fields and content
Text(Point(1, 1), "Sum: ").draw(win)
outputSum = Text(Point(2, 1), " ").draw(win)
Text(Point(1, 0.75), "Product: ").draw(win)
outputProduct = Text(Point(2, 0.75), " ").draw(win)
button = Text(Point(1.5, 0.25), "Do the math").draw(win)
Rectangle(Point(1.125, 0.125), Point (1.875, 0.375)).draw(win)
#wait for mouse click
win.getMouse()
# Convert the inputs into integers
num1 = eval(num1input.getText())
num2 = eval(num2input.getText())
num3 = eval(num3input.getText())
# Calculate values of sum and product of three numbers
sum = num1 + num2 + num3
product = num1 * num2 * num3
# Output the results and change button
outputSum.setText(sum)
outputProduct.setText(product)
button.setText("Quit")
# Wait for click and then quit
win.getMouse()
win.close()
main()
| true |
35621ed7d9d2dfdae93b1fba45b942a3a668efac | JayWebz/PythonExercises | /final/project3 - EmployeeDbCRUDapp/record.py | 1,308 | 4.3125 | 4 | class Employee:
"""employee is an object that creates and manipulates data about a particular employee such as calculating pay, printing employee info, ."""
# Initialize attributes
def __init__(self, firstName, lastName, employeeID, status, payRate):
self.firstName = firstName
self.lastName = lastName
self.employeeID = employeeID
self.status = status
self.payRate = payRate
# Calculate employee pay
def calculatePay(self, status, payRate):
if self.status == 'ft':
self.payRate = float(self.payRate)
monthlyRate = self.payRate / 12
print(monthlyRate, "per month")
elif self.status == 'pt':
self.payRate = float(self.payRate)
classCount = input("How many classes were taught? ")
classCount = float(classCount)
grossPay = self.payRate * classCount
print(grossPay, ", at", payRate, "per class")
elif self.status == 'hourly':
self.payRate = float(self.payRate)
hourCount = input("How many hours were worked? ")
grossPay = self.payRate * hourCount
print(grossPay, ", at", payRate, "per hour")
# Print current data on employee
def employeeInfo(self, firstName, lastName, employeeID, status, payRate):
print("Employee {} {}, id number {}, is {}, at a rate of {}.".format(self.firstName, self.lastName, self.employeeID, self.status, self.payRate)) | true |
48df7ef8f1638b25aa1c405fa7f941792d5d6029 | Slackd/python_learning | /PY4E/05-iterations.py | 665 | 4.28125 | 4 | #! /usr/bin/python3
# Write another program that prompts for a list of
# numbers as above and at the end prints out both the maximum
# and minimum of the numbers instead of the average.
userNums = input("Enter Numbers Separated by spaces: ")
inputNums = userNums.split()
for i in range(len(inputNums)):
inputNums[i] = int(inputNums[i])
largest = None
smallest = None
for itervar in inputNums:
if largest is None or itervar > largest :
largest = itervar
print("Largest:", largest)
for itervar in inputNums:
if smallest is None or itervar < smallest :
smallest = itervar
print("Smallest:", smallest)
print("Sum:", sum(inputNums))
| true |
91a712961cbd6bfd8c8ec3de6629d178d6e0b62e | Slackd/python_learning | /First/if_else.py | 616 | 4.34375 | 4 | is_male = False
is_tall = True
if is_male and is_tall:
print("You are a tall male")
elif is_male and not (is_tall):
print("you are a short male")
elif not (is_male) and is_tall:
print("you are not a male, but are tall")
else:
print("you are neither male not tall or both")
num1 = input("Enter 1st Number: ")
num2 = input("Enter 2nd Number: ")
num3 = input("Enter 3rd Number: ")
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(num1, num2, num3))
| true |
86d1bd41d5682d09eaa8356a0dcde8c978b11210 | Voidivi/Python-1 | /Pig Latin Translator.py | 1,847 | 4.40625 | 4 | #!/usr/bin/env python3
# Assignment Week 6 - Pig Latin Translator
# Author: Lyssette Williams
# global values for the program
ay = 'ay'
way = 'way'
vowels = ['a','e', 'i', 'o', 'u']
punctuations = '''!()-[];:'",<>./?@#$%^&*_~'''
# decided to add some formatting stuff to make it more readable
def display():
print('Welcome to the Pig Latin Translator!')
print('=' * 36)
# I struggled for many hours on how to get this program working for more than one word
# I got it working great for one word only
# I also tried the strip function (after you talked about it in zoom)
# but since it wouldn't pull punctuation out from the middle of a sentence I went back to for loop
def piglatin():
userinput = input('Enter text: ')
no_punct = ""
for char in userinput: #stripping punctionation
if char not in punctuations:
no_punct = no_punct + char
no_punct = no_punct.lower()
userinput = no_punct #converting the no punctuation variable back to userinput so I can do less renaming work downstream
print('English:', userinput)
userinput = userinput.split() #splitting out words
translation = ''
for word in userinput: #searching for vowels
first = word[0]
if first in vowels:
translation = translation + word + way + ' '
else:
for char in word[1:]:
if char in vowels or char == 'y': #dealing with y
translation = translation + word[word.index(char):] + word[0:word.index(char)] + ay + ' '
break
print('Pig Latin:', translation)
# again added some formatting for legibility
def main():
display()
cont_program = 'y'
while cont_program == 'y' or cont_program == 'Y':
piglatin()
cont_program = input('Continue? (y/n): ')
print('=' * 36)
print('Bye!')
if __name__ == "__main__":
main()
| true |
f5b22ec6f30c9d286bc75a37f5001c493abe6b58 | Maria-Lasiuta/geegs_girls_lab3 | /ex3(3).py | 363 | 4.15625 | 4 | #Calculate number of distinct characters in a string using a for loop.
def unique_count(word):
k=list()
b = word.split()
b = ''.join(b)
for x in b:
if x not in k:
k.append(x)
return len(k)
enter=input()
print('унікальних символів:',unique_count(enter))
| true |
2cb3cf3b87d0068c7291eb80c7be10675218e57d | Maria-Lasiuta/geegs_girls_lab3 | /lab 3/5(3).py | 376 | 4.15625 | 4 | #Check if the number is prime
def is_prime(n):
if n > 1:
for i in range(2, (int(n/2)+1)):
if n%i == 0:
return f'{n} is not a prime number'
else:
return f'{n} is a prime nummber'
else:
return f'{n} is a prime number'
n = int(input('Enter integer number: '))
print(is_prime(n))
| false |
4ae76eeee25d37e786eda9fea0dc14163c77a8fa | epotyom/interview_prepare | /coding/sorts/quicksort.py | 1,154 | 4.28125 | 4 | def sort(data):
"""
Quicksort function
Arguments:
data(list): list of numbers to sort
"""
sortIteration(data, 0, len(data)-1)
def sortIteration(data, first, last):
"""
Iteration of quicksort
Arguments:
data(list): list to be sorted
first(int): first element of iteration
last(int): last element of iteration
"""
if first < last:
divpoint = divide_and_conquer(data, first, last)
sortIteration(data, first, divpoint-1)
sortIteration(data, divpoint+1, last)
def divide_and_conquer(data, first, last):
divpoint = first # select divpoint, any method
left_mark = first + 1
right_mark = last
done = False
while not done:
while left_mark <= right_mark and data[left_mark] < data[divpoint]:
left_mark += 1
while right_mark >= left_mark and data[right_mark] > data[divpoint]:
right_mark -= 1
if left_mark > right_mark:
done = True
else:
tmp = data[left_mark]
data[left_mark] = data[right_mark]
data[right_mark] = tmp
tmp = data[divpoint]
data[divpoint] = data[right_mark]
data[right_mark] = tmp
return right_mark
| true |
820dca361b752699d098b0d9b59615971ecdc524 | yohannabittan/iterative_hasher | /iterative_hasher.py | 2,778 | 4.3125 | 4 | #written by Yohann Abittan
#this program uses hashlib to either produce hashes which have been hashed iteratively a given number of times
#or to test wether a given hash matches a password after a number of iterations of hashing
import hashlib
def encryptMd5(initial):
encrypted = hashlib.md5()
encrypted.update(initial)
return encrypted.hexdigest()
def encryptSha1(initial):
encrypted = hashlib.sha1()
encrypted.update(initial)
return encrypted.hexdigest()
def encryptSha224(initial):
encrypted = hashlib.sha224()
encrypted.update(initial)
return encrypted.hexdigest()
def encryptSha256(initial):
encrypted = hashlib.sha256()
encrypted.update(initial)
return encrypted.hexdigest()
def encryptSha384(initial):
encrypted = hashlib.sha384()
encrypted.update(initial)
return encrypted.hexdigest()
def encryptSha512(initial):
encrypted = hashlib.sha224()
encrypted.update(initial)
return encrypted.hexdigest()
def main():
counter = 0
passwordFound = 0
print("\n \nWelcome to iterative hasher \n")
print("Would you like to generate a hash? (1) \n")
mode = raw_input("Or would you like to iteratively hash an input and test if it matches a target? (2) \n")
print("Which algorithm would you like to use? \n")
algo = raw_input("1 = md5, 2 = sha1, 3 = sha224, 4 = sha384, 5 = sha512 \n")
password = raw_input("What is your password\n")
if mode == "2":
target = raw_input("What is your target hash?\n")
iterations = int(raw_input("How many times would you like to hash the input? \n"))
while counter!=iterations:
if algo == "1" or algo == "md5":
password = encryptMd5(password)
elif algo == "2" or algo == "sha1":
password = encryptSha1(password)
elif algo == "3" or algo == "sha224":
password = encryptSha224(password)
elif algo == "4" or algo == "sha384":
password = encryptSha384(password)
elif algo == "5" or algo == "sha512":
password = encryptSha512(password)
if mode == 2:
if password == target:
print("Got it ! number of iterations =%s"%counter)
passwordFound = 1
break
step = int(iterations/10)
if counter%step==0:
print("hashing no:%s"%counter)
print password
counter+=1
if mode == "2":
if passwordFound !=1:
print ("target not found :(")
elif mode == "1":
print("\n \nAfter %s iterations your final hash is = "%iterations + password)
if __name__ == "__main__":
main()
| true |
1817ccf74ed79881b17d5e029cffa926ee282e93 | chrismvelez97/GuideToPython | /techniques/exceptions/value_error.py | 989 | 4.625 | 5 | # How to handle the value error
'''
The value error is when your
program is expecting a certain
value type back such as a number
or a string and you get the other.
For example, we'll be using a
calculator that can add, but
get a value error if we type letters
in place of numbers.
The following is the error
we'd see for strings:
First Number: d
Second Number: d
Traceback (most recent call last):
File "value_error.py", line 23, in <module>
answer = int(f_num) + int(s_num)
ValueError: invalid literal for int() with base 10: 'd'
'''
print ("Give me two letters to add.\nPress 'q' to quit")
while True:
f_num = input("\nFirst Number: ")
if f_num == 'q':
break
s_num = input("Second Number: ")
if s_num == 'q':
break
try:
answer = int(f_num) + int(s_num)
except ValueError:
print ("\nYou can't enter letters to add!\nPress 'q' to quit or try again.")
else:
print ("Answer: " + str(answer))
| true |
6dfde392607bfe8accf5baa0e097e7ee838717da | chrismvelez97/GuideToPython | /techniques/files/storingData/saving_user_data.py | 730 | 4.1875 | 4 | # How to save user data
'''
Using the json.dump() and json.load()
techniques we just learned about, we
can actually save user data to be
used at a later time.
'''
import json
username = input("Hello! What is your name?\n\n")
path = "/home/chrismvelez/Desktop/GuideToPython3/techniques/files/storingData/jsonFiles/user_data.json"
with open(path, 'w') as fobject:
json.dump(username, fobject)
print("\nWe'll remember you when you come back now!")
with open(path) as fobject:
jsonData = json.load(fobject)
reply = input("You said your name was {0} right?\n\n".format(jsonData))
if reply == 'y':
print ("okay good")
elif reply == 'n':
print ("Sorry about that!")
| true |
64c2d50ebe0d127df0170b3834507467c89340d0 | chrismvelez97/GuideToPython | /data_types/dictionaries.py | 1,541 | 4.90625 | 5 | # How to use dictionaries
'''
Dictionaries are special forms of containers that do NOT have indices. They
can start off empty and have values added later
Instead, they have key and value pairs. To access a value you use the key.
The keys must be strings, and the values can hold anything from variables to
lists, to even other dictionaries.
A dictionary can be looped through but it will not be in order since they have
no indices.
Lastly, every single key is unique meaning you cannot use it again within the
same dictionary.
'''
dictionary = {
"words": {
"penultimate": "The second to last item in a group.",
"ultimate": "The last item in a group"
},
"numbers": {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
},
"extra": "value"
}
print (dictionary["words"]) # How you access dictionary values
'''
Results:
{'penultimate': 'The second to last item in a group.',
'ultimate': 'The last item in a group'}
'''
print (dictionary["words"]["penultimate"])
# results: The second to last item in a group.
print (dictionary["numbers"])
# results: {'one': 1, 'three': 3, 'two': 2, 'five': 5, 'four': 4}
# How you add values to dictionaries
dictionary["booleans"] = [True]
print (dictionary["booleans"])
# results: [True]
# How you modify values in dictionaries
dictionary["booleans"] = [True, False]
print (dictionary["booleans"])
# results: [True, False]
# How you delete keys in dictionaries
del dictionary["extra"]
| true |
f837053b00cd472b1097c4f4e72e4e7b053e0100 | chrismvelez97/GuideToPython | /techniques/classes/default_modifying_attributes.py | 1,751 | 4.625 | 5 | # Default values and Modifying attributes
class Character():
"""
This class will model a character in a videogame
to show the different things we can do with classes.
"""
def __init__(self, name):
'''
You can see we have attributes we didn't require
in our parameters but the reason for this is
because we are setting default values.
'''
self.health = 100
self.strength = 20
self.name = name
def displayInfo(self):
print ("Congratulations!")
print ("\nYou have created a brand new character")
print ("This is you!\nName: {0}\nHealth: {1}\nStrength: {2}".format(
self.name, str(self.health), str(self.strength)
))
def fall(self):
'''
You can see below that we changed the default value
to drop in case our character's health fell.
You can also change attributes values directly through
your instance(See line 65 for example)
'''
self.health -= 10
print ("\nUh oh! Seems like you're pretty clumsy! \n\n You get back up but lose ten health")
ryu = Character(name="Ryu")
ryu.displayInfo()
'''
Results:
Congratulations!
You have created a brand new character
This is you!
Name: Ryu
Health: 100
Strength: 20
'''
ryu.fall()
'''
Results:
Uh oh! Seems like you're pretty clumsy!
You get back up but lose ten health
'''
print (ryu.health)
# This is kinda cheating because we wouldn't want our user
# To be able to just reset their health but I'm just
# showing this as an example.
ryu.health = 100
ryu.displayInfo()
'''
Results:
You have created a brand new character
This is you!
Name: Ryu
Health: 100
Strength: 20
'''
| true |
080d28c6f1467abf777e76ac49a786b0e0055333 | chrismvelez97/GuideToPython | /techniques/functions/built_in_functions/sum.py | 478 | 4.15625 | 4 | # How to use the sum() function
'''
The sum() function adds all the numbers up from a list of numbers.
Note that for min, max, and sum, you can only do them on lists full of numbers.
also it is not a method attached to the number datatype which is why it is in
the techniques folder instead of the num_methods folder.
'''
numbers = list(range(11))
print (numbers)
# results: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (sum(numbers))
# results: 55
| true |
97a8074488d0ee8e03d0f1ba2e3ed725c0820691 | chrismvelez97/GuideToPython | /techniques/functions/built_in_functions/range.py | 1,471 | 4.90625 | 5 | # How to use range in python
'''
So after looking over this I really debated with myself if I should
put this under method or techniques and I ended up putting it here because,
the function doesn't execute if not in conjunction with a for loop, hence it
being a technique.
The range(start, end) function creates a set of numbers to
generate starting at the first argument, and ending BEFORE the last argument.
This means that if you put range(1:5) it will go from 1 to 4, not 1 to 5.
Also, if you only enter one argument into the range() function, it will start
at 0 and continue until right before whatever number you entered.
Lastly, you can also use range to generate only even numbers or odd numbers.
(see ex.3-4)
'''
# Ex.1
for value in range(1, 5):
print(value)
'''
Note that below the result aren't inline as each new line is a new result
Results:
1,
2,
3,
4,
'''
# Ex.2
print ("\n ")
for value in range(5):
print (value)
print ("\n")
'''
Note that below the result aren't inline as each new line is a new result
Results:
0,
1,
2,
3,
4,
'''
# Ex. 3
print("Odds:")
for value in range(1, 11, 2): # You must start with an odd number to do odds
print (value)
print("\n")
'''
Note that instead this third argument adds by two giving us only odd
numbers.
Results:
1,
3,
5
'''
# Ex. 4
print ("Evens:")
for value in range(2, 11, 2): # You must start with an even number to do evens
print (value)
print ("\n")
| true |
38c5fa3b7f2798b48e0aaab62bf319f18ff2c8f9 | chrismvelez97/GuideToPython | /techniques/loops/looping_dictionaries.py | 995 | 4.5 | 4 | # How to loop Dictionaries
'''
You can loop through dictionaries but it should be noted that they will not
come out in any specific order because are not ordered by indices
'''
dictionary = {
"words": {
"penultimate": "The second to last item in a group.",
"ultimate": "The last item in a group"
},
"numbers": {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5
},
"booleans": [True, False]
}
# How to print just the keys
for key in dictionary:
print (key)
'''
Results:
numbers
booleans
words
'''
# How to print the key, value pairs
user_0 = {
"username": "efermi",
"first": "enrico",
"last": "fermi"
}
for key, value in user_0.items(): # You need the item() method to print both
print ("\nKey: " + key)
print ("\nValue: " + value)
'''
Results:
Key: first
Value: enrico
Key: last
Value: fermi
Key: username
Value: efermi
'''
| true |
a5d24fbee492882a3802ab5a147d333a937494b2 | pratishhegde/rosalind | /problems/fibd/fibd.py | 1,184 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
Recall the definition of the Fibonacci numbers from “Rabbits and Recurrence
Relations”, which followed the recurrence relation Fn=Fn−1+Fn−2 and assumed that
each pair of rabbits reaches maturity in one month and produces a single pair of
offspring (one male, one female) each subsequent month.
Our aim is to somehow modify this recurrence relation to achieve a dynamic
programming solution in the case that all rabbits die out after a fixed number
of months. See Figure 4 for a depiction of a rabbit tree in which rabbits live
for three months (meaning that they reproduce only twice before dying).
Given: Positive integers n≤100 and m≤20.
Return: The total number of pairs of rabbits that will remain after the n-th
month if all rabbits live for m months.
Sample Dataset
6 3
Sample Output
4
'''
import sys
sys.path.append('../../')
import rosalind_utils
def fibd():
n,m = map(int, open("rosalind_fibd.txt").read().split())
# keep track of rabbit ages
rabbits = [0] * m
rabbits[0] = 1
for i in xrange(n-1):
newborns = sum(rabbits[1:])
rabbits = [newborns] + rabbits[:m-1]
return sum(rabbits)
| true |
7ac4527ba233e39bf952a56b069e4a2f5ff4418c | Wamique-DS/my_world | /Some Basic Program in Python...py | 1,650 | 4.1875 | 4 |
# coding: utf-8
# In[3]:
# prgogarm to find Area of circle
radius=eval(input("Enter the radius of circle ")) # eval takes any value either integer or float
# calculate area
area=radius*radius*3.14
# Display result
print("Area of circle of radius", radius,"is",round(area,2))
# In[8]:
# Program to find area of cirle
import math
r=float(input("Enter radius of a cirlce "))
# using import function
area=math.pi*math.pow(r,2)
# display result
print("Area of circle of radius",radius,"is",round(area,2))
# In[14]:
# Prgogram to find average of three numbers
a=eval(input("Enter the first number "))
b=eval(input("Enter the second number "))
c=eval(input("enter the third number "))
avg=(a+b+c)/3
print("Average of three number is",round(avg,3))
print("Average of ",a,b,c,"is",round(avg,2))
# In[19]:
str(12) # usde to convert int into string
# In[20]:
str(12.76)
# In[25]:
import random
# generate random number
num1=random.randint(0,9)
num2=random.randint(0,9)
answer=eval(input("what is "+str(num1)+ "+" + str(num2) + "?"))
print(num1, "+", num2, "=",answer,"is", num1+num2==answer)
# In[29]:
# Program to generate an OTP of 6 digit
from random import randint
for i in range(10):
print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9))
# In[31]:
a = 2
print('id(a) =', id(a))
a = a+1
print('id(a) =', id(a))
print('id(3) =', id(3))
b = 2
print('id(2) =', id(2))
# In[51]:
x="mohammad wamique hussainmm"
len(x)
x.count('a')
x.count('k')
'i' in x
'p' in x
x.index('n')
#x.strip('m')
#x.strip('m')
x.strip('m')
# In[52]:
x="mohammad wamique hussainmm"
x.strip('m') # it strips all m from both start and end
| true |
901bfe55f38adb6702d4ce85ef8473b0a6e7da4d | kunzhang1110/COMP9021-Principles-of-Programming | /Quiz/Quiz 6/quiz_6.py | 2,804 | 4.1875 | 4 | # Defines two classes, Point() and Triangle().
# An object for the second class is created by passing named arguments,
# point_1, point_2 and point_3, to its constructor.
# Such an object can be modified by changing one point, two or three points
# thanks to the function change_point_or_points().
# At any stage, the object maintains correct values
# for perimeter and area.
#
# Written by Kun Zhang and Eric Martin for COMP9021
from math import sqrt
class Point():
def __init__(self, x = None, y = None):
if x == None and y == None:
self.x = 0
self.y = 0
elif x == None or y == None:
print('Need two coordinates, point not created.')
else:
self.x = x
self.y = y
def collinear(self, p2, p3):
if (p2.y - self.y)*(p3.x - self.x) == (p2.x - self.x) * (p3.y - self.y):
return True
else:
return False
class Triangle:
def __init__(self, *, point_1, point_2, point_3):
# variable after * are keyword only arguments in the form of point_1=xx
if point_1.collinear(point_2, point_3):
self.error_message('Initialisation')
else:
self._initialise(point_1, point_2, point_3)
def error_message(self, phase):
if phase == 'Initialisation':
print('Incorrect input, triangle not created.')
else:
print('Incorrect input, triangle not modified.')
print('Could not perform this change')
def change_point_or_points(self, *, point_1 = None,
point_2 = None,
point_3 = None):
temp_1 = self.get_point(point_1, self.p1)
temp_2 = self.get_point(point_2, self.p2)
temp_3 = self.get_point(point_3, self.p3)
if temp_1.collinear(temp_2, temp_3):
self.error_message('Modify')
else:
self._initialise(temp_1, temp_2, temp_3)
@staticmethod
def get_point(p, sp):
if p is None:
return sp
return p
def _initialise(self, p1, p2, p3):
pass
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.area = self.get_area()
self.perimeter = self.get_peri()
def get_peri(self):
line_1 = sqrt(abs(self.p1.x - self.p2.x)**2 + abs(self.p1.y - self.p2.y)**2)
line_2 = sqrt(abs(self.p1.x - self.p3.x)**2 + abs(self.p1.y - self.p3.y)**2)
line_3 = sqrt(abs(self.p2.x - self.p3.x)**2 + abs(self.p2.y - self.p3.y)**2)
return line_1 + line_2 + line_3
def get_area(self):
return abs(self.p1.x * self.p2.y + self.p2.x * self.p3.y + self.p3.x * self.p1.y -\
self.p1.y * self.p2.x - self.p2.y * self.p3.x - self.p3.y * self.p1.x)/2
| true |
667e34fb89fc133969d6649bb218c3c0c40adaa5 | Maria61/test_script | /2020-08-03/test1.py | 272 | 4.34375 | 4 | # 注释:“:”后缩进的语句视为代码块;python大小写敏感
# a = 100
# if a >= 0:
# print(a)
# else:
# print(-a)
#
# print('I\'m \"OK\"')
#
# print('I\'m OK')
#
# print(r'\\\t\\\ ')
# print('T \t i \n m')
print('''asdf
jlkl
... werwqre
... d''') | false |
c159ab3cb87d420b584ca54d07397f7942600269 | ridolenai/Day_Trip_Generator | /DayTripGenerator.py | 2,583 | 4.15625 | 4 | import random
destinations = ["Disney World", "Oktoberfest", "Crawfish Festival", "Mawmaw's House"]
restaurants = ["Applebee's", "Schnitzel Emporium", "Pizza Hut", "Sullivan's"]
transportation = ['Car', 'Bicycle', '4-wheeler', 'Yee Yee Truck']
entertainment = ['Miley Cyrus Concert', 'Chainsaw Juggler', 'Sock Manufacturing Tour', 'Mud-riding']
day_trip = []
satisfaction = ''
def indecisive_trip (x): #Selects random options from lists.
random_trip = random.choice(x)
print (random_trip)
return (random_trip)
def begin (p):#Keeps track of choices in list.
print("Welcome to the RNGeezus Trip Generator. This will help you find something to do for the day since you have no ideas.")
print ("Below, you will see your selections for the day. If you do not like any of these suggestions, you may have them produced again.")
day_trip.append (indecisive_trip(destinations))
day_trip.append (indecisive_trip(restaurants))
day_trip.append (indecisive_trip(transportation))
day_trip.append (indecisive_trip(entertainment))
def choose_again (q): #Enables user to select another option if one of the selections is undesirable.
if satisfaction == ('y'):
print('We are glad you are satisfied with your selection. Please have a pleasant trip and remember to wear your seatbelt.')
if satisfaction == ('n'):
unsatisfied = (input('Please select the option you would like to change: 1:destination, 2:restaurant, 3:transportation, or 4:entertainment '))
if unsatisfied == ('1'):
day_trip.pop(0)
day_trip.insert(0, indecisive_trip(destinations))
elif unsatisfied == ('2'):
day_trip.pop(1)
day_trip.insert(1, indecisive_trip(restaurants))
elif unsatisfied == ('3'):
day_trip.pop(2)
day_trip.insert(2, indecisive_trip(transportation))
elif unsatisfied == ('4'):
day_trip.pop(3)
day_trip.insert(3, indecisive_trip(entertainment))
return day_trip
begin(indecisive_trip)
while satisfaction != ('y'): #allows users to change undesirable options until they are satisfied.
choose_again(indecisive_trip)
satisfaction = input ('Please type y if you are satisfied or n if you are not')
print ('Here is your randomly generated day trip:')#These three lines print the outcome once the user is satisfied.
print (day_trip)
print ("Thank you for using the RNGeezus Trip Generator. Enjoy your day away! ")
| true |
c21d9ce87e81316c8dc18ea15f4228cb04152e8b | ashutosh-qa/PythonTesting | /PythonBasics/First.py | 509 | 4.28125 | 4 | # To print anything
print("This is first Pyhton program")
# How to define variable in python
a = 3
print(a)
# How to define String
Str="Ashutosh"
print(Str)
# Other examples
x, y, z = 5, 8.3, "Test"
print(x, y, z)
# to print different data types - use format method
print ("{} {}".format("Value is:", x))
# How to know data type, see result in output
print(type(x))
print(type(y))
print(type(z))
#create a variable with integer value.
p=100
print("The type of variable having value", a, " is ", type(p)) | true |
04f373e0bb32fc3a4f4e9d77e1fc83fe368803f2 | Dame-ui/Algorithms | /bubblesort.py | 797 | 4.375 | 4 |
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)): #run N times, where N is number of elements in a list
# Last i elements are already in place
# It starts at 1 so we can access the previous element
for j in range(1, len(list_of_numbers) - i): # N-i elements
if list_of_numbers[j-1] > list_of_numbers[j]: #check if previous element is bigger than the current element
#Swap code from the instructors notes:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers[j] = temp
return list_of_numbers
#Do not change code below this line
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
| true |
c44dc53c8c6aea407e29c934b9559c752a9e0216 | thinhld80/python3 | /python3-17/python3-17.py | 1,695 | 4.3125 | 4 | #Functions in depth
#No Arguments
def test():
print('Normal function')
print('\r\n------ No Arguments')
test()
#Positional and Keyword Arguments
def message(name,msg,age):
print(f'Hello {name}, {msg}, you are {age} years old')
print('\r\n------ Positional and Keyword Arguments')
message('Bryan', 'good morning', 22) #positional
message('Bryan', 22, 'good morning') #positional (wrong order)
message(msg='Good morning', age=46, name='Bryan') #Keywords
message('Bryan', age=46, msg='Good morning') #Both
#Internal functions
def counter():
def display(count = 0): #Function in a function
print(f'Internal: {count}')
for x in range(5): display(x)
print('\r\n------ Internal functions')
counter()
# *args - positional variable length arguments
def multiple(*args):
z = 1
for num in args:
print(f'Num = {num}')
z *= num
print(f'Multiply: {z}')
print('\r\n------ *args')
multiple(2,3,1,4,5,6,8,2,4,5,6)
# **kwargs is used to pass a keyworded, variable length arguments
def profile(**person):
print(person)
def display(k):
if k in person.keys(): print(f'{k} = {person[k]}')
display('name')
display('age')
display('pet')
display('pezzzzt')
print('\r\n------ **kwargs')
profile(name='Bryan', age=46)
profile(name='Bryan', age=46,pet='Cat')
profile(name='Bryan', age=46,pet='Cat',food='pizza')
#Lambda functions (anonymous functions)
print('\r\n------ Lambda')
#normal
def makesqft(width=0,height=0):
return width * height
print(makesqft(width=10,height=8))
print(makesqft(15,8))
#lambda
#z = lambda x: x * y
sqft = lambda width=0,height=0: width * height
print(sqft(width=10,height=8))
print(sqft(15,8))
| true |
8bc9cb211ce9780e5d76303f4869eac4aa0d87bb | thinhld80/python3 | /python3-48/python3-48.py | 2,113 | 4.375 | 4 | #Queues and Futures
#Getting values from a thread
#This is a problem for future me
"""
Queues is like leaving a message
A Future is used for synchronizing program execution
in some concurrent programming languages. They describe an
object that acts as a proxy for a result that is initially unknown,
usually because the computation of its value is not yet complete.
"""
#Imports
import logging
import threading
from threading import Thread
import time
import random
from concurrent.futures import ThreadPoolExecutor #Python 3.2
from queue import Queue
#Queues
#Use Queue to pass messages back and forths
def test_que(name, que):
threadname = threading.current_thread().name
logging.info(f'Starting: {threadname}')
time.sleep(random.randrange(1,5))
logging.info(f'Finished: {threadname}')
ret = 'Hello ' + name + ' your random number is: ' + str(random.randrange(1,100))
que.put(ret)
def queued():
que = Queue()
t = Thread(target=test_que,args=['Bryan', que])
t.start()
logging.info('Do something on the main thread')
t.join()
ret = que.get()
logging.info(f'Returned: {ret}')
#Futures
#Use futures, easier and cleaner
def test_future(name):
threadname = threading.current_thread().name
logging.info(f'Starting: {threadname}')
time.sleep(random.randrange(1,5))
logging.info(f'Finished: {threadname}')
ret = 'Hello ' + name + ' your random number is: ' + str(random.randrange(1,100))
return ret
def pooled():
workers = 20
ret = []
with ThreadPoolExecutor(max_workers=workers) as ex:
for x in range(workers):
v = random.randrange(1,5)
future = ex.submit(test_future,'Bryan' + str(x))
ret.append(future)
logging.info('Do something on the main thread')
for r in ret:
logging.info(f'Returned: {r.result()}')
#Main function
def main():
logging.basicConfig(format='%(levelname)s - %(asctime)s.%(msecs)03d: %(message)s',datefmt='%H:%M:%S', level=logging.DEBUG)
logging.info('App Start')
#queued()
pooled()
if __name__ == "__main__":
main() | true |
34953844e759a37f2b697a345c7ed870d6098e3e | thinhld80/python3 | /python3-4/python3-4.py | 685 | 4.15625 | 4 | #Numbers - int float complex
#int
iVal = 34
print(f'iVal = {iVal}')
#float
fVal = 3.14
print(f'fVal = {fVal}')
import sys
print(sys.float_info) # https://docs.python.org/3/library/sys.html#sys.float_info
#complex - complex([real[, imag]])
cVal = 3 +6j
print(f'cVal = {cVal}')
cVal = complex(5,3)
print(f'cVal = {cVal}')
print(f'real = {cVal.real}, imag = {cVal.imag}')
#Basic numerical operations
x = 3
print(f'x = {x}')
y = x + 3 #add
print(f'add = {y}')
y = x - 1 #subtract
print(f'subtract = {y}')
y = x * 6.846 #multiply
print(f'multiply = {y}')
y = x / 0.5 #divide
print(f'divide = {y}')
y = x ** 2 #pow
print(f'pow = {y}')
y = x % 2.5 #remain
print(f'remain = {y}')
| false |
0cdafb79c9df477474722c851deb8c28efe02905 | thinhld80/python3 | /python3-32/python3-32.py | 1,055 | 4.15625 | 4 | #Multiple Inheritance
#Inherit from multiple classes at the same time
#Vehical class
class Vehical:
speed = 0
def drive(self,speed):
self.speed = speed
print('Driving')
def stop(self):
self.speed = 0
print('Stopped')
def display(self):
print(f'Driving at {self.speed} speed')
#Freezer class
class Freezer:
temp = 0
def freeze(self,temp):
self.temp = temp
print('Freezing')
def display(self):
print(f'Freezing at {self.temp} temp')
#FreezerTruck class
class FreezerTruck(Vehical,Freezer): #Here we define the Method Resolution Order (MRO).
def display(self):
print(f'Is a freezer: {issubclass(FreezerTruck,Freezer)}')
print(f'Is a vehical: {issubclass(FreezerTruck,Vehical)}')
#super(Vehical,self).display() #Works because of MRO
#super(Freezer,self).display() #Fails because of MRO
Freezer.display(self)
Vehical.display(self)
t = FreezerTruck()
t.drive(50)
t.freeze(-30)
print('-'*20)
t.display()
| true |
8579d3e9933115a259e8bebe517ec51b6ae95f1c | loganmcampbell/CSCE-3193 | /Homework[7]/my_cipher2.py | 2,896 | 4.25 | 4 | import functioncipyer
# START HERE : ENTER A THE KEYWORD TO CIPHER AND UPPERCASE IT
word = input("Enter keyword for encrpyt: ")
while (word == ""):
word = input("Enter keyword for encrpyt: ")
print("w o r d : ", word)
word = word.upper()
original = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
original = " ".join(original)
# USE FUNCTION TRANSFORMED FUNCTION
talpha = functioncipyer.TRANSFORMEDALPHABET(word)
# PRINT OUT THE ALPHABET'S, YEAH?
print("\n")
print("TRANSFORMED:\t", talpha)
print("ORIGINAL:\t", original)
# SET UP A CONDITIONAL FOR INPUT, READ FILE , AND NOTHING
choice = input("Read From File [1] or Read From Input [2]: ")
# Read FROM FILE TIME ||
if (choice == "1"):
filename = input("Enter the filename: ")
fileobject = open(filename, "r")
filelist = ""
for line in fileobject:
if (line == "\n" or line == '\n' or line[:-1] == "\n"):
filelist = filelist + "\n"
line = line.upper()
filelist = filelist + line
# INPUT MESSAGE TIME ||
if (choice == "2"):
message = input("Enter message to encrpyt : ")
while (message == ""):
message = input("Enter message to encrpyt : ")
# INPUT FILE READ TO message
if (choice == "1"):
message = filelist
message = message.upper()
print("\nm e s s a g e : ", message)
# CREATE LIST AND ADD THE INDEX #'s LETTERS OF THE WORD FROM THE ALPHABET
numberList = []
for i, c in enumerate(message):
for j, d in enumerate(original):
if (c == d):
numberList.append(j)
if (c == " "):
numberList.append(c)
if (c == "\n" or c == '\n' or c[:-1] == "\n"):
numberList.append("\n")
else:
pass
# COMPARE NUMBER INDICES TO THE LIST FROM ALPHABET TO TRANSFORMED ALPHABET
# SET THE CHARACTER FROM THE TRANSFORMED ALPHABET TO A STRING
code = ""
for x in numberList:
for i, c in enumerate(talpha):
if(i == x):
code = code + c
if (x == "\n" or x == '\n'):
code = code + "\n"
# LOOK FOR MORE THAN 1 SPACES BECAUSE ENUMERATE LOOKS THROUGH EVERYTHING
# REMOVE THEM...
prev = ' '
for letter in code:
if letter == prev:
code = code.replace(" ", "")
code = code.replace("\n", " ")
code = code.strip()
# PRINT THE FINAL PRODUCT OF CIPHERTEXT
print("\nc i p h e r - t e x t : ", code)
if (choice != "1"):
filename = "inputcipher.txt"
if (choice == "1"):
newFilename = filename.replace(".txt", "")
print(newFilename)
writer = open(newFilename + "[ciphered].txt", "w+")
writer.write("FROM THE TEXT FILE : " + filename)
writer.write("\n KEYWORD : " + word)
writer.write("\n ALPHABET :\t" + original)
writer.write("\n TRANSFORMED :\t" + talpha)
writer.write("\n TEXT : \n" + message)
writer.write("\n CIPHERTEXT : " + code)
writer.close()
| false |
8ed8c49a7b826f676b6987a6cb1fb583fefa8d52 | lfparra/MDS-UAI-Programacion-con-Python-Ejercicios | /guia_02_ciclos_01/06.py | 339 | 4.125 | 4 | numero_ingresado = int(input('Ingrese un número, programa finaliza con un -1: '))
suma = 0
while numero_ingresado != -1:
suma = suma + numero_ingresado
numero_ingresado = int(input('Ingrese un número, programa finaliza con un -1: '))
if numero_ingresado == -1:
print('Programa finalizado')
print(f'Suma total: {suma}') | false |
bf0d3e56763cca5dc8024581746ab9eafcb6313b | sandeepmaity09/python_practice | /tuple.py | 354 | 4.59375 | 5 | #!/usr/bin/python3
empty=() # creating tuple
print(type(empty))
empty=tuple() # creation tuple
print(type(empty))
empty="hello", # <---- note trailing comma for create a tuple with only one item
print(empty)
empty=23,34,'heelo' # to create tuple
x,y,z=empty # sequence unpacking of tuple
print(type(x))
print(type(y))
print(type(z))
| true |
975eb35f2c500489c4e0e78f54cebb3fadb49242 | sandeepmaity09/python_practice | /data_structure/disjoint2.py | 254 | 4.125 | 4 | #!/usr/bin/python3
#Running time algorithm = O(n) power 2
def disjoint2(A,B,C):
"""Return True if there is no element common to all three lists."""
for a in A:
for b in B:
if a==b:
for c in C:
if a==c:
return False
return True
| true |
4589b0d8e9c31882841896cec8b077769cb58257 | JohnnySheng/learn_python | /others/foods.py | 567 | 4.15625 | 4 | my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice_cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
print("The first three items in the list are: ")
print(my_foods[0:3])
print("The first three items from the middle of the list are: ")
middle = int(len(my_foods)/2)
print(my_foods[middle:3 + middle])
last = len(my_foods)
print("The first three items from the middle of the list are: ")
print(my_foods[last - 3: last])
| false |
ca0592b5430cca0b075845b1f9a33690ff7cbbdb | Floozutter/project-euler | /python/p004.py | 1,723 | 4.34375 | 4 | """
Project Euler - Problem 4
"Find the largest palindrome made from the product of two 3-digit numbers."
"""
from heapq import merge
from typing import Iterable
def palindromic(s: str) -> bool:
"""
Checks whether a string is a palindrome.
"""
size = len(s)
for i in range(size // 2):
if s[i] != s[size - 1 - i]:
return False
return True
def descending_products(incl_upper: int, excl_lower: int) -> Iterable[int]:
"""
Returns every product of two ranged factors, in descending order.
The upper bound is inclusive, the lower bound is exclusive.
Works by generating sorted rows of multiples for each ranged factor, then
merging the sorted rows together with heapq.
"""
def multiples(factor: int) -> Iterable[int]:
"""
Returns multiples of the factor, in descending order.
The multiples are within the bounds [factor*factor, factor*excl_lower).
"""
return [factor*n for n in range(factor, excl_lower, -1)]
rows = (multiples(factor) for factor in range(incl_upper, excl_lower, -1))
return merge(*rows, reverse=True)
def largest_palindrome_product(digits: int) -> int:
"""
Returns the largest palindrome product of two n-digit numbers.
"""
upper = 10**digits - 1 # inclusive upper bound for n-digit factors
lower = 10**(digits-1) - 1 # exclusive lower bound for n-digit factors
products = descending_products(upper, lower)
return next(filter(lambda z: palindromic(str(z)), products))
def answer() -> str:
"""
Returns the answer to the problem as a string.
"""
return str(largest_palindrome_product(3))
if __name__ == "__main__":
print(answer())
| true |
8056f057bd8fa11a7dfc6e8f41731d37be7dfbba | TrWesche/ca_sorts | /ca_bubblesort.py | 491 | 4.21875 | 4 | nums = [5, 2, 9, 1, 5, 6]
# Define swap() below:
def swap(arr, index_1, index_2):
# pass
temp = arr[index_1]
arr[index_1] = arr[index_2]
arr[index_2] = temp
def bubble_sort(arr):
for el in arr:
for index in range(len(arr) - 1):
if arr[index] > arr[index + 1]:
swap(arr, index, index + 1)
# print(nums)
# swap(nums, 3, 5)
# print(nums)
print("Pre-Sort: {0}".format(nums))
bubble_sort(nums)
print("Post-Sort: {0}".format(nums)) | false |
f9b80902340fda78db2016b2e7b4d77984f5ba7f | LuisPatino92/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 1,177 | 4.5625 | 5 | #!/usr/bin/python3
""" This module has the definition of a Square class"""
class Square:
""" Model of a square """
def __init__(self, size=0):
""" Constructor for Square Method
Args:
size (int): Is the size of the instance, 0 by default.
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
self.__size = size
def area(self):
""" Returns the area of the square
Returns: The area of the Square instance
"""
return self.__size ** 2
@property
def size(self):
""" Getter of size property
Returns: The size of the Square instance
"""
return self.__size
@size.setter
def size(self, value):
""" Setter of size property
Args:
value (int): The size to be set in the Square instance
"""
if not isinstance(value, int):
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
| true |
d098fa93e1def3706732bd290518efe0296b17ae | prathameshkurunkar7/Python_Projects | /Final Capstone Project/FindCostOfTile.py | 388 | 4.21875 | 4 | def find_cost(cost_per_tile, w, h):
"""
Return the total cost of tile to cover
WxH floor
"""
return cost_per_tile * (w * h)
w, h = (int(x) for x in input("Enter W and H : ").split())
cost_tile = float(input("Enter the cost per tile : "))
print(
"Total cost of tile to cover WxH floor : = {:.3f}".format(
find_cost(cost_tile, w, h)
)
)
| true |
2a60f5343b27fe587437abf1b972bbe9e7e04285 | dougBelcher/Scripts | /temperature.6.3.py | 674 | 4.375 | 4 | # 6.3 - Challenge: Convert Temperatures
def convert_cel_to_far(temp_cel):
"""Return the Celsius temp converted to Fahrenheit"""
temp_far = temp_cel * (9 / 5) + 32
return temp_far
def convert_far_to_cel(temp_far):
"""Return the Fahrenheit temp converted to Celsius"""
temp_cel = (temp_far - 32) * (5 / 9)
return temp_cel
temp_far = input("Enter a temperature in degrees F: ")
temp_cel = convert_far_to_cel(float(temp_far))
print(f"{temp_far} degrees F = {temp_cel:.2f} degrees C")
temp_cel = input("\nEnter a temperature in degrees C: ")
temp_far = convert_cel_to_far(float(temp_cel))
print(f"{temp_cel} degrees C = {temp_far:.2f} degrees F")
| false |
4fb378146c4b8c716dfd3b87c0bd3ca8caedbeb4 | ticotheps/Algorithms | /stock_prices/stock_prices.py | 2,711 | 4.375 | 4 | #!/usr/bin/python3
#---------------Understanding the Problem---------------
# Objective: Find the largest positive difference between two numbers in a
# list of 'stock prices'.
# Expected Input: a list of stock prices.
# Example: [1050, 270, 1540, 3800, 2]
# Expected Output: an integer representing the largest (positive) difference between two
# numbers in the list.
# Example: 3530
# Clarifying Questions:
# Can we assume that the list will be sorted?
# Can we ever have a list with 0 items in it?
# Can we ever have a list with negative numbers in it?
# Can we assume that items in the list cannot be repeated?
# Can we assume that all items in the list are integers?
# Can we assume that all items in the list are floats?
#-------------------Devising a Plan----------------------
# Iterative Approach:
# - Create a new empty "profits_list" that will hold all the values of the
# different possible profits.
# - Use a for loop to find the "profits" (positive difference) between each
# current_number (older price) and each compared_number (newer price) to
# the right of it.
# - Store each difference (compared_number - current_number = difference) inside
# the new empty "profits_list".
# - Traverse the profits_list to find the largest number.
# - Return that number.
#-------------------Execute the Plan----------------------
def find_max_profit(prices):
current_max_profit = int(-9 * 10^1000000000)
last_index = len(prices) - 1
list_length = len(prices)
for i in range(0, list_length):
if i > last_index - 1:
break
for j in range(i+1, list_length):
difference = prices[j] - prices[i]
if j > list_length:
break
elif prices[j] == prices[i]:
break
else:
if difference > current_max_profit:
current_max_profit = difference
j += 1
else:
continue
return current_max_profit
print(find_max_profit([1050, 270, 1540, 3800, 2]))
print(find_max_profit([100, 90, 80, 50, 20, 10]))
# import argparse
# def find_max_profit(prices):
# pass
# if __name__ == '__main__':
# # This is just some code to accept inputs from the command line
# parser = argparse.ArgumentParser(description='Find max profit from prices.')
# parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
# args = parser.parse_args()
# print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers)) | true |
55b20ca41e543233e4fb7ba479ac3093a8b3b07d | Mauricio-Fortune/Python-Projects | /randturtle.py | 1,964 | 4.25 | 4 | # Mauricio Fortune Panizo
# COP 2930
# Python turtle with random number
# 09/10/12
import turtle
import random
#what do they want to draw
shape = (input("Do you want a rectangle, triangle, or both?\n"))
turtle.pencolor("violet")
turtle.fillcolor("blue")
#Rectangle
if shape == "rectangle" or shape == "Rectangle" or shape == "RECTANGLE":
#sides of rectangle and turtle alignment
Sside= random.randint(100, 220)
Lside= random.randint(320, 520)
turtle.penup()
turtle.left(180)
turtle.forward(Lside/2)
#rectangle being drawn
turtle.begin_fill()
turtle.pendown()
turtle.right (90)
turtle.forward(Sside)
turtle.right (90)
turtle.forward(Lside)
turtle.right(90)
turtle.forward(Sside)
turtle.right (90)
turtle.forward(Lside)
turtle.end_fill()
#Triangle
elif shape == "triangle" or shape == "Triangle" or shape == "TRIANGLE":
length = random.randint (100, 500)
turtle.penup()
turtle.left(180)
turtle.forward(length/2)
turtle.left(90)
turtle.forward(length/2)
turtle.pendown()
turtle.begin_fill()
turtle.left(150)
turtle.forward(length)
turtle.right(120)
turtle.forward(length)
turtle.right(120)
turtle.forward(length)
turtle.end_fill()
#Both
else:
#Sides of rectangle
Sside= random.randint(60, 170)
Lside= random.randint(200, 310)
#Sides of triangle
length = random.randint (100, 400)
turtle.penup()
turtle.left(180)
turtle.forward(Lside + 10)
turtle.pendown()
#rectangle
turtle.right (90)
turtle.forward(Sside)
turtle.right (90)
turtle.forward(Lside)
turtle.right(90)
turtle.forward(Sside)
turtle.right (90)
turtle.forward(Lside)
turtle.penup()
turtle.right(180)
turtle.forward(Lside+20)
turtle.pendown()
#triangle
turtle.left(60)
turtle.forward(length)
turtle.right(120)
turtle.forward(length)
turtle.right(120)
turtle.forward(length)
| true |
3c757e0e0ab2e6b6a48b8f0cc4e4a4b2360afb36 | SarveshMohan89/Python-Projects | /grade.py | 580 | 4.375 | 4 | score = input("Enter Score: ")
try:
score=float(score)
except:
print("Enter a valid value")
quit()
if score >=0.9:
print("A")
elif score >=0.8:
print("B")
elif score >=0.7:
print("C")
elif score >=0.6:
print("D")
elif score <0.6:
print("F")
# Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade.If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.
| true |
8d5b7d048e87d6fdd6fc7e7c09f60a2d3b17439e | SarveshMohan89/Python-Projects | /Pay.py | 564 | 4.28125 | 4 | hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
r= float(rate)
if h <= 40:
pay = h * r
elif h > 40:
pay = 40*r + (h-40)*r*1.5
print (pay)
#Write a program to prompt the user for hours and rate per hour using input to compute gross pay.Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number
| true |
cb0cd132a4af328cb1007a0ece0b6f6935f5c240 | cinxdy/Python_practice | /Python_Workbook/B08.py | 534 | 4.1875 | 4 | num1 = int(input('number 1?'))
num2 = int(input('number 2?'))
num3 = int(input('number 3?'))
if num1==num2 or num2==num3 or num1==num3 :
print('condition1 satisfied')
if (num1>50 and num2>50) or (num2>50 and num3>50) or (num1>50 and num3>50) :
print('condition2 satisfied')
if num1+num2 == num3 or num2+num3 == num1 or num1+num3 == num1 :
print('condition3 satisfied')
if (num2%num1 == 0 and num3%num1 == 0) or (num1%num2 == 0 and num3%num2 == 0) or (num1%num3 == 0 and num2%num3 == 0) :
print('condition4 satisfied') | false |
fa757a907024fabdf8c6eca41cb99a5ad539fd6f | pBouillon/codesignal | /arcade/intro/3_Exploring_the_Waters/palindromeRearranging.py | 757 | 4.25 | 4 | """
Given a string, find out if its characters can be rearranged to form a palindrome.
Example
For inputString = "aabb", the output should be
palindromeRearranging(inputString) = true.
We can rearrange "aabb" to make "abba", which is a palindrome.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string inputString
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 50.
[output] boolean
true if the characters of the inputString can be rearranged to form a palindrome, false otherwise.
"""
def palindromeRearranging(inputString):
inputString = ''.join(set([x for x in inputString if inputString.count(x) % 2 != 0]))
return len(inputString) < 2
| true |
46e7b658c7f7d1e5cbe22662800a9eedf480148a | pBouillon/codesignal | /arcade/python/1_Slithering_in_Strings/Convert_Tabs.py | 1,221 | 4.28125 | 4 | """
You found an awesome customizable Python IDE that has
almost everything you'd like to see in your working environment.
However, after a couple days of coding you discover that there is
one important feature that this IDE lacks: it cannot convert
tabs to spaces. Luckily, the IDE is easily customizable, so you
decide to write a plugin that would convert all tabs in the code
into the given number of whitespace characters.
Implement a function that, given a piece of code and a positive
integer x will turn each tabulation character in code into x
whitespace characters.
Example
For code = "\treturn False" and x = 4, the output should be
convertTabs(code, x) = " return False".
Input/Output
[execution time limit] 4 seconds (py3)
[input] string code
Your piece of code.
Guaranteed constraints:
0 ≤ code.length ≤ 1500.
[input] integer x
The number of whitespace characters (' ') that should replace each occurrence of the tabulation character ('\t').
Guaranteed constraints:
1 ≤ x ≤ 16.
[output] string
The given code with tabulation characters expanded according to x.
"""
def convertTabs(code, x):
return code.replace('\t', ' ' * x)
| true |
d9dafdd492d3d28036bae95508f9bc80582eca24 | pBouillon/codesignal | /arcade/the_core/2_Corner_of_0s_and_1s/Mirror_Bits.py | 505 | 4.1875 | 4 | """
Reverse the order of the bits in a given integer.
Example
For a = 97, the output should be
mirrorBits(a) = 67.
97 equals to 1100001 in binary, which is 1000011 after
mirroring, and that is 67 in base 10.
For a = 8, the output should be
mirrorBits(a) = 1.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer a
Guaranteed constraints:
5 ≤ a ≤ 105.
[output] integer
"""
def mirrorBits(a):
return int('{:b}'.format(a)[::-1], 2)
| true |
bcf2fee9bf1b50855607e2b748080ad319468f7b | pBouillon/codesignal | /arcade/intro/9_Eruption_of_Light/Is_MAC48_Address.py | 1,343 | 4.53125 | 5 | """
A media access control address (MAC address) is a unique identifier
assigned to network interfaces for communications on the physical
network segment.
The standard (IEEE 802) format for printing MAC-48 addresses in
human-friendly form is six groups of two hexadecimal digits
(0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).
Your task is to check by given string inputString whether it
corresponds to MAC-48 address or not.
Example
For inputString = "00-1B-63-84-45-E6", the output should be
isMAC48Address(inputString) = true;
For inputString = "Z1-1B-63-84-45-E6", the output should be
isMAC48Address(inputString) = false;
For inputString = "not a MAC-48 address", the output should be
isMAC48Address(inputString) = false.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string inputString
Guaranteed constraints:
15 ≤ inputString.length ≤ 20.
[output] boolean
true if inputString corresponds to MAC-48 address naming rules, false otherwise.
"""
def isMAC48Address(inputString):
if len(inputString.split('-')) != 6:
return False
for i in inputString.split('-'):
if len(i) != 2:
return False
try:
int(i, 16)
except ValueError:
return False
return True
| true |
c17719db8ae21f8174e7a4526c9f0e71eb92d32a | pBouillon/codesignal | /arcade/python/5_Fumbling_In_Functionnal/Fix_Result.py | 1,332 | 4.125 | 4 | """
Your teacher asked you to implement a function that calculates
the Answer to the Ultimate Question of Life, the Universe, and
Everything and returns it as an array of integers. After several
hours of hardcore coding you managed to write such a function,
and it produced a quite reasonable result. However, when you decided
to compare your answer with results of your classmates, you discovered
that the elements of your result are roughly 10 times greater than
the ones your peers got.
You don't have time to investigate the problem, so you need to
implement a function that will fix the given array for you. Given
result, return an array of the same length, where the ith element
is equal to the ith element of result with the last digit dropped.
Example
For result = [42, 239, 365, 50], the output should be
fixResult(result) = [4, 23, 36, 5].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer result
The result your function produced, where each element is
greater than 9.
Guaranteed constraints:
0 ≤ result.length ≤ 15,
10 ≤ result[i] ≤ 105.
[output] array.integer
Array consisting of elements of result with last digits dropped.
"""
def fixResult(result):
def fix(x):
return x // 10
return list(map(fix, result))
| true |
d93215df09999419db4bab6bc4f8eb39b2aeb127 | pBouillon/codesignal | /arcade/python/6_Caravan_of_Collections/Unique_Characters.py | 939 | 4.28125 | 4 | """
You need to compress a large document that consists of a
small number of different characters. To choose the best
encoding algorithm, you would like to look closely at the
characters that comprise this document.
Given a document, return an array of all unique characters
that appear in it sorted by their ASCII codes.
Example
For document = "Todd told Tom to trot to the timber",
the output should be
uniqueCharacters(document)
= [' ', 'T', 'b', 'd', 'e', 'h', 'i', 'l', 'm', 'o', 'r', 't'].
Input/Output
[execution time limit] 4 seconds (py3)
[input] string document
A string consisting of English letters, whitespace characters and punctuation marks.
Guaranteed constraints:
1 ≤ document.length ≤ 80.
[output] array.char
A sorted array of all the unique characters that appear in the document.
"""
def uniqueCharacters(document):
return sorted(list(set([c for c in document])))
| true |
c74785827938751410f2ca78676c167697e02ce5 | digitalcourtney87/lpthw | /ex3.py | 972 | 4.625 | 5 | # prints the string "I will now count my chickens:"
print("I will now count my chickens:")
# prints hens and roosters and the calculation after each string
print("Hens", 25 + 30 / 6)
print("Roosters", 100 - 25 * 3 % 4)
# prints the string "I wil now count my eggs"
print("I will now count my eggs:")
# prints the calculation
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
# prints the string "Is it true that....?"
print("Is it true that 3 + 2 < 5 - 7?")
# Asks whether 3+2 is less that 5-7
print(3 + 2 < 5 - 7)
# prints the string asking the question then does the calculation after the comma
print("What is 3 + 2?", 3 + 2)
print("What is 5 - 7?", 5 - 7)
# prints a statement
print("Oh, that's why it's false.")
# prints a statement
print("How about some more.")
# prints some more strings and calculations with greater, greater or equal and less or equal
print("Is it greater?", 5 > -2)
print("is it greater or equal?", 5>= -2)
print("Is it less or equal?", 5 <= -2)
| true |
f64c77c65741ef75db8bab6200a1714c05ac954e | jamincen/Python3X_Daily_question | /24_simple_operation_of_strings.py | 1,390 | 4.5 | 4 | """
字符串的三种表达方式
. single quotes '
. double quotes "
. three quotes ''' # multi-line string
"""
## 拼接字符串的方式
a = 'hello'
b = 'world'
print(a + ' ' + b)
print(a, b)
print('%s %s' % (a, b)) # 推荐,效率高
print('hello''world')
print('{}{}'.format(a, b)) # 推荐,效率高
print(''.join(['hello', 'world']))
## 字符串常用的操作
msg = 'python,java,javascript'
# 通过','分隔字符串,返回数组
print('\n 分隔字符串,: \n', msg.split(' '))
# 每次单词的首字母大写
print('\n 将字符串的所有单词首字母大写:\n', msg.title())
# 是否已python开头(startswith) 结尾(endswith),如果是返回True,不是返回False
print('\n 是否已python开头: \n', msg.startswith('python'))
print('\n 是否已python结尾: \n', msg.endswith('python'))
print('\n 将字符串的第一个字符大写: \n', msg.capitalize())
print('\n 将所有字符大写: \n', msg.upper())
print('\n 将所有字符小写: \n', msg.lower())
## 字符串的截取、查找、替换
msg = 'abcdefgaaa'
print('\n 输出前3个字符: \n', msg[0: 3]) # 从0开始
print('\n 输出最后5个字符: \n', msg[-5:])
print('\n 替换字符a为v:\n', msg.replace('a', 'v'))
print('\n 查找元素c的位置: \n', msg.find('c'))# 从0开始,a-0,b-1,c-3
| false |
2c6fb80d74f7c752c451cb1d28c91fa8767de50e | RuggeroPiazza/rock_paper_scissors | /rockPaperScissors.py | 1,998 | 4.15625 | 4 | import random
"""
This program execute a given number of runs of
'Rock, Paper, Scissors' game and returns stats about it.
"""
choices = ['paper', 'rock', 'scissors']
winning = [('paper', 'rock'), ('rock', 'scissors'), ('scissors', 'paper')]
def run():
"""INPUT: no input.
OUTPUT: string.
The function randomly choose and returns a winner"""
game = (random.choice(choices), random.choice(choices))
if game not in winning:
if game[0] == game[1]:
return 'draw'
else:
return 'p2'
else:
return 'p1'
def counter(runs):
"""INPUT: integer; number of runs.
OUTPUT: integers; number of wins per player and draws.
The function appends, counts and returns each run's result."""
results = []
p1, p2, draw = (0, 0, 0)
for _ in range(runs):
results.append(run())
for item in results:
if item == 'p1':
p1 += 1
if item == 'p2':
p2 += 1
if item == 'draw':
draw += 1
return p1, p2, draw
def stats():
"""INPUT: no input.
OUTPUT: strings; stats about the simulation.
The function calculates and displays the stats."""
p1_wins, p2_wins, draws = counter(num_of_runs)
tot_wins = p1_wins + p2_wins + draws
perc_p1 = (p1_wins / tot_wins) * 100
perc_p2 = (p2_wins / tot_wins) * 100
perc_draws = (draws / tot_wins) * 100
print(f"After executing {num_of_runs} runs:")
print("Player 1: {} wins {} %".format(p1_wins, round(perc_p1)))
print("Player 2: {} wins {} %".format(p2_wins, round(perc_p2)))
print("Draws : {} {} %.".format(draws, round(perc_draws)))
def validate_input(msg):
while True:
try:
user_input = int(input(msg))
except ValueError:
print("Input not valid!")
else:
return user_input
if __name__ == "__main__":
num_of_runs = validate_input("Please enter a number of simulation: ")
stats()
| true |
0cd51399d1c1d5e08cdc522da22e7b0ab4aaa4d2 | manasmdg3/python | /F2CTemperature.py | 601 | 4.28125 | 4 | #Fahrenheit to Celcius Temperature
def c2fConverter():
temp = float(input("\nEnter Temperature in Celcius: "))
print(str(temp)+" degree Celcius in Fahrenheit is: "+"{:.2f}".format((9*temp)/5+32))
def f2cConverter():
temp = float(input("\nEnter Temperature in Fahrenheit: "))
print(str(temp)+" degree Fahrenheit in Celcius is: "+"{:.2f}".format((temp-32)*5/9))
choice = int(input("Temperature Converter:\n1. Celcius to Fahrenheit\n2. Fahrenheit to Celcius\nEnter your choice: "))
if choice == 1:
c2fConverter()
elif choice == 2:
f2cConverter()
else:
print("Wrong Choice!")
| false |
9aff11cc554d9567141f292091d60eea7e47473c | renegadevi/hour-calculator | /main.py | 2,678 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Hour Calculator
Quickly made hour calculator for 24h day clock to prevent the need of relying
on a website for simple time calculations. Does the work; enter timestamps,
shows results in a table of elapsed time and total hours.
"""
import datetime
import sys
import os
__title__ = "Hour Calculator"
__author__ = "Philip Andersen <philip.andersen@codeofmagi.net>"
__license__ = "MIT"
__version__ = "1.0"
__copyright__ = "Copyright 2018 (c) Philip Andersen"
def clear_screen():
return os.system('cls' if os.name == 'nt' else 'clear')
def format_timedelta(time):
minutes, seconds = divmod(time.seconds + time.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
def get_interger(string):
while True:
try:
return int(input(string))
except ValueError:
print('Not a valid number\n')
continue
break
def get_timestamps(times, time_format='%H:%M'):
timestamps = {}
for time in range(0, times):
while True:
try:
print("\nTimestamp {} ({})".format(time+1, time_format))
start = datetime.datetime.strptime(
input("- Start: "),
time_format
)
end = datetime.datetime.strptime(
input("- End: "),
time_format
)
timestamps[time+1] = [start, end, end-start]
except ValueError as time_error:
print(time_error)
continue
break
return timestamps
def get_total_hours(timestamps):
return format_timedelta(
sum([y[2] for x, y in timestamps.items()], datetime.timedelta())
)
def print_table(timestamps, time_format='%H:%M'):
clear_screen()
print('='*40)
print(' # Start End Time elapsed')
print('='*40)
for x, y in timestamps.items():
print(" {} {} {} {}".format(
x,
y[0].strftime(time_format),
y[1].strftime(time_format),
y[2]
))
print('='*40)
print(' TOTAL HOURS: {}\n'.format(get_total_hours(timestamps)))
def main():
# Just added for time saving sake, not that pretty.
if len(sys.argv) > 1:
try:
print_table(get_timestamps(int(sys.argv[1])))
except:
print('Not a valid number')
print_table(get_timestamps(get_interger("How many days?: ")))
else:
print_table(get_timestamps(get_interger("How many days?: ")))
if __name__ == "__main__":
main()
| true |
c0da82154044bc19c0417101c83f80c25c3b160e | PdxCodeGuild/Programming102 | /resources/example_lessons/unit_2/grading_with_functions.py | 1,633 | 4.25 | 4 | import random # for randint()
#### add this function if there's time
"""# return True if the number is between 1 and 100
# return False otherwise
def get_modifier(score):
'''
return a grade modifier based on a score
'''
# isolate the ones digit of the score with % 10
ones = score % 10
modifier = ''
if ones <= 3:
modifier = '-'
elif ones >= 7:
modifier = '+'
return modifier
"""
# define a function to convert scores to letter grades
def get_grade(score):
# convert to letter grade
if score >= 90 and score <= 100:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
elif score >= 0:
grade = 'F'
# return the letter grade
return grade
while True:
# ask the user for their score
user_score = input("Please enter your score 1-100 or 'q' to quit: ")
# exit if the user entered 'q'
if user_score == 'q':
print('Goodbye')
break # end the loop
# convert the score to an integer
user_score = int(user_score)
# generate a random rival score
rival_score = random.randint(0, 100)
# convert the user score with the function
user_grade = get_grade(user_score)
# convert the rival score with the function
rival_grade = get_grade(rival_score)
'''
# get the user's grade modifier
user_mod = get_modifier(user_score)
# get the user's grade modifier
rival_mod = get_modifier(rival_score)
'''
print(f'user: {user_score} - {user_grade}') #{user_mod}')
print(f'rival: {rival_score} - {rival_grade}') # {rival_mod}')
| true |
0fb9823e4724afbace1b7b392876fc3d6661f933 | pramodchahar/Python_A_2_Z | /lists/slices.py | 540 | 4.5625 | 5 | ###########################
# Slicing of List
###########################
# makes new lists using slices or parts of original lists
# list_name[start:end:step]
#sort of similar to range(start,end,step size)
num_list=[11,22,33,44,55,66,77,88,99]
print(num_list[3:])
print(num_list[5:])
print(num_list[-1:])
print(num_list[-3:])
print(num_list[:])
print(num_list[:3])
print(num_list[4:7])
print(num_list[-4:8])
print(num_list[::3])
print(num_list[::-3])
# modify part of list
num_list[2:5]=['a','b','c']
print(num_list)
| true |
2eb5d6e96aa9cc6b08b66e5724bb3b2bb7fc9960 | Javenkm/Functions-Basic-2 | /functions_basic2.py | 2,376 | 4.28125 | 4 | # 1. Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: cuntdown(5) should return [5, 4, 3, 2, 1].
def countDown(num):
list = []
for x in range(num, -1, -1):
list.append(x)
return list
print(countDown(5))
# 2. Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1, 2]) should print 1 and return 2.
def printReturn(list):
print(list[0])
return(list[1])
printReturn([1, 2])
# 3. First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (firstvalue: 1 + length: 5).
def firstPlusLen(list):
first = list[0]
length = len(list)
return first + length
print(firstPlusLen([1,2,3,4,5,6,7,8,9,10]))
# 4. Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False.
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False.
def greaterSecond(list):
newList = []
count = 0
for x in range(0, len(list), 1):
if list[x] > list[1]:
newList.append(list[x])
count += 1
print(count)
if count < 2:
return False
else:
return newList
print(greaterSecond([5, 2, 3, 2, 1, 4, 6, 8, 1, 1, 9]))
# 5. This Length, That Value - Write a function that accets two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4, 7) should return [7,7,7,7].
# Example: length_and_value(6, 2) should return [2,2,2,2,2,2].
def lenValue(size, value):
list = []
for x in range(0, size, 1):
list.append(value)
return list
print(lenValue(2, 1))
print(lenValue(4, 7))
print(lenValue(6, 2))
print(lenValue(8, 3))
print(lenValue(10, 5)) | true |
4e0730d471146edd5bb196ff536c023e67eb5453 | akash123456-hub/hello.py | /vns2.py | 836 | 4.15625 | 4 | '''
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
'''
'''
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
'''
#change list items
'''
thislist = ["apple","banana","cherry"]
thislist[1] = "blackcurrant"
print(thislist)
'''
'''
class Employee:
company = "google"
def getsalary(self):
print("salary is 10k")
harry = Employee()
harry.getsalary()
'''
| true |
9421a2ef16ebab41bc62af119d3a39013ae06099 | clementeqp/Python_Clemen | /09-In_Not.py | 383 | 4.3125 | 4 | # con una lista
trabajadores=["Laura", "Manolo", "Jorge", "Teresa"]
if "Manolo" in trabajadores:
print("Manolo esta en la lista")
else:
print("Manolo no esta en la lista")
# con un string
trabajadores2="Laura", "Manolo", "Jorge", "Teresa"
if "Manolo" not in trabajadores2:
print("Manolo donde esta?")
else:
print("Manolo esta en la lista") | false |
1cfd08df97ae7e4228ec082f096432bb2beee189 | Brokenshire/codewars-projects | /Python/six_kyu/in_array.py | 1,066 | 4.28125 | 4 | # Python solution for 'Which are in?' codewars question.
# Level: 6 kyu
# Tags: REFACTORING, ARRAYS, SEARCH, ALGORITHMS, LISTS, DATA STRUCTURES, and STRINGS.
# Author: Jack Brokenshire
# Date: 11/06/2020
import unittest
from re import search
def in_array(array1, array2):
"""
Finds which words within array1 are withing array2 in sorted order.
:param array1: an array of strings.
:param array2: an array of strings.
:return: a sorted array in lexicographical order of the strings of a1 which are substrings of strings of a2.
"""
result = []
for i in array1:
for j in array2:
if search(i, j) and i not in result:
result.append(i)
return sorted(result)
class TestInArray(unittest.TestCase):
"""Class to test 'in_array' function"""
def test_in_array(self):
a1 = ["live", "arp", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
r = ['arp', 'live', 'strong']
self.assertEquals(in_array(a1, a2), r)
if __name__ == '__main__':
unittest.main()
| true |
850ef1bc3215064426abed63def8de9a52fd8cc4 | Brokenshire/codewars-projects | /Python/six_kyu/likes.py | 1,552 | 4.375 | 4 | # Python solution for 'Who likes it?' codewars question.
# Level: 6 kyu
# Tags: Fundamentals, Formatting, Algorithms, and Strings.
# Author: Jack Brokenshire
# Date: 19/02/2020
import unittest
def likes(names):
"""
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other
items. We want to create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people
who like an item. For 4 or more names, the number in and 2 others simply increases.
:param names: A list of names whom like a post.
:return: Nicely formatted string of people liking a post.
"""
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
}[min(4, n)].format(*names[:3], others=n-2)
class TestLikes(unittest.TestCase):
"""Class to test 'likes' function"""
def test_likes(self):
self.assertEqual(likes([]), 'no one likes this')
self.assertEqual(likes(['Peter']), 'Peter likes this')
self.assertEqual(likes(['Jacob', 'Alex']), 'Jacob and Alex like this')
self.assertEqual(likes(['Max', 'John', 'Mark']), 'Max, John and Mark like this')
self.assertEqual(likes(['Alex', 'Jacob', 'Mark', 'Max']), 'Alex, Jacob and 2 others like this')
if __name__ == '__main__':
unittest.main()
| true |
a6c9f153e08a44a65cd9cd314229b7b18a7a60f6 | Brokenshire/codewars-projects | /Python/seven_kyu/find.py | 636 | 4.53125 | 5 | # Python solution for 'Sum of all the multiples of 3 or 5' codewars question.
# Level: 7 kyu
# Tags: FUNDAMENTALS.
# Author: Jack Brokenshire
# Date: 18/05/2020
import unittest
def find(n):
"""
Finds the sum of all multiples of 3 and 5 of an integer.
:param n: an integer value.
:return: the sum of all multiples of 3 and 5.
"""
return sum(x for x in range(n+1) if x % 5 == 0 or x % 3 == 0)
class TestFind(unittest.TestCase):
"""Class to test 'find' function"""
def test_find(self):
self.assertEqual(find(5), 8)
self.assertEqual(find(10), 33)
if __name__ == '__main__':
unittest.main()
| true |
f66d99f8800f29f0da719a02ca7df5666637ff11 | Brokenshire/codewars-projects | /Python/seven_kyu/square_digits.py | 891 | 4.4375 | 4 | # Python solution for 'Simple Pig Latin' codewars question.
# Level: 7 kyu
# Tags: Fundamentals, Mathematics, Algorithms, and Numbers
# Author: Jack Brokenshire
# Date: 11/02/2020
import unittest
def square_digits(num):
"""
Welcome. In this kata, you are asked to square every digit of a number.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer
:param num: input integer value.
:return: integer of all digits within the input number squared.
"""
return int("".join(map(str, [x ** 2 for x in list(map(int, str(num)))])))
class TestSquareDigits(unittest.TestCase):
"""Class to test 'square_digits' function"""
def test_square_digits(self):
self.assertEqual(square_digits(9119), 811181)
if __name__ == '__main__':
unittest.main()
| true |
19937ad4042fe640d47bc40486434f0a2fd86c3e | Brokenshire/codewars-projects | /Python/four_kyu/permutations.py | 962 | 4.1875 | 4 | # Python solution for 'Permutations' codewars question.
# Level: 4 kyu
# Tags: ALGORITHMS, PERMUTATIONS, and STRINGS.
# Author: Jack Brokenshire
# Date: 13/05/2020
import unittest
import itertools
def permutations(string):
"""
Create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all
letters from the input in all possible orders.
:param string: a string value.
:return: all permutations of the string.
"""
return list("".join(x) for x in set(itertools.permutations(string)))
class TestPermutations(unittest.TestCase):
"""Class to test 'permutations' function"""
def test_permutations(self):
self.assertEqual(sorted(permutations('a')), ['a']);
self.assertEqual(sorted(permutations('ab')), ['ab', 'ba'])
self.assertEqual(sorted(permutations('aabb')), ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'])
if __name__ == '__main__':
unittest.main()
| true |
e48a8a7273db7f74a15710e01769a58535e3fdcd | Brokenshire/codewars-projects | /Python/seven_kyu/in_asc_order.py | 1,046 | 4.125 | 4 | # Python solution for "Are the numbers in order?" codewars question.
# Level: 7 kyu
# Tags: ALGORITHMS, FUNDAMENTALS, MATHEMATICS, NUMBERS, CONTROL FLOW, BASIC LANGUAGE FEATURES, and OPTIMIZATION.
# Author: Jack Brokenshire
# Date: 06/04/2020
import unittest
def in_asc_order(arr):
"""
Determines if the given array is in ascending order or not.
:param arr: an integer array.
:return: True if array is in ascending order otherwise, False.
"""
return arr == sorted(arr)
class TestInAscOrder(unittest.TestCase):
"""Class to test "in_asc_order" function"""
def test_in_asc_order(self):
self.assertEqual(in_asc_order([1, 2]), True)
self.assertEqual(in_asc_order([2, 1]), False)
self.assertEqual(in_asc_order([1, 2, 3]), True)
self.assertEqual(in_asc_order([1, 3, 2]), False)
self.assertEqual(in_asc_order([1, 4, 13, 97, 508, 1047, 20058]), True)
self.assertEqual(in_asc_order([56, 98, 123, 67, 742, 1024, 32, 90969]), False)
if __name__ == "__main__":
unittest.main()
| true |
cf815b0af79820535c15167786267ec93245cfc2 | Brokenshire/codewars-projects | /Python/six_kyu/count_smileys.py | 1,811 | 4.21875 | 4 | # Python solution for 'Count the smiley faces!' codewars question.
# Level: 6 kyu
# Tags: Fundamentals, Regular Expressions, Declarative Programming, Advanced Language Features, and Strings.
# Author: Jack Brokenshire
# Date: 06/02/2020
import unittest
def count_smileys(arr):
"""
Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
:param arr: An array.
:return: the total number of smiling faces.
"""
total = 0
for x in arr:
if x[0] == ":" or x[0] == ";":
if x[1] == ")" or x[1] == "D":
total += 1
elif x[1] == "-" or x[1] == "~":
if x[2] == ")" or x[2] == "D":
total += 1
return total
class TestCountSmileys(unittest.TestCase):
"""Class to test 'count_smileys' function"""
def test_count_smileys(self):
self.assertEqual(count_smileys([':)', ';(', ';}', ':-D']), 2);
self.assertEqual(count_smileys([';D', ':-(', ':-)', ';~)']), 3);
self.assertEqual(count_smileys([';]', ':[', ';*', ':$', ';-D']), 1);
self.assertEqual(count_smileys([]), 0);
self.assertEqual(count_smileys([':D',':~)',';~D',':)']), 4);
self.assertEqual(count_smileys([':)',':(',':D',':O',':;']), 2);
self.assertEqual(count_smileys([';]', ':[', ';*', ':$', ';-D']), 1);
if __name__ == '__main__':
unittest.main()
| true |
a5746557d0b41917a459998bc393246117f4ba40 | Brokenshire/codewars-projects | /Python/eight_kyu/reversed_string.py | 725 | 4.15625 | 4 | # Python solution for 'Reversed Strings' codewars question.
# Level: 8 kyu
# Tags: FUNDAMENTALS and STRINGS.
# Author: Jack Brokenshire
# Date: 27/06/2020
import unittest
def solution(string):
"""
Complete the solution so that it reverses the string passed into it.
:param string: a string value.
:return: the sting reversed.
"""
return string[::-1]
class TestSolution(unittest.TestCase):
"""Class to test 'solution' function"""
def test_solution(self):
self.assertEqual(solution('world'), 'dlrow')
self.assertEqual(solution('hello'), 'olleh')
self.assertEqual(solution(''), '')
self.assertEqual(solution('h'), 'h')
if __name__ == '__main__':
unittest.main()
| true |
ffa315450ca504e52aa8d42b1a66e75bc8273040 | Brokenshire/codewars-projects | /Python/seven_kyu/reverse_letter.py | 880 | 4.25 | 4 | # Python solution for 'Simple Fun #176: Reverse Letter' codewars question.
# Level: 7 kyu
# Tags: FUNDAMENTALS.
# Author: Jack Brokenshire
# Date: 03/05/2020
import unittest
def reverse_letter(string):
"""
Given a string str, reverse it omitting all non-alphabetic characters.
:param string: a string value input.
:return: the reverse of the string containing only letters.
"""
return "".join(x for x in string[::-1] if x.isalpha())
class TestReverseLetter(unittest.TestCase):
"""Class to test 'reverse_letter' function"""
def test_reverse_letter(self):
self.assertEqual(reverse_letter("krishan"), "nahsirk")
self.assertEqual(reverse_letter("ultr53o?n"), "nortlu")
self.assertEqual(reverse_letter("ab23c"), "cba")
self.assertEqual(reverse_letter("krish21an"), "nahsirk")
if __name__ == '__main__':
unittest.main()
| true |
3187a208fd79756ce2f348354e0439249a5d786a | Brokenshire/codewars-projects | /Python/six_kyu/find_missing_number.py | 991 | 4.21875 | 4 | # Python solution for 'Number Zoo Patrol' codewars question.
# Level: 6 kyu
# Tags: ALGORITHMS, PERFORMANCE, MATHEMATICS, and NUMBERS.
# Author: Jack Brokenshire
# Date: 09/05/2020
import unittest
def find_missing_number(numbers):
"""
akes a shuffled list of unique numbers from 1 to n with one element missing (which can be any number including n).
:param numbers: array of intergers.
:return: this missing number.
"""
total = 1
for i in range(2, len(numbers) + 2):
total += i
total -= numbers[i - 2]
return total
class TestFindMissingNumber(unittest.TestCase):
"""Class to test 'find_missing_number' function"""
def test_find_missing_number(self):
self.assertEqual(find_missing_number([2, 3, 4]), 1)
self.assertEqual(find_missing_number([1, 3, 4]), 2)
self.assertEqual(find_missing_number([1, 2, 4]), 3)
self.assertEqual(find_missing_number([1, 2, 3]), 4)
if __name__ == '__main__':
unittest.main()
| true |
2227299998c5819a79b6ad295b37d46e55ad626f | Brokenshire/codewars-projects | /Python/seven_kyu/odd_or_even.py | 972 | 4.46875 | 4 | # Python solution for 'Odd or Even?' codewars question.
# Level: 7 kyu
# Tags: Fundamentals, Arithmetic, Mathematics, Algorithms, Numbers, and Arrays.
# Author: Jack Brokenshire
# Date: 15/02/2020
import unittest
def odd_or_even(arr):
"""
Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string
matching "odd" or "even". If the input array is empty consider it as: [0] (array with a zero).
:param arr: A list of numbers.
:return: 'even' if the sum of the numbers in the list is even, otherwise 'odd'.
"""
return "even" if sum(arr) % 2 == 0 else "odd"
class TestOddOrEven(unittest.TestCase):
"""Class to test 'odd_or_even' function"""
def test_odd_or_even(self):
self.assertEqual(odd_or_even([0, 1, 2]), "odd")
self.assertEqual(odd_or_even([0, 1, 3]), "even")
self.assertEqual(odd_or_even([1023, 1, 2]), "even")
if __name__ == '__main__':
unittest.main()
| true |
a77599b1b182804ef47d14662e3e4a6f8640af86 | Brokenshire/codewars-projects | /Python/seven_kyu/get_count.py | 806 | 4.1875 | 4 | # Python solution for 'Vowel Count' codewars question.
# Level: 7 kyu
# Tags: Fundamentals, Strings, and Utilities
# Author: Jack Brokenshire
# Date: 09/02/2020
import unittest
def get_count(inputStr):
"""
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.
:param inputStr: input string value.
:return: the number (count) of vowels in the given string.
"""
return sum(1 for i in inputStr if i in ["a", "e", "i", "o", "u"])
class TestGetCount(unittest.TestCase):
"""Class to test 'get_count' function"""
def test_get_count(self):
self.assertEqual(get_count("abracadabra"), 5)
if __name__ == '__main__':
unittest.main()
| true |
bca58d3cfb38f49d0c0a227539eb638498ae5e31 | Brokenshire/codewars-projects | /Python/seven_kyu/convert_my_dollars.py | 2,708 | 4.3125 | 4 | # Python solution for "Currency Conversion" codewars question.
# Level: 7 kyu
# Tags: FUNDAMENTALS, MATHEMATICS, ALGORITHMS, NUMBERS, and ALGEBRA.
# Author: Jack Brokenshire
# Date: 05/04/2020
import unittest
CONVERSION_RATES = {
"Argentinian Peso": 10,
"Armenian Dram": 478,
"Bangladeshi Taka": 1010010,
"Croatian Kuna": 110,
"Czech Koruna": 10101,
"Dominican Peso": 110000,
"Egyptian Pound": 18,
"Guatemalan Quetzal": 111,
"Haitian Gourde": 1000000,
"Indian Rupee": 63,
"Japanese Yen": 1101111,
"Kenyan Shilling": 1100110,
"Nicaraguan Cordoba": 11111,
"Norwegian Krone": 1000,
"Philippine Piso": 110010,
"Romanian Leu": 100,
"Samoan Tala": 11,
"South Korean Won": 10000100011,
"Thai Baht": 100000,
"Uzbekistani Som": 8333,
"Venezuelan Bolivar": 1010,
"Vietnamese Dong": 101100000101101
}
def convert_my_dollars(usd, currency):
"""
If a country's currency begins with a consonant, then the conversion rate has been tampered with.
:param usd: integer of amount of united states dollars.
:param currency: string of currency to be converted.
:return: the amount of foreign currency you will receive when you exchange your United States Dollars.
"""
if currency[0] in "AEIOU":
return "You now have {} of {}.".format(CONVERSION_RATES[currency] * usd, currency)
else:
return "You now have {} of {}.".format(int(str(CONVERSION_RATES[currency]), 2) * usd, currency)
class TestConvertMyDollars(unittest.TestCase):
"""Class to test "convert_my_dollars" function"""
def test_convert_my_dollars(self):
self.assertEqual(convert_my_dollars(7, "Armenian Dram"), "You now have 3346 of Armenian Dram.")
self.assertEqual(convert_my_dollars(322, "Armenian Dram"), "You now have 153916 of Armenian Dram.")
self.assertEqual(convert_my_dollars(25, "Bangladeshi Taka"), "You now have 2050 of Bangladeshi Taka.")
self.assertEqual(convert_my_dollars(730, "Bangladeshi Taka"), "You now have 59860 of Bangladeshi Taka.")
self.assertEqual(convert_my_dollars(37, "Croatian Kuna"), "You now have 222 of Croatian Kuna.")
self.assertEqual(convert_my_dollars(40, "Croatian Kuna"), "You now have 240 of Croatian Kuna.")
self.assertEqual(convert_my_dollars(197, "Czech Koruna"), "You now have 4137 of Czech Koruna.")
self.assertEqual(convert_my_dollars(333, "Czech Koruna"), "You now have 6993 of Czech Koruna.")
self.assertEqual(convert_my_dollars(768, "Dominican Peso"), "You now have 36864 of Dominican Peso.")
self.assertEqual(convert_my_dollars(983, "Dominican Peso"), "You now have 47184 of Dominican Peso.")
if __name__ == "__main__":
unittest.main()
| false |
4c1ef91c4464eb933dfeb493523e27d408a89b30 | Brokenshire/codewars-projects | /Python/seven_kyu/even_chars.py | 1,045 | 4.5 | 4 | # Python solution for 'Return a string's even characters.' codewars question.
# Level: 7 kyu
# Tags: FUNDAMENTALS, STRING, AND SARRAYS.
# Author: Jack Brokenshire
# Date: 16/08/2020
import unittest
def even_chars(st):
"""
Finds all the even characters in a string.
:param st: string value.
:return: a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than
two characters or longer than 100 characters, the function should return "invalid string".
"""
if len(st) < 2 or len(st) > 100: return "invalid string"
else: return [st[i] for i in range(len(st)) if i % 2]
class TestEvenChars(unittest.TestCase):
"""Class to test 'even_chars' function"""
def test_even_chars(self):
self.assertEqual(even_chars("a"), "invalid string")
self.assertEqual(even_chars("abcdefghijklm"), ["b", "d", "f", "h", "j", "l"])
self.assertEqual(even_chars("aBc_e9g*i-k$m"), ["B", "_", "9", "*", "-", "$"])
if __name__ == "__main__":
unittest.main()
| true |
1790d87e28600368578483b8c0511619df107563 | Brokenshire/codewars-projects | /Python/seven_kyu/get_middle.py | 1,284 | 4.15625 | 4 | # Python solution for 'Get the Middle Character' codewars question.
# Level: 7 kyu
# Tags: Fundamentals, and Strings
# Author: Jack Brokenshire
# Date: 10/02/2020
import unittest
def get_middle(s):
"""
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is
odd, return the middle character. If the word's length is even, return the middle 2 characters.
:param s: A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000
in some test cases due to an error in the test cases). You do not need to test for this. This
is only here to tell you that you do not need to worry about your solution timing out.
:return: The middle character(s) of the word represented as a string.
"""
return s[int((len(s)-1)/2):int(len(s)/2+1)]
class TestGetMiddle(unittest.TestCase):
"""Class to test 'get_middle' function"""
def test_get_middle(self):
self.assertEqual(get_middle("test"), "es")
self.assertEqual(get_middle("testing"), "t")
self.assertEqual(get_middle("middle"), "dd")
self.assertEqual(get_middle("A"), "A")
self.assertEqual(get_middle("of"), "of")
if __name__ == '__main__':
unittest.main()
| true |
204d75a486784b74f705a51a2edc7f5989d5b554 | Brokenshire/codewars-projects | /Python/five_kyu/sum_pairs.py | 1,845 | 4.1875 | 4 | # Python solution for "Sum of Pairs" codewars question.
# Level: 5 kyu
# Tags: FUNDAMENTALS, PARSING, ALGORITHMS, STRINGS, MEMOIZATION, DESIGN PATTERNS, and DESIGN PRINCIPLES.
# Author: Jack Brokenshire
# Date: 08/04/2020
import unittest
def sum_pairs(ints, s):
"""
Finds the first pairs to equal the integer given.
of appearance that add up to form the sum.
:param ints: list of integers.
:param s: integer sum value.
:return: the first two values (parse from the left please) in order of appearance that add up to form the sum.
"""
seen = set()
for x in ints:
if s - x in seen:
return [s - x, x]
seen.add(x)
class TestSumPairs(unittest.TestCase):
"""Class to test "sum_pairs" function"""
def test_sum_pairs(self):
self.assertEqual(sum_pairs([1, 4, 8, 7, 3, 15], 8), [1, 7])
# Basic: %s should return [1, 7] for sum = 8
self.assertEqual(sum_pairs([1, -2, 3, 0, -6, 1], -6), [0, -6])
# Negatives: %s should return [0, -6] for sum = -6
self.assertEqual(sum_pairs([20, -13, 40], -7), None)
# No Match: %s should return None for sum = -7
self.assertEqual(sum_pairs([1, 2, 3, 4, 1, 0], 2), [1, 1])
# First Match From Left: %s should return [1, 1] for sum = 2
self.assertEqual(sum_pairs([10, 5, 2, 3, 7, 5], 10), [3, 7])
# First Match From Left REDUX!: %s should return [3, 7] for sum = 10
self.assertEqual(sum_pairs([4, -2, 3, 3, 4], 8), [4, 4])
# Duplicates: %s should return [4, 4] for sum = 8
self.assertEqual(sum_pairs([0, 2, 0], 0), [0, 0])
# Zeroes: %s should return [0, 0] for sum = 0
self.assertEqual(sum_pairs([5, 9, 13, -3], 10), [13, -3])
# Subtraction: %s should return [13, -3] for sum = 10
if __name__ == "__main__":
unittest.main()
| true |
0f702ff15d1d5b9145082f6402c50e7a282d49a8 | Brokenshire/codewars-projects | /Python/eight_kyu/make_negative.py | 714 | 4.21875 | 4 | # Python solution for 'Return Negative' codewars question.
# Level: 8 kyu
# Tags: FUNDAMENTALS and NUMBERS.
# Author: Jack Brokenshire
# Date: 11/04/2020
import unittest
def make_negative(number):
"""
Make a given number negative.
:param number: an integer value.
:return: the integer as a negative number.
"""
return -abs(number)
class TestMakeNegative(unittest.TestCase):
"""Class to test make_negative function"""
def test_make_negative(self):
self.assertEqual(make_negative(42), -42)
self.assertEqual(make_negative(1), -1)
self.assertEqual(make_negative(-5), -5)
self.assertEqual(make_negative(0), 0)
if __name__ == '__main__':
unittest.main()
| true |
8ce90fd19cf8df52af008dac2f8c61ad9054b3fb | Brokenshire/codewars-projects | /Python/five_kyu/pig_it.py | 880 | 4.21875 | 4 | # Python solution for 'Square Every Digit' codewars question.
# Level: 5 kyu
# Tags: Algorithms
# Author: Jack Brokenshire
# Date: 11/02/2020
import unittest
def pig_it(text):
"""
Move the first letter of each word to the end of it, then add "ay" to the end of the word.
Leave punctuation marks untouched.
:param text: an input string value.
:return: the first letter of each word to the end of it, then add "ay" to the end of the word.
"""
return " ".join(map(str, [x[1:] + x[0:1] + "ay" if x.isalpha() else x for x in text.split()]))
class TestPigIt(unittest.TestCase):
"""Class to test 'pig_it' function"""
def test_pig_it(self):
self.assertEqual(pig_it('Pig latin is cool'), 'igPay atinlay siay oolcay')
self.assertEqual(pig_it('This is my string'), 'hisTay siay ymay tringsay')
if __name__ == '__main__':
unittest.main()
| true |
5696eedb1fce1317b7e599a1a3d82c11ed318297 | Brokenshire/codewars-projects | /Python/eight_kyu/bool_to_word.py | 767 | 4.1875 | 4 | # Python solution for 'Convert boolean values to strings 'Yes' or 'No'.' codewars question.
# Level: 8 kyu
# Tags: FUNDAMENTALS, BOOLEAN, and SBEST PRACTICES.
# Author: Jack Brokenshire
# Date: 01/05/2020
import unittest
def bool_to_word(boolean):
"""
Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
:param boolean: boolean variable.
:return: Yes if true, otherwise, No.
"""
return "Yes" if boolean else "No"
class TestBoolToWord(unittest.TestCase):
"""Class to test 'bool_to_word' function"""
def test_bool_to_word(self):
self.assertEqual(bool_to_word(True), 'Yes')
self.assertEqual(bool_to_word(False), 'No')
if __name__ == '__main__':
unittest.main()
| true |
cfa7febef65c5683971080f1119d2734c91dc229 | thekuldeep07/SDE-SHEET | /majority element.py | 745 | 4.15625 | 4 | # Question :- find the majority element i.e which appear more than n//2 times
# method1:- using two nested loops
# o(n2)
# method2:- using hashmap
# O(n)
# mrthod 3 :- using moore voting algorithm
def findMajority(nums):
maj_index=0
count=0
for i in range(len(nums)):
if nums[i]== nums[maj_index]:
count+=1
else:
count-=1
if count==0:
count=1
maj_index=i
c=0
for i in range(len(nums)):
if nums[i]==nums[maj_index]:
c+=1
if c > len(nums)//2 :
print(nums[maj_index])
else:
print("no majority element")
arr=[7,7,5,7,5,1,7]
findMajority(arr) | true |
d85fc53158e06d73441712a6401b59bf3dd3ebf8 | VicSanNun/DeterminantePython | /main.py | 2,944 | 4.1875 | 4 | #@author: Victor Nunes
#Estudante de Fsica e Engenharia
#Calcular Determinante de Matrizes bsicas
#v.1.0 - 13/05/2018 00:20
#Definindo Funes para Calcular o Determinante
#Ordem 2
def ordem_2(a11, a12, a21, a22):
det = ((a11*a22)-(a21*a12))
return det
#Ordem 3
def ordem_3(a11, a12, a13, a21, a22, a23, a31, a32, a33):
det = (((a11*a22*a33)+(a12*a23*a31)+(a13*a21*a32))-((a31*a22*a13)+(a32*a23*a11)+(a33*a21*a12)))
return det
#Escolhendo a ordem da Matriz
ordem = int(input("Qual a ordem da Matriz ? 2 OU 3?"))
#Se ela for de Ordem 2
if (ordem == 2):
linha1 = input("Insira os termos da primeira linha: ")
#Conferindo a Quantidade de termos na linha
if (linha1.count(" ") != 1):
print("Dados Errados, Reinicie o Programa!");
elif(linha1.count(" ") == 1):
#Separando os Termos da Linha em Variveis
(a11, a12) = linha1.split(" ")
#Convertendo para numero
a11 = float(a11)
a12 = float(a12)
linha2 = input("Insira os termos da segunda linha: ")
#Conferindo a Quantidade de termos na linha
if(linha2.count(" ") != 1):
print("Dados Errados, Reinicie o Programa!")
elif(linha2.count(" ") == 1):
#Separando os Termos da Linha em Variveis
(a21, a22) = linha2.split(" ")
#Convertendo para numero
a21 = float(a21)
a22 = float(a22)
determinante = ordem_2(a11, a12, a21, a22)
print("\n","MATRIZ:")
print("\n","|",a11, a12,"|")
print("","|",a21, a22,"|")
print("\n","Determinante =", determinante)
elif (ordem == 3):
linha1 = input("Insira os termos da linha 1: ")
#Conferindo Quantidade de Termos na MATRIZ
if(linha1.count(" ") != 2):
print("Dados Errados, Reinicie o Programa!")
elif(linha1.count(" ") == 2):
#Separando os Termos da Linha em Variveis
(a11, a12, a13) = linha1.split(" ")
#Convertendo para numero
a11 = float(a11)
a12 = float(a12)
a13 = float(a13)
linha2 = input("Insira os termos da linha 2: ")
#Conferindo Quantidade de Termos na MATRIZ
if(linha2.count(" ") != 2):
print("Dados Errados, Reinicie o Programa!")
elif(linha2.count(" ") == 2):
#Separando os Termos da Linha em Variveis
(a21, a22, a23) = linha2.split(" ")
#Convertendo para numero
a21 = float(a21)
a22 = float(a22)
a23 = float(a23)
linha3 = input("Insira os termos da linha 3: ")
#Conferindo Quantidade de Termos na MATRIZ
if(linha3.count(" ") != 2):
print("Dados Errados, Reinicie o Programa!")
elif(linha3.count(" ") == 2):
#Separando os Termos da Linha em Variveis
(a31, a32, a33) = linha3.split(" ")
#Convertendo para numero
a31 = float(a31)
a32 = float(a32)
a33 = float(a33)
determinante = ordem_3(a11, a12, a13, a21, a22, a23, a31, a32, a33)
print("\n","MATRIZ:")
print("\n","|",a11, a12, a13,"|")
print("","|",a21, a22, a23,"|")
print("","|",a31, a32, a33,"|")
print("\n","Determinante =", determinante) | false |
b1d3f6edbe21e683f6e8596c56ad8a8b0a288ded | Zizo001/Random-Password-Generator | /RandomPasswordGenerator.py | 1,798 | 4.34375 | 4 | """
Author: Zeyad E
Description: random password generator that uses characters, numbers, and symbols
Last Modified: 6/9/2021
"""
import random
import string
import pyperclip #external library used to copy/paste to clipboard
def randomPassword(length):
characters = string.ascii_letters + string.digits + string.punctuation #characters will consist of letters,numbers, and symbols
return ''.join(random.choice(characters) for i in range(length)) #creates a string of characters that is as long as the chosen length by the user
print("""---------------------------------------------------------------
| Hi there, welcome to Z's random password generator! |
| How long would you like your password to be? |
| Please keep in mind that it must be at least 12 characters |
---------------------------------------------------------------\n""")
print('Password length: ', end='')
while True: #checks if length is long enough. If less than 12, ask the user again
passwordLength = int(input())
if passwordLength >= 12:
break
print("ERROR: password is too short. Please try again\n")
print('Password length: ', end='')
generatedPassword = randomPassword((passwordLength)) #generate the password and assign it to the variable
print("\nYour secure random password is:")
print(generatedPassword) #can be commented out for security concerns (i.e. password visible on screen)
pyperclip.copy(generatedPassword) #copies the password to clipboard
print("\nThe password has been copied to your clipboard. Enjoy")
#Todo
'''
Ensure length input is an integer, otherwise ask the user again
Ask the user if they would like the password to be copied to their clipboard
GUI
'''
| true |
54bab2af89fe1cb539ebafc3777a39971492d69b | stoltzmaniac/data_munger | /basics.py | 1,293 | 4.40625 | 4 | def mean(data: list) -> float:
"""
Calculates the arithmetic mean of a list of numeric values
:param data: list of numeric values
:return: float
"""
data_mean = sum(data) / len(data)
return data_mean
def variance(data: list) -> float:
"""
Calculates the variance of a list of numeric values
:param data: list of numeric values
:return: float
"""
data_mean = mean(data)
ss = sum((i - data_mean)**2 for i in data)
return ss
def std_dev(data: list, deg_of_freedom=1) -> float:
"""
Calculates the standard deviation allowing for degrees of freedom
:param data: list of numeric values
:param deg_of_freedom: Degrees of freedom, set as 0 to compute without sample
:return: float
"""
ss = variance(data)
pvar = ss / (len(data) - deg_of_freedom)
sd = pvar ** 0.5
return sd
def covariance(data_x: list, data_y: list) -> float:
"""
Calculates covariance between two data lists of numeric variables
:param data_x: list of numeric values
:param data_y: list of numeric values
:return: float
"""
covar = 0.0
x_mean = mean(data_x)
y_mean = mean(data_y)
for i in range(len(data_x)):
covar += (data_x[i] - x_mean) * (data_y[i] - y_mean)
return covar
| true |
47355faeb3b11b5eed30d09453b463dd564ce36c | carlocamurri/NeuralNetworksKarpathyTutorial | /neural_network_practice.py | 2,065 | 4.40625 | 4 | # Simplified version of multiplication gate to return the output or the gradient of the input variables
def multiply_gate(a, b, dx=1, backwards_pass=False):
if not backwards_pass:
return a * b
else:
da = b * dx
db = a * dx
return da, db
def add_gate(a, b, dx=1, backwards_pass=False):
if not backwards_pass:
return a + b
else:
da = 1 * dx
db = 1 * dx
return da, db
# We can combine different gates together
# For example, a + b + c
def add_gate_combined(a, b, c, dx=1, backwards_pass=False):
if not backwards_pass:
return a + b + c
else:
da = 1 * dx
db = 1 * dx
dc = 1 * dx
return da, db, dc
# Another example: combining addition and multiplication (a * b + c)
def add_multiplication_combined(a, b, c, dx=1, backwards_pass=False):
if not backwards_pass:
return a * b + c
else:
da = b * dx
db = a * dx
dc = 1 * dx
return da, db, dc
def sigmoid(x):
return 1 / (1 + (exp(-x)))
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
# An even more complex neuron (sigmoid(a*x + b*y + c))
def complex_neuron(a, b, c, x, y, df=1, backwards_pass=False):
if not backwards_pass:
q = a*x + b*y + c
f = sigmoid(q)
return f
else:
dq = sigmoid_derivative(f) * df
da = x * dq
dx = a * dq
dy = b * dq
db = y * dq
dc = 1 * dq
return da, db, dc, dx, dy
# What if both inputs of a multiplication are equal (a * a)?
def square_neuron(a, dx=1, backwards_pass=False):
if not backwards_pass:
return a * a
else:
# From power rule:
da = 2 * a * dx
# Short form for:
# da = a * dx
# da += a * dx
return da
# For a*a + b*b + c*c:
def sum_squares_neuron(a, b, c, dx=1, backwards_pass=False):
if not backwards_pass:
return a*a + b*b + c*c
else:
da = 2 * a * dx
db = 2 * b * dx
dc = 2 * c * dx | true |
0676e98b993097962e0014a31daabedc5c1939f5 | rsinger86/software-testing-udacity | /lessons/luhns_algorithm.py | 1,351 | 4.34375 | 4 |
# concise definition of the Luhn checksum:
#
# "For a card with an even number of digits, double every odd numbered
# digit and subtract 9 if the product is greater than 9. Add up all
# the even digits as well as the doubled-odd digits, and the result
# must be a multiple of 10 or it's not a valid card. If the card has
# an odd number of digits, perform the same addition doubling the even
# numbered digits instead."
#
# for more details see here:
# http://www.merriampark.com/anatomycc.htm
#
# also see the Wikipedia entry, but don't do that unless you really
# want the answer, since it contains working Python code!
#
# Implement the Luhn Checksum algorithm as described above.
# is_luhn_valid takes a credit card number as input and verifies
# whether it is valid or not. If it is valid, it returns True,
# otherwise it returns False.
def is_luhn_valid(n):
stringified = str(n)
do_calc_property = 'odd' if len(stringified) % 2 == 0 else 'even'
total = 0
cursor = 'odd'
for digit in stringified:
n = int(digit)
if cursor == do_calc_property:
n = 2 * n
if n > 9:
n = n - 9
total += n
if cursor == 'odd':
cursor = 'even'
elif cursor == 'even':
cursor = 'odd'
return total % 10 == 0
| true |
15054803c30ba692946895d90db8d16ac202c84b | Jefferson-Oliveira1/python | /03_ receber_dados_client.py | 1,143 | 4.34375 | 4 | """
Receber Dados Do Client
input() -> Todo Dado Recebido Via Input e do tipo String
Em Python Stinng e Tudo que Estiver entre:
- Aspas Simples
- Aspas Duplas:
- Aspas Simples Triplas:
- Aspas Duplas Triplas:
Exemplos:
- aspas Simples -> 'Anjolina Jolie'
- aspas duplas -> "Anjolina Jolie"
- aspas Simples tiplas -> '''Anjolina Jolie'''
"""
#- aspas duplas triplas -> """Anjolina Jolie"""
# entrada de dados
# print("Qual O Seu Nome? ")
# nome = input() # Input -> Entrada
nome = input("Qual O Seu Nome? ")
# Exempo de Print Antigo 2.x
# print("Seja Bem Vindo(a) %s" % nome)
# Exemplo De Printe Moderno 3.x
# print("Seja Bem-vindo(a) {0}" .format(nome))
# Exemplo De Print Atual3.7
print(f"Seja Bem Vindo(a) {nome}")
# print("Qual Sua Idade? ")
# idade = input()
idade = int(input("Quanos Anos vc tem? "))j
# Processamento
# saida de dados "antigo" 2.x
# print(" %s Tem %s Anos" % (nome, idade))
# Exmplo De Print Moderno 3.x
# print("A {0} Tem {1}" .format(nome, idade))
# Exemplo De Print Atual3.7
# print(f"A {nome} Tem {idade} anos")
"""
# int(idade) -> cast
cast e a "conversao"de um tipo de dado para outro
"""
print(f"{nome} Nasceu em {2020 - idade}") | false |
9d6e83cb10bca31436fd3a1dc0d7941b29a205eb | Saikat2019/Python3-oop | /5magic_dunder.py | 1,116 | 4.25 | 4 | #magic methods - emulate some built-in methods in python
#implement operator overloding
#dunder means double'_' -- __add__() it's a dunder method
#you can change some special methods , like for __add__
#we define add in our way ... in line 32
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, second,pay):
self.first = first
self.second = second
self.pay = pay
self.email = first + '.' + second + '@gmail.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first,self.second)
def applyRaise(self):
self.pay = int(self.pay * self.raise_amount)
def __repr__(self):
return "Employee('{}','{}','{}')".format(self.first,self.second,self.pay)
def __str__(self):
return "{}-{}".format(self.fullname(),self.email)
def __add__(self,other): #defining __add__() like this
return self.pay +other.pay
def __len__(self):
return len(self.fullname())
emp_1 = Employee('saikat','mondal',50000)
emp_2 = Employee('biju','mondal',20000)
#print(emp_1)
#print(emp_1.__repr__())
#print(emp_1.__str__())
print(emp_1+emp_2)
print(len(emp_1)) | false |
090d2c08fc310eec386602a8686fa8694265967e | alfredleo/ProjectEuler | /problem1.py | 2,667 | 4.5 | 4 | import unittest
from utils import performance
def multiplesof3and5(to):
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
https://projecteuler.net/problem=1
"""
sum = 0
for i in range(1, to):
if (i % 3 == 0) or (i % 5 == 0):
sum += i
return sum
def sum_of_divisible(n, div):
top = n / div
return (top + 1) * top / 2 * div
def multiplesof3and5optimized(to):
"""
Optimized solution to find multiples sum
:param to:
:return:
"""
return sum_of_divisible(to - 1, 5) - sum_of_divisible(to - 1, 15) + sum_of_divisible(to - 1, 3)
def make_test(num):
"""
:param num: is used to pass some variable and run tests accordingly
:return: TestClass for unittesting
"""
class TestClass(unittest.TestCase):
def test(self):
""" Unit test suite """
''' testing multiplesof3and5 '''
self.assertEqual(multiplesof3and5(3), 0)
self.assertEqual(multiplesof3and5(4), 3)
self.assertEqual(multiplesof3and5(10), 23)
self.assertEqual(multiplesof3and5(1000), 233168)
# self.assertEqual(multiplesof3and5(100000000), 2333333316666668) # Takes too much time
# self.assertEqual(multiplesof3and5(200000000L), 2333333316666668L) # error
''' testing multiplesof3and5optimized '''
self.assertEqual(multiplesof3and5optimized(3), 0)
self.assertEqual(multiplesof3and5optimized(4), 3)
self.assertEqual(multiplesof3and5optimized(10), 23)
self.assertEqual(multiplesof3and5optimized(1000), 233168)
self.assertEqual(multiplesof3and5optimized(100000000), 2333333316666668)
self.assertEqual(multiplesof3and5optimized(200000000), 9333333166666668)
self.assertEqual(multiplesof3and5optimized(1000000000), 233333333166666668)
''' testing sum_of_divisible '''
self.assertEqual(sum_of_divisible(4, 5), 0)
self.assertEqual(sum_of_divisible(10, 5), 15)
def test_performance(self):
# Performance test. Method 1. Convenient and nice
performance(True)
multiplesof3and5(30000000)
performance()
multiplesof3and5optimized(100000000)
performance()
test.__doc__ = 'Test on calculations <%d>' % num
return TestClass
Test1 = make_test(0)
# globals()['Test2'] = make_test(10)
if __name__ == '__main__':
unittest.main(verbosity=5) | true |
42997cc7da8ef79ab952c1594a30f878aa649ad0 | purusoth-lw/Python | /10.operator.py | 897 | 4.3125 | 4 | """
Operator:
=========
1.arithmatic Operator
2.Relational Operator
3.Logical Operator
4.Bitwise Operator
5.Assignent Operator
6.Special OPerator
1.arithmatic Operator:
=====================
(+) ----> Addition
(-) ----> Subtraction
(*) ----> Multiplication
(/) ----> Division
(//) ----> Floor Division
(%) ----> Modulus
(**) ----> Exponential
a=27
b=8
c=a+b
print("add : ",c)
c=a-b
print("sub : ",c)
c=a*b
print("mul : ",c)
c=a/b
print("div : ",c)
c=a//b
print("f.div : ",c)
c=a%b
print("mod : ",c)
c=a**b
print("exp : ",c)
"""
a=10
b=2
#expression
add=a+b #c=12
sub=a-b #c=8
mul=a*b #c=20
div1=a/b #c=5.0
div2=a//b #c=5
mod=a%b #c=0
exp=a**b #c=100
#result
print("add : ",add)
print("sub : ",sub)
print("mul : ",mul)
print("div : ",div1)
print("f.div : ",div2)
print("mod : ",mod)
print("exp : ",exp)
| false |
80b595700516c71fce8cb9a27d205d18e4a793d1 | Vanzcoder/HackerRankChallenges-Python- | /List_Comprehensions.py | 1,655 | 4.375 | 4 | """
Let's learn about list comprehensions!
You are given three integers X,Y and Z representing the dimensions of a cuboid along with an integer N.
You have to print a list of all possible coordinates given by (i,j,k) on a 3D grid
where the sum of i + j + k is not equal to N.
Here, 0 <= i <= X; 0 <= j <= Y, 0 <= k <= Z
Input Format:
Four integers X,Y,Z and N each on four separate lines, respectively.
Constraints:
Print the list in lexicographic increasing order.
Sample input:
1 (1 is max value, so 1st item will be 0 <= x <= 1 in every sublist)
2 (so 2nd item will be 0 <= y <= 2 in every sublist)
3 (so 3rd item will be 0 <= z <= 3 in every sublist)
4 (the total x + y + z != 4)
Sample output (this is an example but it is not in the correct order):
[([0,0,0], [0,0,1], [0,1,0], [1,0,0],) ([0,0,2], [0,1,1], [0,2,0], [1,0,1], [1,1,0],) [0,0,3],[0,1,2],
[0,2,1],[1,0,2], [1,1,1], [1,2,0], [0, 2, 3], [1,1,3],[1,2,2],[1,2,3]]
Concept
You have already used lists in previous hacks. List comprehensions are an elegant way to
build a list without having to use different for loops to append values one by one.
This example might help.
Example: You are given two integers x and y .
You need to find out the ordered pairs ( i , j ) , such that ( i + j ) is not equal to
n and print them in lexicographic order.( 0 <= i <= x ) and ( 0 <= j <= y) This is the
code if we dont use list comprehensions in Python.
Solution:
"""
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print([[ i, j, k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if k+j+i != n])
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.