blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d974cd6b8c7f5e8ea7672f0e935acac30dbd82a9 | mleue/project_euler | /problem_0052/python/e0052.py | 840 | 4.15625 | 4 | def get_digits_set(number):
"""get set of char digits of number"""
return set((d for d in str(number)))
def is_2x_to_6x_permutable(number):
"""check if all numbers 2x, 3x, 4x, 5x, 6x contain the same digits as number"""
digits_set = get_digits_set(number)
multipliers = (2, 3, 4, 5, 6)
for m in multipliers:
if not get_digits_set(m*number) == digits_set:
return False
return True
def find_smallest_2x_to_6x_permutable():
"""return the smallest integer whose 2x, 3x, 4x, 5x, and 6x all contain
the same digits as the number itself"""
lower_thresh, upper_thresh = 10, 17
while True:
for n in range(lower_thresh, upper_thresh):
if is_2x_to_6x_permutable(n):
return n
lower_thresh *= 10
upper_thresh *= 10
if __name__ == '__main__':
print(find_smallest_2x_to_6x_permutable())
| true |
4ff167bec52d0c1ab4196536b6ec81be4f3d13fe | gunit84/Code_Basics | /Code Basics Beginner/ex20_class_inheritance.py | 1,288 | 4.34375 | 4 | #!python3
"""Python Class Inheritance... """
__author__ = "Gavin Jones"
class Vehicle:
def general_usage(selfs):
print("General use: transportation")
class Car(Vehicle):
def __init__(self):
print("I'm Car ")
self.wheels = 4
self.has_roof = True
def specific_usage(self):
print("Specific Use: commute to work, vacation with family")
class Motorcycle(Vehicle):
def __init__(self):
print("I'm MotorCycle")
self.wheels = 2
self.has_roof = False
def specific_usage(selfs):
print("For Cruising and having fun!")
# Calls the Car Class
carInfo = Car()
# Inherits the general usage function from Vehicle Class
carInfo.general_usage()
# Uses it's own specific method
carInfo.specific_usage()
# Calls the Motorcycle Class
motorcycleInfo = Motorcycle()
# Inherits from Vehicle class
motorcycleInfo.general_usage()
# Uses it's own class method
motorcycleInfo.specific_usage()
# Check the Instance and Issubclass of the Objects
# This Checks the Object is an Instance of a Class or subclass
# Checks to see if carinfo is the Object/Instance of the Car Class
print(isinstance(carInfo, Car))
# Checks to see if Class Car is the subclass (inherits) from the Vehicle class
print(issubclass(Car, Vehicle))
| true |
d10ced02db8f0c93bd026b745cf916c1519fe4ef | gunit84/Code_Basics | /Code Basics Beginner/ex21_class_multiple_inheritance.py | 572 | 4.46875 | 4 | #!python3
"""Python Multiple Inheritance Example... """
__author__ = "Gavin Jones"
class Father():
def skills(self):
print('gardening, programming')
class Mother():
def skills(self):
print("cooking, art")
# Inherits from 2 SuperClasses above
class Child(Father, Mother):
def skills(self):
Father.skills(self)
Mother.skills(self)
print("I love sports")
# The child object is Created from the class Child which inherits the methods from the Parent Classes
child = Child()
# Inherited from Father Class
child.skills()
| true |
5b3ae06bb5ab6d7fbedf32e70113462324728453 | lilsweetcaligula/sandbox-online-judges | /leetcode/easy/number_of_segments_in_a_string/py/solution.py | 528 | 4.125 | 4 | #
# In order to count the number of segments in a string, defined as
# a contiguous sequence of non-space characters, we can use the
# str.split function:
# https://docs.python.org/3/library/stdtypes.html#str.split
#
# Given no parameters, the string is split on consecutive runs of
# whitespace and produce a list of segments. We simply return
# the length of the list.
#
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split())
| true |
80e5adbdcb0cf56f35ea9676103e5dad73771473 | lilsweetcaligula/sandbox-online-judges | /leetcode/easy/move_zeroes/py/solution.py | 1,633 | 4.125 | 4 | #
# We use a slow/fast pointer technique. The fast pointer (index) is running ahead,
# reporting whether the value it is pointing to is a zero value or not.
#
# If nums[fast] is not a zero value, we copy the value to nums[slow] and increment
# the slow pointer. This way, by the time the fast pointer reaches the end of the
# array we will have all non-zero values maintaining their initial order to the left
# of the slow pointer.
#
# At this point, some non-zero values to the right of the slow pointer that have
# been priorly copied, can linger. We must walk the slow pointer to the end of the
# array and overwrite all values with 0.
#
# The whole approach can be reminiscent of the Lomuto partitioning algorithm:
# https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
#
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
slow = 0
fast = 0
while fast < len(nums):
# If nums[fast] is not 0, copy the value to nums[slow]
# and move the fast index a step further.
if nums[fast] != 0:
nums[slow] = nums[fast]
slow += 1
fast += 1
# All non-zero values have been placed to the left of the slow
# index now at this point. Fill the remainder of the array with
# zeros to overwrite whatever values could linger.
while slow < len(nums):
nums[slow] = 0
slow += 1
| true |
f93a0e365415b56b37ddc49187da509706235061 | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Trees/Root_to_leaf_paths_binary_tree.py | 1,489 | 4.40625 | 4 | #1. Idea here is we want to return a list of strings which contains all of the root to leaf paths in the binary tree.
#2. So initialize a list (path_list) then we are going to make a recursive call function. In the function we will pass the root of the binary tree and a empty string which we will modify and add node values as we recurse.
#3. If the root is NOT none, we want to add that node value to our string, this will always begin from the ROOT of the binary tree. This will build our string of paths.
#4. Once we come accross a leaf our second condition will be met thus we know that if we hit a leaf we have reached the END of the path, so we have our root to leaf path, hence we should add that path to our path_list, not path_list will be global for inner function.
#5. Otherwise if we are not at a leaf, we still want to build our list and add the node value BUT we want to keep recursing down the tree until we hit the leaves, so we simply recurse left and right respectivley.
#6. Rememeber to pass the path + -> as this will build the string according to the desired output. Done!
def binaryTreePaths(self, root):
path_list = []
def recurse(root, path):
if root:
path += str(root.val)
if not root.left and not root.right:
path_list.append(path)
else:
recurse(root.left, path + "->")
recurse(root.right, path + "->")
recurse(root, "")
return path_list | true |
4c4b94ca6467f49e4d8309393d0b64723a85c59c | Tanmay-Thanvi/DSA-and-Leetcode-Walkthroughs | /Trees/Max_path_sum_in_binary_tree.py | 2,107 | 4.4375 | 4 | #1. Firstly, understand what the question wants. It wants the MAX PATH. Recall a path is a sequence or iteration of nodes in a binary tree where there are no cycles.
#2. Now, I want you to approach the recursion this way - "What work do I want to do at EACH node?" Well at each node we want to find the value of its left and right subtrees and take the MAX between those to subtrees as this SPECIFIC nodes path.
#3. No this is seen by our calls to left_subtree and right subtree, think of it as EACH node in the binary tree saying "hey I want the value of MY left subtree and MY right subtrees. If there negative, well I don't want em! Else I will gladly take em!".
#4. Then after we have found the MAX values of the node which we are currently looking at, imagine our node says this "OK, so this is MY value, and here is the value of my two children which may or may not be subtrees i don't really care, oh and they are not gonna be negative don't worry!"
#5. We then will record the max_path everytime! Think dp style.
#6. Finally we will return the current nodes MAX path! Now this is where you may mess up, Imagine this:
# 3
# \
# 5
# /
# 6
# / \
# 7 8
# * Now if your taking the max path of 5 well would you take the sum of BOTH 7 & 8 leaves? No because this is not a path! As to do so we would have a REPETITION! 6 would be repeated and we know that we cannot repeat any nodes in a path!
# * This is the reason WHY we have to take the maximum value between the left and right subtrees otherwise we get repetition and we DON'T have a valid path!
def maxPathSum(self, root: TreeNode) -> int:
max_path = root.val
def findMaxPath(root):
nonlocal max_path
if not root: return 0
left_subtree = max(findMaxPath(root.left), 0)
right_subtree = max(findMaxPath(root.right), 0)
max_path = max(max_path, root.val + left_subtree + right_subtree)
return root.val + max(left_subtree, right_subtree)
findMaxPath(root)
return max_path | true |
12cbb9b004d8360c72ca0e797b88094b86037cdb | ctec121-spring19/programming-assignment-2-beginnings-JLMarkus | /Prob-3/Prob-3.py | 1,055 | 4.5 | 4 | # Module 2
# Programming Assignment 2
# Prob-3.py
# Jason Markus
def example():
print("\nExample Output")
# print a blank line
print()
# create three variables and assign three values in a single statement
v1, v2, v3 = 21, 12.34, "hello"
# print the variables
print("v1:", v1)
print("v2:", v2)
print("v3:", v3)
def studentCode():
# replace <name> with your name
print("\nJason's Output")
# print a blank line
print()
# replicate the assignment statement above, but use your own variable
# names and values
x1, x2, x3 = 13, 12.34, "howdy"
# print the values of the 3 variables
print("x1:", x1)
print("x2:", x2)
print("x3:", x3)
# Get 3 values from the user and assign them to the variables defined
# above. See the page in Canvas on Simulataneous Assignment
# BONUS POINTS for using the split() method
x1, x2, x3 = input("Enter 3 values: ").split()
print()
print("x1:", x1)
print("x2:", x2)
print("x3:", x3)
example()
studentCode() | true |
db0479a9cb64020a74d3226af0b38ebbda140e66 | joyonto51/Programming_Practice | /Python/Old/Python Advance/Practise/Factorial_by_Recursion.py | 347 | 4.21875 | 4 | def factorial(number):
if number == 0:
return 1
else:
sum = number * factorial(number - 1)
return sum
number=int(input("please input your number:"))
'''
num=number-1
num1= number
for i in range(num,0,-1):
sum=num1*i
print(num1,"*",i,"=",sum)
num1=sum
'''
print(factorial(number))
| true |
90d6f45188cd37274453b2b944ad5432de3a60d5 | sunshine55/python-practice | /lab-01/solution_exercise1.py | 2,140 | 4.1875 | 4 | def quit():
print 'Thank you for choosing Python as your developing tool!'
exit()
def choose(choices=[]):
while True:
choice = raw_input('Please choose: ')
if len(choices)==0:
return choice
elif choice in choices:
return choice
else:
print 'You must choose from one of the following: ', sorted(choices)
def main():
choice = '0'
screen_data = screens[choice]
while True:
display_output = screen_data[0]
print display_output
print '========================'
choice = choose(screen_data[1].keys())
action = screen_data[1][choice]
if type(action) is str:
# action is a string (a key)
screen_data = screens[action]
else:
# Execute action
action()
# keyed by the selection path
screens = {
'0':('''
WELCOME TO SIMPLE PYTHON MANUAL 1.0
Please choose a category:
1. Data types and related operations
2. Statement and syntax
3. Modules
q: Exit
''',{ '1':'2-1',
'2':'2-2',
'3':'2-3',
'q':quit
}),
'2-1':('''
1. Data types and related operations:
Which data type would you like to know more about?
a.String b.Int c.Float d.Complex e.Bool
f.FronzenSet g.Tuple h.Bytes
i.Bytearray i.List j.Set k.Dict l.Object
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit,
'a':'2-1-a',
'b':'2-1-b'
}),
'2-2':('''
2. Statement and syntax
Which syntax would you like to know more about?
a.Assignment b.Conditional c.Loops
d.Function e.Class f.Method
g.Exception
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit,
'a':'2-1-a',
'b':'2-1-b'
}),
'2-3':('''
3. Modules
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
q: Exit
''',{ '1':'0',
'q':quit
}),
'2-1-a':('''
Data types and related operations:
String:
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
2:BACK TO "Data types and related operations"
q: Exit
''',{ '1':'0',
'2':'2-1',
'q':quit
}),
'2-1-b':('''
Data types and related operations:
Int:
// Content under development
// Please checkback later
1:BACK TO MAIN MENU
2:BACK TO "Data types and related operations"
q: Exit
''',{ '1':'0',
'2':'2-1',
'q':quit
})
}
if __name__ == '__main__':
main()
| true |
671443c555f412d1c03018de29760dbf5bb67f82 | nicap84/mini-games | /Guess the number/Guess the number.py | 2,218 | 4.125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#import simplegui
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# initialize global variables used in your code
num_range=100
aleatorio=0
inp_number=0
count=7
# helper function to start and restart the game
def new_game():
global aleatorio
aleatorio=random.randrange(0,num_range)
# define event handlers for control panel
def range100():
global num_range
num_range=100
global count
count=7
new_game()
print "New game. Range is from 0 to " +str (num_range)
print "Number if remaining guesses is " + str(count)
print ""
def range1000():
global num_range
num_range=1000
global count
count=10
new_game()
print "New game. Range is from 0 to 1000"
print "Number if remaining guesses is " + str(count)
print ""
def input_guess(guess):
global inp_number
inp_number=int(guess)
global count
count=count-1
print "Guess was " + str(inp_number)
print "Number of remaining guesses is " + str(count)
if count>0:
if inp_number < aleatorio:
print "Higher!"
print ""
elif inp_number >aleatorio:
print "Lower!"
print ""
elif inp_number == aleatorio:
print "Correct!"
print ""
if num_range==100:
range100()
else:
range1000()
elif count<=0:
print "You ran out of guesses. The number was " + str(aleatorio)
print ""
if num_range==100:
range100()
else:
range1000()
# create frame
frame=simplegui.create_frame ("Guess the number",200,200)
# register event handlers for control elements
frame.add_button ("Range is [0,100)", range100, 200)
frame.add_button ("Range is [0,1000)",range1000, 200)
frame.add_input ("Enter a guess", input_guess, 200)
range100()
frame.start()
# always remember to check your completed program against the grading rubric | true |
f99b9d736330ed66277e98311ccfb3a07b984f9e | Louis95/oop-in-python | /Exception/OnlyEven.py | 595 | 4.125 | 4 | '''
While this class is effective for demonstrating exceptions in action, it isn't very good at its job.
It is still possible to get other values into the list using index notation or slice notation.
This can all be avoided by overriding other appropriate methods, some of which are double-underscore methods.
'''
class OnlyEven(list):
def append(self, integer):
if not isinstance(integer, int):
raise TypeError("Only integers can be added")
if integer % 2:
raise ValueError("Only even even numbers can be added")
super().append(integer)
| true |
8a81a67dad68f690099e1e4f435c44a990b96ed4 | khadeejaB/Week10D2A2 | /questionfile.py | 749 | 4.3125 | 4 | #In this challenge, a farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three species:
chicken = 2
cow = 4
dog = 4
#The farmer has counted his animals and he gives you a subtotal for each species. You have to implement a script or function that returns the total number of legs of all the animals.
def animals(chicken_leg, cow_leg, dog_leg):
leg1 = chicken*chicken_leg
leg2 = cow * cow_leg
leg3 = dog * dog_leg
all_legs = leg1 + leg2 + leg3
return all_legs
#Example 1
print(animals(2, 3, 5))
#Example 2
#input(1, 2, 3) ➞ 22
#Example 3
#How many Chickens? 5
#How many Cows? 2
#How many Dogs? 8
#50 legs
#Create a python script to solve this problem.
| true |
359824127dd9b48c34a2df72f7f21fd85077d9ff | Armin-Tourajmehr/Learn-Python | /Number/Fibonacci_sequence.py | 950 | 4.28125 | 4 | # Enter a number and have the program generate
# The Fibonacci sequence number or the nth number
def Fibonacci_sequence(n):
'''
Return Fibonacci
:param n using for digit that user want to calculator Fibonacci:
:return sequence number as Fibonacci :
'''
# Initialization number
a = 1
b = 1
for i in range(n):
a, b = b, b + a
yield b
def ValidInput(n):
'''
Return True or False
:param n: Get number
:return: True if number will be correct or versa vise
'''
try:
number = int(n)
except ValueError:
print('Enter an integer')
else:
print('Wait.....')
return True
if __name__ == '__main__':
while True:
user = input('Please Enter a number: ')
if ValidInput(user):
n = int(user)
for i in Fibonacci_sequence(n):
print(i)
break
else:
continue
| true |
c64ac69d915f54109e959d046f6317348650a460 | evan-nowak/other | /generic/date_range.py | 2,881 | 4.53125 | 5 | #!/usr/bin/env python
"""
#########################
Date Range
#########################
:Description:
Generates a date range based on starting/ending dates and/or number of days
:Usage:
Called from other scripts
:Notes:
The function needs exactly two of the three arguments to work
When providing the start and end dates, both will be in the resulting list
"""
def date_range(start=None, end=None, day_count=None):
"""
:Description:
Generates a date range
Generates a date range using two of the following: starting date, ending date, day count
:Params:
start: The starting date
type: str
format: YYYY-MM-DD
default: None
end: The ending date
type: str
format: YYYY-MM-DD
default: None
day_count: The number of days in the range
type: int
default: None
returns: Range of dates in ascending order
type: list
:Dependencies:
Python3
:Notes:
The function needs exactly two of the arguments to work
:Example:
date_range(start='2018-01-01', end='2018-02-01')
"""
from datetime import datetime, timedelta
# If start is provided, validate format
if start is not None:
try:
start = datetime.strptime(start, '%Y-%m-%d')
except Exception:
raise Exception('Please provide dates in the following format: YYYY-MM-DD')
# If end is provided, validate format
if end is not None:
try:
end = datetime.strptime(end, '%Y-%m-%d')
except Exception:
raise Exception('Please provide dates in the following format: YYYY-MM-DD')
# If day_count is provided, validate format
if day_count is not None:
try:
day_count = int(day_count)
except Exception:
raise Exception('Day count must be a number')
# Create date range using start/end dates
if (start is not None) and (end is not None) and (day_count is None):
dates = [datetime.strftime(start + timedelta(days=n), '%Y-%m-%d') for n in range(int((end - start).days) + 1)]
# Create date range using start date and day count
elif (start is not None) and (day_count is not None) and (end is None):
dates = [datetime.strftime(start + timedelta(days=n), '%Y-%m-%d') for n in range(day_count)]
# Create date range using end date and day count
elif (end is not None) and (day_count is not None) and (start is None):
dates = [datetime.strftime(end - timedelta(days=n), '%Y-%m-%d') for n in range(day_count)][::-1]
else:
raise Exception('Please provide exactly 2 arguments')
print('{0} - {1}'.format(dates[0], dates[-1]))
return dates
if __name__ == '__main__':
print(__doc__)
| true |
0a5f2461b362405b244867ba8a8b44c21a363e51 | ferdiansahgg/Python-Exercise | /workingwithstring.py | 493 | 4.34375 | 4 | print("Ferdi\nMIlla")
print("Ferdi\"MIlla")
phrase = "Ferdiansah and MilleniaSaharani"
print(phrase.upper().isupper())#checking phrase is uppercase or not, by functioning first to upper and check by function isupper
print(len(phrase))#counting the word
print(phrase[0])#indexing the character
print(phrase.index("F"))#phasing the parameter
print(phrase.replace("Ferdiansah","FerdiGanteng"))#Replace the character, first that i wanna to replace by comma(,) and you put in that you wanna replace | true |
53255ace53f8e0265529c46a5bcacee089a7d404 | Patrick-Ali/PythonLearning | /Feet-Meters.py | 381 | 4.15625 | 4 | meterInches = 0.3/12
meterFoot = 0.3
footString = input("enter feet: ")
footInt = int(footString)
inchString = input("enter inches: ")
inchInt = int(inchString)
footHeightMeters = meterFoot*footInt
inchHeightMeters = meterInches*inchInt
heightMeters = round(footHeightMeters + inchHeightMeters, 2)
print("You are about: " + str(heightMeters) + " meters tall.")
| true |
a092e63cdfed3394aae4902d689b13140d1e42b9 | sarahsweeney5219/Python-Projects | /dateDetectionRegex.py | 1,663 | 4.75 | 5 | #date detection regex
#uses regular expression to detect dates in the DD/MM/YYYY format (numbers must be in min-max range)
#then tests to see if it is a valid date (based on number of days in each month)
import re, calendar
#creating the DD/MM/YYYY regex
dateRegex = re.compile('(3[01]|[12][0-9]|0?[1-9])\/(0?[1-9]|1[012])\/([12][0-9][0-9][0-9])')
#asking user to input text
print('Please enter either a single date, a series of dates, or a body of text with dates contained in it.')
text = input()
matches = []
for groups in dateRegex.findall(text):
date = '/'.join([groups[0], groups[1], groups[2]])
matches.append(date)
print(matches)
if len(matches) > 0:
print('These are the DD/MM/YYYY formatted dates in your input:')
for match in matches:
print(match)
print('We will now proceed to see if they are valid days (according to the number of days in a month')
validDates = []
for match in matches:
if match[3:5] in ['05', '06', '09', '11']:
if int(match[0:2]) <= 30:
validDates.append(match)
elif match[3:5] == '02':
#check to see if leap year
if calendar.isleap(int(match[6:10])) == True:
if int(match[0:2]) <= 29:
validDates.append(match)
else:
if int(match[0:2]) <= 28:
validDates.append(match)
else:
if int(match[0:2]) <= 31:
validDates.append(match)
print("Of your inputted dates, the following are valid:")
for validDate in validDates:
print(validDate)
else:
print('There were no dates in your input.')
| true |
76330f9dfd49d09599509e9909d2ef0715eeb9c3 | JeffreybVilla/100DaysOfPython | /Beginner Day 13 Debugging/debugged.py | 1,709 | 4.1875 | 4 | ############DEBUGGING#####################
# # Describe Problem
# def my_function():
# """
# Range function range(a, b) does not include b.
# 1. What is the for loop doing?
# The for loop is iterating over a range of numbers.
#
# 2. When is the function meant to print 'You got it'?
# If i is 20, then we print 'You got it'.
#
# 3 What are your assumptions about i?
# i is an arbitrary letter to keep track of iterations.
# i is initially = to 1, then 2, 3, etc.
# When i is 20. We print.
# """
# for i in range(1, 20 + 1):
# if i == 20:
# print("You got it")
# my_function()
# # Reproduce the Bug
# from random import randint
# dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
# dice_num = randint(0, 5)
# #The sixth number is causing the error.
# #Setting it to 6 will reproduce the error.
# #dice_num = 6
# print(dice_imgs[dice_num])
# # Play Computer
# year = int(input("What's your year of birth? "))
# if year > 1980 and year < 1994:
# print("\nYou are a millenial.")
# elif year >= 1994:
# print("\nYou are a Gen Z.")
# # Fix the Errors
# age = int(input("How old are you? "))
# if age > 18:
# print(f"You can drive at age {age}.")
# #Print is Your Friend
# pages = 0
# word_per_page = 0
# pages = int(input("Number of pages: "))
# #print(pages)
# word_per_page = int(input("Number of words per page: "))
# #print(word_per_page)
# total_words = pages * word_per_page
# print(total_words)
#Use a Debugger
#appending part wasnt in for loop
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item)
print(b_list)
mutate([1,2,3,5,8,13])
| true |
c0b096fa60b91b859fac13c0bf6a804116140dfc | hlainghpone2003/SFU-Python | /Sets.py | 2,214 | 4.15625 | 4 | #Sets
includes a data type for sets.
Curly braces or the set() fuction can be used to create sets.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) #show that duplicates have been removed
'orange' in basket # fast member testing
'crabgrass' in basket
Demonstrate set operation on unique letter form two words
a = set('abracadabra')
b = set('alacazam')
a #unique letter in a
a - b #letter in a but not in b
a | b #letter in a or b or both
a & b #letter in both a and b
a ^ b #letter in a or b but not both
>>> a - b
{'r', 'b', 'd'}
>>> a | b
{'l', 'd', 'm', 'a', 'c', 'r', 'b', 'z'}
>>> a & b
{'c', 'a'}
>>> a ^ b
{'l', 'd', 'm', 'b', 'r', 'z'}
x = set('23802348')
y = set('57839012')
>>> x - y
{'4'}
>>> y - x
{'5', '1', '7', '9'}
>>> x | y
{'1', '3', '9', '0', '8', '7', '4', '5', '2'}
>>> x & y
{'8', '2', '3', '0'}
>>> x ^ y
{'1', '9', '7', '4', '5'}
fruits = {"apple", "banana", "cherry", "orange", "kiwi", "lemon", "mango"}
print("cherry" in fruits)
a = {x for x in 'abracadabra' if x not in 'abc'}
a
---------
>>>Dictionaries
#Dictionaries
#Another useful data type built into Python is the dictionaries
tel = {'jack' : 4098, 'sape':4139}
tel['sape']
tel['guide'] = 4127
list(tel) #change
sorted(student) #Alphabet sorting
'MgOo' in student
'MaMa' not in student
dict([('sape', 4139), ('guide',4127), ('jack',4098)])
dict(sape=4139, guide= 4127, jack= 4098)
{x: x**2 for x in (2,4,6)}
{2: 4, 4: 16, 6: 36}
>>> for x in 2, 4, 6:
... print(x,x**2)
...
2 4
4 16
6 36
>>> for x in 2, 4, 6:
... print(x,':',x**2)
...
2 : 4
4 : 16
6 : 36
{x: x**3 for x in (10, 20, 30, 40, 50) }
{10: 1000, 20: 8000, 30: 27000, 40: 64000, 50: 125000}
-----------
When looping through dictionaries
>>> knights = {'gallahad': 'the pure', 'robin':'brave', 'sape': 4355}
>>> for k, v in knights.items():
... print(k,v)
...
gallahad the pure
robin brave
>>> for k, v in knights.items():
... print(k,v)
...
gallahad the pure
robin brave
sape 4355
>>> for x, y in enumerate(['tic','tac', 'toe']):
... print(x, y)
...
0 tic
1 tac
2 toe | true |
2be5ff41a0dd3029786f149dd7674ead6a9f07f1 | titojlmm/python3 | /Chapter2_Repetition/2_01_RockPaperScissors.py | 1,346 | 4.25 | 4 | import random
# This program plays the game known as Rock-Paper-Scissors.
# Programmed by J. Parker Jan-2017
print("Rock-Paper_Scissors is a simple guessing game.")
print("The computer will prompt you for your choice, ")
print("which must be one of 'rock', 'paper', or 'scissors'")
print("When you select a choice the computer will too (it ")
print("will not cheat) and the winner is selected by three ")
print("simple rules: rock beats scissors, paper beats ")
print("rock, and scissors beat paper. If a tie happens")
print("then you should play again.")
# Computer selection
i = random.randint(1, 3)
if i == 1:
choice = "rock"
elif i == 2:
choice = "paper"
else:
choice = "scissors"
print("Rock-paper-scissors: type in your choice: ")
player = input()
if player == choice:
print("Game is a tie. Please try again.")
else:
if player == "rock":
if choice == "scissors":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
elif player == "paper":
if choice == "rock":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
elif player == "scissors":
if choice == "paper":
print("Congratulations. You win.")
else:
print("Sorry. Computer wins")
else:
print("Option ", player, " is not valid. Please choose among rock, paper or scissors")
| true |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.