blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
dae86981446a3bc49c1a03d4d817cc13f1008cca | paulgrote/python-practice | /automate-boring-stuff/04/commaCode.py | 551 | 4.125 | 4 | # Comma Code
# Given a list, write a function that takes a list value as an argument
# and return a string with all the items separated by a comma and space,
# with and inserted before the last item.
my_list = ['Lagavulin',
'Bruichladdich',
'Dalwhinnie',
'Oban',
'Kilkerran',
'Ben Nevis',
'Deanston']
def theScotches(scotches):
new_list = [scotch + ', ' for scotch in scotches]
new_list[-1] = new_list[-1].rstrip(", ")
new_list[-1] = "and " + new_list[-1] + "."
new_string = "".join(new_list)
print(new_string)
theScotches(my_list)
| true |
4ac1e93c524a6327ee7e30319c407ce4550147e9 | HaYZEBurton/Summer2018_Python | /Day_1/Chap2Ex2.py | 1,024 | 4.25 | 4 | #Paul Burkholder
#08/28/2017
#Program Chapter2 Exercise2
#Pseudocode
"""Get input for total sales
calculate projected profit by multiplying total sales by 23% (.23)
display projected profit"""
#If total sales greater than 100,000 then Sales Percentage will be 25%
#Else sales perecentage is 23%
#Variable Declarations
TOTAL_SALES_PERCENTAGE_23_PERCENT = .23 # Represents 23% applied to total sales
TOTAL_SALES_PERCENTAGE_25_PERCENT = .25
#TOTAL_SALES_PERCENTAGE = 0.0
TOTAL_SALES = 0.0 # Represents total gross sales
TOTAL_PROFIT = 0.0 # Represent total profit (my take home)
#Prompting user for total sales
TOTAL_SALES = float(input("Enter projected sales: "))
#Making decision on total sales
if TOTAL_SALES > 100000:
TOTAL_PROFIT = TOTAL_SALES * TOTAL_SALES_PERCENTAGE_25_PERCENT
print("Total sales is greater than 100,000")
#Calculate total profit based on sales recorded
#TOTAL_PROFIT = TOTAL_SALES * TOTAL_SALES_PERCENTAGE
#Display total profit
print ("Your total profit is: $", format(TOTAL_PROFIT, ',.2f'))
| true |
bbee76d93ce05b041ce6e368cf8cca039272b5ab | CatherineLiyuankun/DataProcessingUsingPython | /src/week5/DogClass.py | 1,463 | 4.15625 | 4 | # -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name):
self.name = name
def getInfo(self):
print "This animal's name: %s" % self.name
def sound(self):
print "The sound of this animal goes?"
class Cat(Animal):
def sound(self):
print "The sound of cat goes meow ~"
class Dog(Animal):
"define Dog class"
counter = 0
def __init__(self, name, size):
self.name = name
self.__size = size
Dog.counter += 1
# print 'class' % self.name
def getInfo(self):
print "This dog's name: %s" % self.name
print "This dog’s size: %s" % self.__size
def greet(self):
print "Hi, I am %s, my number is %d, my size is %d" % (self.name, Dog.counter, self.__size)
class BarkingDog(Dog):
"define subclass BarkingDog"
def __init__(self, name, age):
self.name = name
self.age = age
Dog.counter += 1
# print 'subclass:%s' % self.age
def greet(self):
"initial subclass"
print "Woof! I am %s, my number is % d , my age is % d" % (self.name, Dog.counter, self.age)
if __name__ == '__main__':
# dog = BarkingDog("Zoe", 3)
# dog.greet()
dog = Dog('coco', 'small')
dog.sound()
cat = Cat('kawaii')
cat.getInfo()
cat.sound()
print isinstance(dog, Animal)
print isinstance(cat, Animal)
print isinstance(dog, Dog)
print isinstance(dog, Cat)
| true |
bee378171166f2308765d20457fdec36338ff57c | nbala02/Python-Functions | /descendingOrder.py | 1,004 | 4.59375 | 5 | # Python 3.8.0
# The following code takes non-negative integers and returns it in descending order
# Creating a function that reads non-negative integers and outputs it in descending order
def descendingOrder(userInput):
# Statement to make sure the input is a digit or a non-negative number
if userInput.isdigit():
# Add the input digits into a list
# Sort the list from smallest to largest digits
# Reverse the list to get the digits in descending order
input_list = list(userInput)
input_list.sort()
input_list.reverse()
# Join the digits together and print the list in descending order
print("Output the descending list of numbers: ")
print(''.join(input_list))
# Output Invalid if the input is a negative integer
else:
print("Invalid Integer Input")
# Enter the list of numbers
# Call the function descendingOrder
print("Input a list of numbers: ")
userInput = input()
descendingOrder(userInput)
| true |
e86d18420f5d55ccdbb83962acef8324cd7adb2b | mrasdfdela/springboard_18-02_python-data-structures | /13_capitalize/capitalize.py | 381 | 4.21875 | 4 | def capitalize(phrase):
"""Capitalize first letter of first word of phrase.
>>> capitalize('python')
'Python'
>>> capitalize('only first word')
'Only first word'
"""
lst = list(phrase)
lst[0] = lst[0].upper()
return "".join(lst)
print(capitalize('python')) # 'Python'
print(capitalize('only first word')) # 'Only first word'
| true |
a96ffc559c67fe098bf037818ad7f8640284c3f4 | tennessysherry/ds2 | /EveningClass/Lesson2a.py | 946 | 4.15625 | 4 | # functions and control statements
# A functions is a block of statements performing specific task
# Advantages: makes easy to understand and maintain, used OOP, improve code reuse.
def simple_interest():
principle = 7000
rate = 2.5
time = 24
answer = (principle * rate * time)/100
print('Your Simple interest is: ', answer)
simple_interest() # call/use
def body_mass_index():
weight = float(input('What is your Weight in Kgs'))
height = float(input('What is your Height in m'))
bmi = weight/(height*height)
print('Your Body Mass Index is ', bmi)
# Comparison operators: >, >=, <, <=, ==, !=(Not equal to)
# Logical operators: and, or, not
if bmi < 18.5:
print('Underweight')
elif bmi >= 18.5 and bmi <= 24.9:
print('Normal')
elif bmi > 24.9 and bmi <= 29.9:
print('Overweight')
else:
print('Very Overweight')
body_mass_index()
| true |
77482f802bdb17a554011dab782928571436097b | Hersonmei/ExerciciosPY | /Learn python with games/guess.py | 739 | 4.125 | 4 | import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1,20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
for guessesTaken in range(6):
print('Take a guess.')
guess = input()
guess = int(guess)
if guess < number:
print('Seu palpite é muito baixo')
if guess > number:
print('Seu palpite é muito alto')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! Você acertou meu número em ' + guessesTaken + ' palpites!')
if guess != number:
number = str(number)
print('Não. O número que eu estava pensando era ' + number + '.') | false |
acd37aa462918b2a0b9c2166db49ac03a0ad222f | lk-hang/leetcode | /solutions/1237-find-positive-integer-solution-for-a-given-equation.py | 1,554 | 4.125 | 4 | """
Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.
The function is constantly increasing, i.e.:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
interface CustomFunction {
public:
// Returns positive integer f(x, y) for any given positive integer x and y.
int f(int x, int y);
};
For custom testing purposes you're given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you'll know only two functions from the list.
You may return the solutions in any order.
"""
"""
This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
def f(self, x, y):
"""
class Solution:
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
sol = []
y_max = 1000
for x in range(1, 1001):
y = 1
while customfunction.f(x, y) <= z and y <= y_max:
if customfunction.f(x, y) == z:
sol.append([x, y])
y_max = min(y_max, y)
y += 1
y_max = min(y_max, y)
if customfunction.f(x, 1) >= z:
break
return sol
| true |
8b51f088642eaaf62f03579599e3c5b14613ccda | keachico/CS303E_and_CS313E | /CS 313E/Final Assignment Programs/Assignment 9/HashSolver.py | 2,076 | 4.15625 | 4 | # File: HashSolver.py
#
# Description: This program generates a list of words from a file,
# adds them to a hashed Wordlist, generates hash keys,
# searches corresponding buckets in the table, and gives the
# statistics of each search.
#
# Student's Name: Nadeem Abha, Kevin Achico
#
# Student's UT EID: na4333, ka6893
#
# Course Name: CS 313E
#
# Date Created: 11/25/12
#
# Date Last Modified: 11/28/12
import string
import time
from Wordlist import *
def main():
#create hashed wordlist ADT
word_lst = HashedWordlist()
print("Using hash table wordlist.")
print("Creating wordlist \n")
# start timer
start = time.time()
count = word_lst.addWordsFromFile("UnorderedWordlist.txt")
print
empty_buckets, avg = word_lst.loadFactor()
# stop timer
end = time.time()
print ("The Wordlist contains ",count," words.")
print ("There are %d empty buckets" % empty_buckets)
print ("Non-empty buckets have an average length of %3.11f" % avg)
print ("Building the Wordlist took %2.3f seconds. \n" % (end - start))
while True:
# Ask user to input a word
word = input("Enter a scrambled word (or EXIT): ")
word = word.lower()
# If the user types "exit", break the program
if word == "exit":
print ("Thanks for playing! Goodbye. \n")
break
# start the timer for word search.
start = time.time()
# Return a Tuple of the count and a permurtation
# if the users word is found within the data
foundWord, count = word_lst.findPerm(word)
if foundWord != False:
# start timer
end = time.time()
print("Found word:", foundWord)
print("Solving this jumble took %2.5f seconds" % (end - start))
print("Made %d comparisons \n" % count)
continue
# stop timer
end = time.time()
print("Word not found. Try again")
print("Search took %2.9f seconds. \n" % (end - start))
main()
| true |
35d4027e15449578ccfdd7bae16123b55a351c38 | keachico/CS303E_and_CS313E | /CS 313E/Practice Programs/Turtle Programs/turtle_donut.py | 459 | 4.15625 | 4 | def drawDonut(turtle, x, y):
"""Draw 36 circles in a donut shape. Each
circle has radius 45. Figure is centered
on (x, y)."""
turtle.up()
turtle.setheading(0)
direction = turtle.heading()
for i in range(36):
turtle.setheading(direction)
turtle.forward(55)
x1, y1 = turtle.position()
turtle.down()
drawCircle(turtle, x1, y1, 45)
turtle.up()
turtle.goto(x, y)
direction += 10
| true |
75daf79045bcd9dfe77befc62d876dc836ce4e2b | keachico/CS303E_and_CS313E | /CS 313E/Practice Programs/UnorderedList.py | 2,374 | 4.28125 | 4 | class UnorderedList:
"""A linked list in which the items are unordered."""
def __init__(self):
"""Create an empty list of no items and
length 0."""
self._head = None
self._length = 0
def isEmpty(self):
return not self._head
def __str__(self):
"""Adding all items to the printstring requires
traversing the list."""
output = "[ "
ptr = self._head
while ptr != None:
output += str(ptr.getData()) + " "
ptr = ptr.getNext()
return output + "]"
# Continues the UnorderedList class
def get(self, index):
"""Fetch the item at the indexed position."""
# Is the index within bounds?
if index < 0 or index >= self._length:
print ("Index out of range.")
return None
# Count down the list until you reach the
# right node.
cursor = self._head
for i in range(index):
cursor = cursor.getNext()
return cursor.getData()
def add(self, item):
# Add an item to the front of the list.
temp = Node(item)
temp.setNext( self._head )
self._head = temp
self._length += 1
def remove(self, item):
"""Remove first occurrence of item, if any."""
current = self._head
previous = None
found = False
while not found and current != None:
if current.getData() == item:
self._length -= 1
found = True
else:
previous = current
current = current.getNext()
if current == None:
# item is not in the list
return
elif previous == None:
# item is at head of the list
self._head = current.getNext()
else:
previous.setNext(current.getNext())
def search(self, item):
"""Return a boolean indicating whether
item is in the list."""
current = self._head
# Search to find item or fall off the end.
while current != None:
if current.getData() == item:
return True
else:
current = current.getNext()
# If you reach the end of the list.
return False
| true |
9894ab3006ab894ac04cee30661af1b841806ec9 | ism-hub/cryptopals-crypto-challenges | /s2_9.py | 1,218 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Implement PKCS#7 padding
A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of plaintext into ciphertext. But we almost never want to transform a single block; we encrypt irregularly-sized messages.
One way we account for irregularly-sized messages is by padding, creating a plaintext that is an even multiple of the blocksize. The most popular padding scheme is called PKCS#7.
So: pad any block to a specific block length, by appending the number of bytes of padding to the end of the block. For instance,
"YELLOW SUBMARINE"
... padded to 20 bytes would be:
"YELLOW SUBMARINE\x04\x04\x04\x04"
"""
""" psck#7 style
examples -
Input: block="YELLOW SUBMARINE", wantedSize=20
Output: "YELLOW SUBMARINE\x04\x04\x04\x04"
Input: block="YELLOW SUBMARIN", wantedSize=20
Output: "YELLOW SUBMARIN\x05\x05\x05\x05\x05"
Throws: exception if len(block) > wantedSize
"""
def padToLen(block, wantedSize):
if(len(block) > wantedSize):
raise ValueError('block size is too big for padding to the wanted block size')
sizeToPad = wantedSize - len(block)
res = bytearray(block)
res.extend([sizeToPad]*sizeToPad)
return res
| true |
a2ce349216e92bb556a72c4cb3187269707a3ee6 | henrychen222/Leetcode | /python DS/Sets.py | 978 | 4.375 | 4 | # https://www.tutorialspoint.com/python/python_sets.htm
# 12.21
"""Create a set """
Days = set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"])
print(Days)
Month = {"Jan", "Feb", "Mar"}
Dates = {21, 22, 17}
print(Month)
print(Dates)
# set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
# set(['Jan', 'Mar', 'Feb'])
# set([17, 21, 22])
""" Accessing Values in a Set """
for day in Days:
print(day)
"""Adding Items to a Set"""
Days.add("Sun")
print(Days)
"""Removing Item from a Set"""
Days.discard("Sun")
print(Days)
print("\n")
"""Union of Sets"""
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
union_days = DaysA | DaysB
print(union_days)
"""Intersection of Sets"""
intersection_days = DaysA & DaysB
print(intersection_days)
"""Difference of Sets"""
difference_days = DaysA - DaysB
print(difference_days)
"""Compare Sets"""
compare_result = DaysA <= DaysB
compare_result2 = DaysB >= DaysA
print(compare_result)
print(compare_result2)
| false |
d1d0b50af7facf9475be7055f4121dbb0b81c3af | sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions | /Dynamic Programming/numberOfWaysToMakeChange.py | 744 | 4.1875 | 4 | """
Number Of Ways To Make Change
Given an array of positive integers representing coin denominations and
a single non-negative integer representing a target amount of money,
implement a function that returns the number of ways to make change for
that target amount using the given coin denominations.
Note that an unlimited amount of coins is at your disposal.
Sample input: 6, [1, 5]
Sample output: 2 (1x1 + 1x5 and 6x1)
"""
# O(n*denoms) time | O(n) space
def numberOfWaysToMakeChange(n, denoms):
ways = [0 for _ in range(n+1)]
ways[0] = 1
for denom in denoms:
for amount in range(1, n+1):
if denom <= amount:
ways[amount] += ways[amount-denom]
return ways[n]
| true |
0029832b355b2bcdd895900712ff668fd5978cc5 | sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions | /Searching/searchInSortedMatrix.py | 961 | 4.15625 | 4 | """
Search In Sorted Matrix
You're given a two-dimensional array (a matrix) of distinct integers and a target integer.
Each row in the matrix is sorted, and each column is also sorted; the matrix doesn't necessarily have
the same height and width.
Write a function that returns an array of the row and column indices of the target integer if it's
contained in the matrix, otherwise [-1, -1].
Sample input:
[ [1, 4, 7, 12, 15, 1000],
[2, 5, 19, 31, 32, 1001],
[3, 8, 24, 33, 35, 1002],
[40, 41, 42, 44, 45, 1003],
[99, 100, 103, 106, 128, 1004] ], 44
Sample output: [3, 3]
"""
# O(n + m) time | O(1) space
def searchInSortedMatrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < target:
row += 1
else:
return [row, col]
return [-1, -1]
| true |
8cabfb501e8ff199906928884b49fc9ee126332b | sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions | /Strings/groupAnagrams.py | 1,799 | 4.21875 | 4 | """
Group Anagrams
Write a function that takes in an array of strings and groups anagrams together.
Anagrams are strings made up of exactly the same letters, where order doesn't matter.
For example, "cinema" and "iceman" are anagrams; similarly, "foo" and "ofo" are anagrams.
Your function should return a list of anagram groups in no particular order.
Sample Input: ["yo", "act", "flop", "tac", "cat", "oy", "olfp"]
Sample Output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"]]
"""
# SOLUTION 1
# O(w * n * log(n) + n * w * log(w)) time | O(wn) space - where w is the number of words and
# n is the length of the longest word
def groupAnagrams1(words):
if len(words) == 0:
return []
sortedWords = ["".join(sorted(w)) for w in words]
indices = [i for i in range(len(words))]
indices.sort(key=lambda x: sortedWords[x])
result = []
currentAnagramGroup = []
currentAnagram = sortedWords[indices[0]]
for index in indices:
word = words[index]
sortedWord = sortedWords[index]
if sortedWord == currentAnagram:
currentAnagramGroup.append(word)
continue
result.append(currentAnagramGroup)
currentAnagramGroup = [word]
currentAnagram = sortedWord
result.append(currentAnagramGroup)
return result
# SOLUTION 2
# O(w * n * log(n)) time | O(wn) space - where w is the number of words and
# n is the length of the longest word
def groupAnagrams2(words):
anagrams = {}
for word in words:
sortedWord = "".join(sorted(word))
if sortedWord in anagrams:
anagrams[sortedWord].append(word)
else:
anagrams[sortedWord] = [word]
return list(anagrams.values())
| true |
89e84b4fff5ce69008c8ef55ab49b5f5c6bdeec9 | sagnikghoshcr7/DSA-AlgoExpert-Practice_Solutions | /Recursion/NthFib.py | 1,467 | 4.3125 | 4 | """
Nth Fibonacci
The Fibonacci sequence is defined as follows:
the first number of the sequence is 0,
the second number is 1,
and the nth number is the sum of the (n - 1)th and (n - 2)th numbers.
Write a function that takes in an integer n and returns the nth Fibonacci number.
Important note: the Fibonacci sequence is often defined with its first 2 numbers as F0 = 0 and F1 = 1.
For the purpose of this question, the first Fibonacci number is F0;
therefore, getNthFib(1) is equal to F0, getNthFib(2) is equal to F1, etc..
Sample input #1: 2
Sample output #1: 1 (0, 1)
Sample input #2: 6
Sample output #2: 5 (0, 1, 1, 2, 3, 5)
"""
# SOLUTION 1
# O(2^n) time | O(n) space
def getNthFib1(n):
if n == 2:
return 1
elif n == 1:
return 0
else:
return getNthFib1(n - 1) + getNthFib1(n - 2)
# SOLUTION 2
# O(n) time | O(n) space
def getNthFib2(n, memoize=None):
if memoize is None:
memoize = {1: 0, 2: 1}
if n in memoize:
return memoize[n]
else:
memoize[n] = getNthFib2(n - 1, memoize) + getNthFib2(n - 2, memoize)
return memoize[n]
# SOLUTION 3
# O(n) time | O(1) space
def getNthFib3(n):
lastTwo = [0, 1]
counter = 3
while counter <= n:
nextFib = lastTwo[0] + lastTwo[1]
lastTwo[0] = lastTwo[1]
lastTwo[1] = nextFib
counter += 1
return lastTwo[1] if n > 1 else lastTwo[0]
| true |
a062b7b9b83e22ff258c5d9ef514648ab75ecbda | ozcankursun/Precourse-Front-end-Development-Introduction-to-Programming-with-Python | /02_python_strings.py | 978 | 4.46875 | 4 | # Set a different value for 'str' to get the right answer.
str = 'The lenght should be'
# 1. Length
# The length should be 20
print("Length of str = ", len(str))
# 2. Positions
# This will display the second letter:
print(str[1])
# Now, show the third letter
print(str[2])
# 3. Index
# Display the position of the first match with the letter a
# It should print 1
str = 'car'
print("First position of the letter a = ", str.index("a"))
# 4. Count
# Count at least 5 letters a
s = 'I am thinking of the main idea of topic but i cannot remember that'
print("It has ", s.count("a"))
# 5. Print in rows
# Print every letter of the string
str = 'banana'
for x in str:
print(x)
# 6. For the next exercise, leave the value of `str` as it is
# and use methods to change the given string to lower case,
# print it, then change it to upper case and print it
str = "HeLLo, hOW aRe YoU?"
print(str.lower())
print(str.upper())
# Tip: search for the different Python String Methods | true |
112b049e6fe6d99dc7c69afc9816e7e5be2e598a | AmpersandTalks/CIS106-Cesar-Perez | /Assignment 11/Defined Activity 2.py | 944 | 4.21875 | 4 | # This activity Finds the day of the birthday the person inputs.
# Refrences: https://en.wikipedia.org/wiki/Zeller%27s_congruence
# https://www.geeksforgeeks.org/zellers-congruence-find-day-date/
def getValue(name):
print(" Enter " + name + " value: ")
value = int(input())
return value
def calculateDayOfWeek(year, month, day):
if month < 3:
month += 12
year -= 1
j = round(year / 100)
k = year % 100
m = month
q = day
h = q + 13 * (m + 1) // 5 + k + k // 4 + j // 4 + 5 * j
h = h % 7
return h
def displayResults(dayofweek):
days = [
"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"
]
print("That day is a " + days[dayofweek])
def main():
year = getValue("year")
month = getValue("month")
day = getValue("day")
dayofweek = calculateDayOfWeek(year, month, day)
displayResults(dayofweek)
main()
| true |
eb3fad770864c2818897d142fadffd7be91af5f7 | AmpersandTalks/CIS106-Cesar-Perez | /Assignment 13/Activity 2.py | 644 | 4.3125 | 4 | # This program will print out a sentence in reverse and
# will also delete leading, trailing, and duplicate spaces.
def get_sentence():
print("Enter Sentence to reverse it")
name = str(input())
name = name.strip()
return name
def get_list(name):
name_list = name.split()
return name_list
def string_reverse(name):
print(name[::-1])
def display_output(name_list):
name_string = " ".join(name_list)
print(" In reverse you string will look something like.....")
string_reverse(name_string)
def main():
name = get_sentence()
name_list = get_list(name)
display_output(name_list)
main()
| true |
63bc4e3b64deea928b2e0b65cba0442d94bc50b7 | sewald00/Strong-Password-Generator-Python | /password_generator_ver2.py | 1,835 | 4.125 | 4 | # Random password Generator
# Seth Ewald
# March 6th 2018
import tkinter as tk
from tkinter import ttk
from random import randint
# Define the main program function to run
def main():
# Define function to change label text on button click
def onClick():
password = ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvqxyz1234567890!@#$%&*?')
# Assign the first letter to the PW to make sure it is a letter
randomPW = []
x = randint(0, 51)
randomPW.append(password[x])
#If/else statement to determine state of allow special characters checkbox
if checkVar1.get()==1:
# assign specified number
for i in range(19):
x = randint(0, 69)
randomPW.append(password[x])
finalPW = (''.join(randomPW))
e.delete(0, 20)
e.insert(0, finalPW)
else:
for i in range(19):
x = randint(0, 61)
randomPW.append(password[x])
finalPW = (''.join(randomPW))
e.delete(0, 20)
e.insert(0, finalPW)
# Create app window
root = tk.Tk()
root.minsize(width=300, height=75)
root.maxsize(width=300, height=75)
root.title("Password Generator")
# Create button to generate a random password
button = tk.Button(root, text='Generate Password',
width=25, command=onClick)
button.pack()
# Create a label to display the random password
e = tk.Entry(root, width=30)
e.pack()
#create check button
checkVar1=tk.IntVar()
C1 = tk.Checkbutton(root, text="Allow Special Characters", variable=checkVar1,
onvalue=1, offvalue=0, height=5,width=20,command=print(checkVar1.get()))
C1.pack()
root.mainloop()
main()
| false |
f190cccefdb04d6612be104be0f896de0a813f66 | devparkk01/Tkinter | /Frame/ttk/1ttkFirst.py | 1,285 | 4.4375 | 4 | import tkinter as tk
from tkinter import ttk
# creating a window
win = tk.Tk()
# default size , width * height
win.geometry("300x500")
# to prevent gui from being resizable , i.e , We can't change the size of
# gui . We need to use resizable() method
win.resizable( 0 , 0 )
win.title("Python Gui")
# ttk stands for themed tkinter . It's like a sub module inside tkinter
# We can create nice widgets with the help of ttk
# Some of the most common widgets include Label ,Frame , Button , Entry , Combobox, Notebook ,
# Radiobutton , CheckButton , MenuButton
# Creating a label
labelOne = ttk.Label(win , text = "Label One" , foreground = "red" , background = "grey", width = 10 )
# above code is only going to create a label , if we run the code now , we won't see it in the gui
# This is because we haven't packed it , in other words we haven't yet placed it in our gui .
# In order to place it , we can use two methods , pack() and grid() .
labelOne.grid(row = 0 , column = 0 , sticky = tk.W)
# Now since we've placed it , we can see the label now .
# creating another label
labelTwo = ttk.Label(win , text = "Label Two" , foreground = "#76ad98", background = "grey" ,width = 10)
# Now place the label
labelTwo.grid(row = 1 , column = 0 ,sticky = tk.W)
win.mainloop()
| true |
91eeb5f7b0b3ca294b915b02d8491cce928bf8f6 | wuhao0015/matplot | /show_day.py | 430 | 4.125 | 4 | months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
endings = ['st', 'nd', 'rd']+17*['th']\
+ ['st', 'nd', 'rd']+7*['th']\
+ ['st']
year = input('Year: ')
month = input('Month(1-12): ')
day = input('Day (1-31):')
month_number = int(month)
day_number = int(day)
month_name = months[month_number-1]
ordinal = day+endings[day_number-1]
print(month_name + ' ' + ordinal + ',' + year)
| false |
d3162b9b8fde74f1819b551970a7028c0b62e166 | msembinelli/pypractice | /exercises/reversestring/reversestring.py | 491 | 4.34375 | 4 | def reverse(s):
"""
Given a string, return a new string with the reversed order of characters.
reverse('apple') == 'elppa'
reverse('hello') == 'olleh'
reverse('Greetings!') == '!sgniteerG'
"""
return s[::-1]
def reverse_join(s):
return ''.join(reversed(s))
def reverse_manual(s):
tmp = ""
for c in reversed(s):
tmp += c
return tmp
def reverse_array(s):
tmp = []
for c in list(s):
tmp.insert(0, c)
return ''.join(tmp) | true |
0185ee7d69916c69d18fe524fe771677c05750cb | msembinelli/pypractice | /exercises/capitalize/capitalize.py | 939 | 4.25 | 4 | def capitalize_string(s):
"""
Write a function that accepts a string. The function should
capitalize the first letter of each word in the string then
return the capitalized string.
self.assertEqual(func('a short sentence'), 'A Short Sentence'))
self.assertEqual(func('a lazy fox'), 'A Lazy Fox'))
self.assertEqual(func('look, it is working!'), 'Look, It Is Working!'))
"""
word_list = []
for word in s.split(' '):
cap_word = word
if word[0].isalnum():
cap_word = word[0].upper() + word[1:]
word_list.append(cap_word)
new_s = ' '.join(word_list)
return new_s
def capitalize_string_char(s):
char_list = []
last_c = ' '
for c in s:
new_c = c
if last_c == ' ' and c.isalnum():
new_c = c.upper()
char_list.append(new_c)
last_c = new_c
new_s = ''.join(char_list)
return new_s
| true |
a192ecf3978deda3425cb416db7cf95c74f93069 | vincent-frimpong/AdventOfCode | /src/day_1_report_repair/main.py | 1,756 | 4.375 | 4 | # The Advent of code 😊
# DAY 1
def report_repair(data: list) -> int:
"""
find two numbers (say a, b) from the data provided that sum up to 2020
and return their product( i.e a*b)
:param data: list of numbers
:return: product of two terms (i.e a*b) or 0 if we can't find any (a,b: a+b=2020)
"""
try:
for i in range(len(data)):
for j in range(i+1, len(data)):
if data[i] + data[j] == 2020:
return data[i] * data[j]
except TypeError:
print("Error: expected data to be of type list[int]")
return 0
# Part Two
def report_repair_three_numbers(data):
"""
find three numbers (say a, b, c) from the data provided that sum up to 2020
and return their product( i.e a*b*c)
:param data: list of numbers
:return: product of three terms (i.e a*b*c) or 0 if we can't find any (a,b,c: a+b+c=2020)
:raises: TypeError: when data is not of type list[int]
"""
try:
for i in range(len(data)):
for j in range(i + 1, len(data)):
for k in range(j + 1, len(data)):
if data[i] + data[j] + data[k] == 2020:
return data[i] * data[j] * data[k]
except TypeError as e:
raise TypeError("expected input param - data: list[int]") from e
return 0
if __name__ == '__main__':
with open("../../resources/day1_input_data") as f:
# read data and cast to integers
testData = list(map(int, f.readlines()))
print("report_repair(testData) ->",report_repair(testData))
print("report_repair_three_numbers(testData) ->", report_repair_three_numbers(testData))
| true |
6dce966a034573a082b2074683dbc0121255fc73 | aitiwa/pythonTraining | /m3_1_ifElifElseMultiTest_001_06.py | 2,332 | 4.1875 | 4 | print("caseStudy: 학점 계산 - 중첩 조건문 6단계 - print를 grade변수화")
print('m3_1_ifelifelsemultiTest_001_06\n')
print("1. grade, score 변수 선언과 초기화: ")
print(' grade = "" ')
print(' score=int(input(" 점수를 입력하세요 : "))')
grade = ""
score=int(input(" 점수를 입력하세요 : "))
print()
print("2. 여러 단계 조건을 실행하는 중첩 조건문 ")
print(' if score == 100 : ')
print(' grade=" A+" ')
print(' elif score >= 90: ')
print(' result = score % 10 ')
print(' if result < 5 : ')
print(' grade=" A0" ')
print(' else : ')
print(' grade=" A+" ')
print(' elif score >= 80: ')
print(' result = score % 10 ')
print(' if result < 5 : ')
print(' grade=" B0" ')
print(' else : ')
print(' grade=" B+" ')
print(' elif score >= 70: ')
print(' result = score % 10 ')
print(' if result < 5 : ')
print(' grade=" C0" ')
print(' else : ')
print(' grade=" C+" ')
print(' elif score >= 60: ')
print(' result = score % 10 ')
print(' if result < 5 : ')
print(' grade=" D0" ')
print(' else : ')
print(' grade=" D+" ')
print(' else : ')
print(' grade=" F" ')
print(' ')
print(' print("{}학점 입니다.".format(grade)) ')
print(' print() ')
print()
print("3. 결과값->")
if score == 100 :
grade=" A+"
elif score >= 90:
result = score % 10
if result < 5 :
grade=" A0"
else :
grade=" A+"
elif score >= 80:
result = score % 10
if result < 5 :
grade=" B0"
else :
grade=" B+"
elif score >= 70:
result = score % 10
if result < 5 :
grade=" C0"
else :
grade=" C+"
elif score >= 60:
result = score % 10
if result < 5 :
grade=" D0"
else :
grade=" D+"
else :
grade=" F"
print("{}학점 입니다.".format(grade))
print()
print('4. 프로그램 종료')
print(' print("Program End")')
print(" Program End") | false |
31977151e388b673ba613dbe365b9bcdc4dcadce | oinume/alpy | /linked_list.py | 1,413 | 4.1875 | 4 | class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def InsertNth(head, data, position):
current = 0
prev = None
node = head
if head is None:
node = Node(data)
return node
while node is not None:
if position == current:
n = Node(data, node)
if prev is not None:
prev.next = n
else:
return n
#node.next = n
#return head
prev = node
node = node.next
current += 1
return head
# 0: a, next=b
# 1: b, next=c
# 2: c, next=None
# 0: a, next=x # next=xにする
# 1: x, next=b # next=bにする
# 2: b, next=c
# 3: c, next=None
# head.data=2, data=3, position=0
# head.data=2, data=5, position=1
# head.data=2, data=4, position=2
# head.data=2, data=2, position=3
# head.data=2, data=10, position=1
# head.data=2, data=3, position=0
# 2
# head.data=2, data=5, position=1
# 2
# head.data=2, data=4, position=2
# 2
# head.data=2, data=2, position=3
# 2
# head.data=2, data=10, position=1
# 2
def print_node(head):
n = head
while n is not None:
print(n.data)
n = n.next
if __name__ == '__main__':
c = Node('c', None)
b = Node('b', c)
a = Node('a', b)
print_node(a)
print("---")
head = InsertNth(a, 'x', 0)
print_node(head)
| true |
74babef255cd29d89be0185a57da45f48130868e | taruchit/Python | /StringOperations.py | 658 | 4.1875 | 4 | #Taking user input
a=input()
#Displaying character at 3rd position
print("Character at 3rd position",a[2])
#Displaying character at 4th position
print("Character at 4th position",a[3])
#Displaying characters at 3rd and 4th position together
print(a[2:4])
print("6th position onwards along with next two characters",a[5:8])
#Displaying length of the string
print(len(a))
#Removing extra spaces on left side of the string
a=a.lstrip()
#Removing extra spaces on right side of the string
a=a.rstrip()
print(a)
#Replacing character at 5th position of the string
a=a[:4]+'p'+a[5:]
print(a)
#Converting the string to all lower case
a=a.lower()
print(a) | true |
6f7fe5e143f74962dc16b7b7ad67a1dcdeb5c8bc | Jenoe-Balote/ICS3U-Unit3-08-Python | /leapyear.py | 758 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by Jenoe Balote
# Created on May 2021
# This program runs the leap year program
import string
def main():
# this function runs the leap year program
# input
print("Welcome!")
num_year = str(input("Please enter the year: "))
# process and output
try:
num_year = int(num_year)
if num_year % 4 == 0:
if num_year % 100 == 0:
if num_year % 400 == 0:
print("{} is a leap year!".format(num_year))
else:
print("{} is not a leap year!".format(num_year))
except Exception:
print("{} is invalid data.".format(num_year))
finally:
print("Thanks for participating!")
if __name__ == "__main__":
main()
| true |
f28b47aa1bc11c8c46935c7cb5e69dbcbc54493f | Tobi-mmt/nltk-book | /chapter_5/exercise_13.py | 607 | 4.53125 | 5 | # -*- coding: utf-8 -*-
# 11, 13, 15, 17, 27, 34, 36, 39, 40, 43
##################
# 13 - We can use a dictionary to specify the values to be substituted into a formatting string.
# Read Python's library documentation for formatting strings http://docs.python.org/lib/typesseq-strings.html
# and use this method to display today's date in two different formats.
##################
from datetime import date
today = {
'day': date.today().day,
'month': date.today().month,
'year': date.today().year
}
print('{day}.{month}.{year}'.format(**today))
print('{year}-{month}-{day}'.format(**today))
| true |
63cea74780ecf2145edca527dbd0e9205c66ddea | CodingLordSS/BMI-Calculator-Developer-CodeLordSS | /BMI.py | 683 | 4.375 | 4 | // Developer CodeLordSS
// Programmning language: Python
Height=float(input("Enter your height in centimeters: "))
Weight=float(input("Enter your Weight in Kg: "))
Height = Height/100
BMI=Weight/(Height*Height)
print("your Body Mass Index is: ",BMI)
if(BMI>0):
if(BMI<=16):
print("you are severely underweight")
elif(BMI<=18.5):
print("you are underweight")
elif(BMI<=25):
print("you are Healthy")
elif(BMI<=30):
print("you are overweight")
else: print("you are severely overweight")
else:("enter valid details")
// The result will be: =>
// Enter your height in centimeters: 170
Enter your Weight in Kg: 67
your Body Mass Index is: 23.18339100346021
you are Healthy
| true |
a76060ece17749ef1ebf0e37f952b9b46e25e6c8 | jjzhang166/Python-OOP-High | /OOP/13-对象属性和类属性.py | 433 | 4.15625 | 4 | #对象属性和类属性
class A():
#在这里定义的属性是类属性,如果没有同名的对象属性,则调用类属性
name = 'a'
def __init__(self,name):
self.name = name
self.haha = 1
a = A('haha')
print(a.name)
#类只能调用类属性
#print(A.haha)
print(A.name)
del a.name
print(a.name)
#注意一般不要将对象属性与类属性同名,否则对象属性将屏蔽掉类属性
| false |
f3afbefdd0c0209e09aba11b9dcef1b6c1f1f997 | jjzhang166/Python-OOP-High | /OOP/12-析构函数.py | 320 | 4.125 | 4 | '''
析构函数:
在类的对象被释放(程序结束或者对象被释放掉)
时,调用该函数,执行一些功能
'''
class A():
def say(self):
print('hello,python')
def __del__(self):
print('该对象被释放了')
a = A()
a.say()
del a
print('--------------------------------') | false |
2a7aa7b609c6d0cf17e31f7a51dfed825e52b4b4 | Jason-Delancey/Python | /conditionals.py | 1,529 | 4.34375 | 4 | #The program is just used as practice for using conditionals
#by Jason Delancey
#use if conditional with lists
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
print()
#inequality testing
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
print()
#checking multiple conditions
age_0 = 22
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
print()
#compare a value with elements in a list
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
else:
print()
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
#check to ensure the list is not empty first before running a for loop
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
print()
#compare multiple lists
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!") | true |
530273bb4f2845acc98006443cf73a418c5cd38a | motomax990/lictions | /liction2/Chepa/spiral1.py | 1,194 | 4.15625 | 4 | import turtle
from math import sin, cos, pi, radians
import time
R = int(turtle.textinput("Введите радиус: ", "Ввелите радиус: "))
n = int(turtle.textinput("Введите растояние между спиралями: ", "Ввелите растояние между спиралями: "))
x0 = int(turtle.textinput("Введите x чепы: ", "Ввелите x чепы: "))
y0 = int(turtle.textinput("Введите y чепы: ", "Ввелите y чепы: "))
turtle.color('red')
turtle.penup()
turtle.goto(x0 + R, y0)
turtle.pendown()
def circlMy1(r, a, n):
shift = n/360
#shift = 1
print(shift)
for c in range(0,361, a):
rd = pi/180*a
turtle.left(a)
turtle.speed(100)
turtle.forward(sin(rd)* (r + shift * c))
#turtle.right(90)
#turtle.forward(shift)
#turtle.left(90)
a = 1
for i in range(int(turtle.textinput("Введите колво петлей: ", "Введите колво петлей: "))):
circlMy1(R + (n * i), a, n)
turtle.penup()
turtle.goto(x0 + (-R), y0)
turtle.pendown()
#turtle.circle(100)
turtle.exitonclick()
| false |
0c044209a922c6c22375b1aad779420cba3e638b | mingregister/design-patterns | /结构型/不常用/11组合模式(Composite)/composite-luffycity.py | 1,226 | 4.21875 | 4 | # coding: utf-8
from abc import ABCMeta, abstractclassmethod
# 抽象组件
class Graphic(metaclass=ABCMeta):
@abstractclassmethod
def draw(self):
pass
# 叶子组件
class Point(Graphic):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "点(%s, %s)" %(self.x, self.y)
def draw(self):
print(str(self))
# 叶子组件
class Line(Graphic):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def __str__(self):
return "线段[%s, %s]" % (self.p1, self.p2)
def draw(self):
print(str(self))
# 复合组件
class Picture(Graphic):
def __init__(self, iterable):
self.children = []
for g in iterable:
self.add(g)
def add(self, graphic):
self.children.append(graphic)
def draw(self):
print("--------复合图形--------------------")
for g in self.children:
g.draw()
print("--------复合图形--------------------")
l = Line(Point(1,1), Point(2,2))
l.draw()
# print(l)
p1 = Point(2,3)
l1 = Line(Point(3,4), Point(6,7))
l2 = Line(Point(1,3), Point(7,8))
pic1 = Picture([p1, l1, l2])
pic1.draw() | false |
1ac4adfdb761ec9f56e4696dcac943f21b0e8cb2 | uma5958/PythonBasics-RaghavPal | /Basics/Basics2.py | 614 | 4.1875 | 4 | # ifelse-if
if 5>3:
print("5 is greater than 3")
num = 0
if num>0:
print("This is positive number")
elif num==0:
print("number is zero")
else:
print("This is a nagative number")
# for loop
num = [1,2,3,4,5]
for val in num:
print(val)
num = [1,2,3,4,5]
sum = 0
for val in num:
sum=sum+val
print("Total is: ",sum)
# for-else combination
fruits = ["apple", "oranges", "grapes"]
for val in fruits:
print(val)
else:
print("No fruits left")
# while loop
# num = 10
print("Enter a number: ")
num = int(input())
sum = 0
i=1
while i<num:
sum=sum+i
i=i+1
print("Total is: ",sum)
| true |
c4ca9d1cbdb3f2b09e5d55848bad9dafa57e6ad7 | dazvid/cryptopals | /2_9.py | 1,490 | 4.28125 | 4 | #!/usr/bin/python3
"""
2_9.py
Implement PKCS#7 padding
A block cipher transforms a fixed-sized block (usually 8 or 16 bytes) of
plaintext into ciphertext. But we almost never want to transform a single
block; we encrypt irregularly-sized messages.
One way we account for irregularly-sized messages is by padding, creating
a plaintext that is an even multiple of the blocksize. The most popular
padding scheme is called PKCS#7.
So: pad any block to a specific block length, by appending the number of
bytes of padding to the end of the block. For instance,
"YELLOW SUBMARINE"
... padded to 20 bytes would be:
"YELLOW SUBMARINE\x04\x04\x04\x04"
"""
#######################################
# IMPORTS
#######################################
from binascii import a2b_qp
import sys
#######################################
# FUNCTIONS
#######################################
def pad_message(message, block_size):
"Pad message to be block_size"
fill = block_size - len(message)
bytes_str = message.encode('utf-8')
for _ in range(fill):
bytes_str += fill.to_bytes(1, byteorder=sys.byteorder)
return bytes_str.decode('utf-8')
#######################################
# MAIN
#######################################
message = 'YELLOW SUBMARINE'
block_size = 20
padded = pad_message(message, block_size)
print('Original: {} ({})\nPadded: {} ({})'.format(message, len(message),
a2b_qp(padded), len(padded)))
| true |
a50127229e07273def9dcaeb68fa4ebe871b1c13 | AngelWings1997/Algorithm-and-Complexity | /Basic Knowledge/Data Structure/list (linked list implementation).py | 1,755 | 4.3125 | 4 | """
# -*- coding: utf-8 -*-
@author: Hongzhi Fu
"""
# sequential list (linked list implementation) and its three operations: Search, Insert and Remove
# complexity: search Θ(n), insert Θ(1) remove Θ(1)
class Node(object):
def __init__ (self, value):
self.value = value
self.next = None
class Linked_List(object):
def __init__(self):
self.length = 0
self.header = None
def search(self, value):
p = self.header # retrieve the first node
while p != None:
if p.value == value:
return p
p = p.next
return None
def insert(self, value):
# instantiate a new node
p = Node(value)
p.next = self.header
self.header = p
self.length += 1
def remove(self):
p = self.header # retrieve the first node
if p is not None:
self.header = p.next
self.length -= 1
del p # delete node p
def traversal(self):
array = [] # for displaying
p = self.header
while p is not None:
array.append(p.value)
p = p.next
return array
elements = [24, 22, 76, 41, 7, 61, 15, 34, 80]
# initialize an empty linked list
linked_list = Linked_List()
# construct linked list
for e in elements:
linked_list.insert(e)
print("The original array: \n", linked_list.traversal())
# search node 61
print("Search node 61:")
if linked_list.search(61):
print("Search is successful!")
else:
print("Search is unsuccessful!")
# remove a node
linked_list.remove()
print("After removing a node: \n", linked_list.traversal())
# insert node 80
linked_list.insert(80)
print("After inserting node 34: \n", linked_list.traversal())
| true |
980d30357ef3dde054d58fd0f101ef64eedaaf6e | AngelWings1997/Algorithm-and-Complexity | /Transform and Conquer/Presorting/check element uniqueness.py | 891 | 4.1875 | 4 | """
# -*- coding: utf-8 -*-
@author: Hongzhi Fu
"""
# implementation of checking element uniqueness with the idea of presorting
# time complexity: Θ(nlog n) + Θ(n) = Θ(nlog n)
# space complexity: Θ(1)
"""
# brute-force approach
# time complexity: Θ(n^2)
# space complexity: Θ(1)
def is_unique_bf(array):
length = len(array)
for i in range(length-1):
element = array[i]
for j in range(i+1, length):
if array[j] == element:
return False
return True
"""
def is_unique_presort(array):
length = len(array)
array.sort() # sort array
for i in range(length-1):
if array[i] == array[i+1]:
return False
return True
array = [3, 1, 6, 2, 7, 9]
# array = [2, 4, 1, 6, 2, 5]
if is_unique_presort(array):
print("Elements in the array is unique.")
else:
print("Elements in the array is not unique.") | true |
92decdecf43cdc354d44717bdcf93f34f4bd46f7 | Pasiak/UDEMY_PythonFirstSteps | /UDEMY_S1_S2/01.05_Date.py | 844 | 4.28125 | 4 | print("Hello what day is today?")
from datetime import date
print("Today is")
print (date.today().strftime("%A"))
# Komentarze
'''
Ten skrypt policzy ile razy mrugamy okiem w czasie X lat.
Zakladamy ze:
-liczba mrugniec na minute to 20
-liczba minut w godzinie to 60
-liczba godzin w dobie 24
-liczba lat (czyli nasz X) 50
Uwaga: jezeli przyjac ze spimy 8 godzin to liczba godzin na dobe
powinna wynosic 16
'''
# l mrugnięć na min
blinksPerMin = 20
# l minut w godzinie i godzin w dobie
minInHour = 60
hoursInDay = 16
daysInYears = 365
# Liczba lat
years = 50
print (blinksPerMin * minInHour * hoursInDay * daysInYears)
#definitionOfVariables
daysOfWorkPermonth = 20
monthsInYear = 12
vacation = 26
yearsOfWOrk = 40
#result
print((daysOfWorkPermonth * monthsInYear - vacation)*yearsOfWOrk)
input ("Press Enter to continue")
| false |
f4035e57633a0d84084877aca8affd69aa7b0d5c | AnkuKumar029/hacktober-21 | /Rudra4.py | 497 | 4.34375 | 4 | # Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]
# use anonymous function to filter
result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
# Python Program to find the factors of a number
# This function computes the factor of the argument passed
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = 320
print_factors(num)
| true |
15ba49d381f771ea30b4ae0551c781225c9dff5c | arunshenoy99/python-assignments | /list7.py | 309 | 4.375 | 4 | # Reversing a List
def normal_method(my_list):
new_list = my_list[::-1]
return new_list
my_list = [1,2,3]
print('Normal method:{}'.format(normal_method(my_list)))
my_list.reverse()
print('Using reverse function:{}'.format(my_list))
#output
#Normal method:[3, 2, 1]
#Using reverse function:[3, 2, 1] | true |
c1c81a44f6b7fb340ab1766698c3c402b9251343 | arunshenoy99/python-assignments | /list9.py | 810 | 4.25 | 4 | # Count occurrences of an element in a list
def list_count(my_list, ele):
count = 0
for el in my_list:
if el == ele:
count += 1
return count
my_list = []
n = int(input('Enter the length of the list:'))
for i in range(0, n):
el = input('Enter the {} element of the list:'.format(i))
my_list.append(el)
ele = input('Enter the element to find its count in the list:')
print('Using normal method:{}'.format(list_count(my_list, ele)))
print('Using count() method:{}'.format(my_list.count(ele)))
#output
#Enter the length of the list:4
#Enter the 0 element of the list:a
#Enter the 1 element of the list:b
#Enter the 2 element of the list:c
#Enter the 3 element of the list:a
#Enter the element to find its count in the lista
#Using normal method:2
#Using count() method:2 | true |
c31d45be061f14f726a49cd9e8ec2b580c7d6a73 | cao527121128/Python-study | /untitled/tuple(元组).py | 2,484 | 4.375 | 4 | #coding=utf-8
print("tuple元组")
'''
tuple
本质: 是一种有序的集合
特点:
1、与列表相似
2、一旦初始化就不能修改
3、使用小括号
4、元组相对于列表更加安全 能用元组的尽量用元组不用列表
创建tuple
格式:
元组名 = (元组元素1,元组元素2,......,元组元素n)
'''
#创建空元组
tuple1 = ()
print(tuple1)
#创建带有元素的元组,元组中的元素可以是不同类型的数据
tuple2 = (1,2,3,"good",True)
print(tuple2)
#定义只有一个元素的元组
tuple3 = (1,)
print(tuple3)
print(type(tuple3))
#元组元素的访问
#格式: 元组名[下标]
#下标从0开始
tuple4 = (1,2,3,4,5)
print(tuple4[0])
print(tuple4[1])
print(tuple4[2])
print(tuple4[3])
print(tuple4[4])
#print(tuple4[5]) 越界
#获取元组的最后一个元素
print(tuple4[-1])
#修改元组
tuple5 = (1,2,3,4,[5,6,7])
#tuple5[0] = 100 #报错 元组一旦初始化 元组的元素就不可修改
print(tuple5)
#tuple5[-1] = [7,9,10] #报错 元组一旦初始化 元组的元素就不可修改
print(tuple5)
tuple5[-1][0] = 500 #元组一旦初始化 元组的元素就不可修改,但是如果这个元素是可变的,则可以修改该元素 比如列表
#实际上[5,6,7]在该元组里面存放的是一个内存地址,该内存地址不可变,但是内存地址里面存放的列表元素可以修改
print(tuple5)
#删除元组
tuple6 = (1,2,3)
del tuple6
#print(tuple6)
#元组的操作
#元组相加
t7 = (1,2,3)
t8 = (4,5,6)
t9 = t7 + t8
print(t9)
print(t7,t8)
#元组重复
t10 = (1,2,3)
print(t10 * 3)
#判断元素是否在元组中
t11 = (1,2,3)
print(1 in t11)
print(1 not in t11)
print(4 in t11)
print(4 not in t11)
#元组的截取
#格式:元组名[开始下标:结束下标]
#从开始下标开始截取,截取到结束下标之前
t12 = (1,2,3,4,5,6,7,8,9)
print(t12[3:7])
print(t12[3:])
print(t12[:7])
#二维元组
#元素为一维元组的元组
t13 = ((1,2,3),(4,5,6),(7,8,9))
print(t13[1][1]) #访问5
#元组的方法
#len()
#返回元组中元素的个数
t14 = (1,2,3,4)
print(len(t14))
#max() 返回元组中的最大值
#min() 返回元组中的最小值
print(max((1,2,3,4,5)))
print(min((1,2,3,4,5)))
#将列表转成元组
list = [1,2,3]
t15 = tuple(list)
print(t15)
#元组的遍历
for i in (1,2,3,4,5):
print(i) | false |
eef84a8b7673d99fafb0c800c511b50a20cb1925 | cao527121128/Python-study | /untitled/面向对象思想-类/5self.py | 1,406 | 4.25 | 4 | #coding=utf-8
'''
self 代表类的实例,而非类
哪个对象调用方法,那么该方法中的self就代表那个对象
self.__class__ 代表类名
'''
class Person(object):
#定义方法(也即是定义函数)
#注意:方法的参数必须以self为第一个参数
#self代表类的实例(某一个对象)
def run(self):
print("run")
#self.__class__ 代表类名 可以等同于p=Persion("lilei",20,170,130) 创建Person对象
print(self.__class__)
p = self.__class__("lilei",20,170,130)
print(p)
def eat(self,food):
print("eat " + food)
def openDoor(self):
print("open door")
def fillEle(self):
print("fill Ele")
def closeDoor(self):
print("close door")
def say(self):
print("Hello! my name is %s, I am %d years old" %(self.name,self.age))
#self不是关键字,换成其他的字符也是可以,但是约定俗成都是使用self字符
def play(a):
print("play " + a.name)
def __init__(self,name,age,height,weight):
#print("这里是init")
self.name = name
self.age = age
self.height = height
self.weight = weight
pass
per1 = Person("hanmeimei",20,170,55)
per1.say()
per2 = Person("Tom",22,175,70)
per2.say()
per2.play()
per2.run()
| false |
72194d7f405ba3e6e0609700b37b002e86281e2f | DocterBack/Specialist_Python | /python_1/day_1/sorting_hat.py | 789 | 4.125 | 4 | age = input('Введите ваш возраст: ')
if age.isdigit():
age = int(age)
if age <= 3:
print('Вы сидите дома')
elif age > 3 and age <= 6:
print('Вам пора в садик')
elif age > 6 and age <= 17:
print('Вам пора в школу')
elif age > 17 and age <= 22:
print('Вам пора в институт')
elif age > 22 and age <= 25:
print('Вам пора в аспирантуру')
elif age > 25 and age <= 59:
print('Вам пора на работу')
elif age > 60:
print('Пора на дачу, Ва пенсионер')
else:
print('Ого, а это как?')
else
print('Возраст необходимо указать простым числом')
| false |
b50daacd6ad7cc554606699e626a9fc2b5b7a3e0 | gangadharsingh/20186074_CSPP-1 | /cspp1_practice/m9/Odd Tuples Exercise/odd_tuples.py | 795 | 4.15625 | 4 | '''#Exercise : Odd Tuples
#Write a python function oddTuples(aTup) that takes a some numbers in the tuple as input and
returns a tuple in which contains odd index values in the input tuple
@author: gangadharsingh
'''
def odd_tuples(atup_inp):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# Your Code Here
t_empt = ()
j_chec = 0
for i_chec in atup_inp:
if j_chec % 2 == 0:
t_empt = t_empt+ tuple(i_chec)
j_chec += 1
return t_empt
def main():
'''Input : Tuple
Output : Odd place in Tuple
'''
data = input()
data = data.split()
atup_inp=()
for j_inp in range(len(data)):
atup_inp += ((data[j_inp]),)
print(odd_tuples(atup_inp))
if __name__ == "__main__":
main()
| false |
1570bb62f7ae0bba04ca2d73bf3bc930df15432b | gangadharsingh/20186074_CSPP-1 | /cspp1-assignments/m20/CodeCampMatrixOperations/matrix_operations.py | 2,286 | 4.21875 | 4 | '''Matrix addition and multiplication
'''
def mult_matrix(mat_1, mat_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes invalid for mult"
'''
if len(mat_1[0]) != len(mat_2):
print("Error: Matrix shapes invalid for mult")
`
return None
return mat_mul
def add_matrix(mat_1, mat_2):
'''
check if the matrix shapes are similar
add the matrices and return the result matrix
print an error message if the matrix shapes are not valid for addition
and return None
error message should be "Error: Matrix shapes invalid for addition"
'''
sum_m = []
if len(mat_1) == len(mat_2) and len(mat_1[0]) == len(mat_2[0]):
for i in range(len(mat_1)):
for j in range(len(mat_1[i])):
sum_m.append(mat_1[i][j] + mat_2[i][j])
return [sum_m[cnt:cnt+len(mat_1[0])] for cnt in range(0, len(sum_m), len(mat_1[0]))]
print("Error: Matrix shapes invalid for addition")
return None
def read_matrix():
'''
read the matrix dimensions from input
create a list of lists and read the numbers into it
in case there are not enough numbers given in the input
print an error message and return None
error message should be "Error: Invalid input for the matrix"
'''
mat = []
list_inp = input().split(',')
row_m, col_m = int(list_inp[0]), int(list_inp[1])
for _ in range(row_m):
l_mat_r = input().split(' ')
if col_m == len(l_mat_r):
mat.append([int(i) for i in l_mat_r])
else:
print("Error: Invalid input for the matrix")
return 0
return mat
def main():
'''main function
'''
# read matrix 1
mat_one = read_matrix()
# read matrix 2
mat_two = read_matrix()
if mat_one != 0 and mat_two != 0:
print(add_matrix(mat_one, mat_two))
print(mult_matrix(mat_one, mat_two))
else:
exit()
# add matrix 1 and matrix 2
# multiply matrix 1 and matrix 2
if __name__ == '__main__':
main()
| true |
e44b2a721304cb951e4484242697bbf2994c1b09 | Pratham82/Python-Programming | /23. Generators/Gnerators_homework.py | 1,437 | 4.375 | 4 | # Problem 1
# Create a generator that generates the squares of numbers up to some number N.
def squares_gen(num):
for i in range(num):
yield i**2
print(squares_gen)
# Iterating through generator
for i in squares_gen(10):
print(i)
# Problem 2
# Create a generator that yields "n" random numbers between a low and high number (that are inputs).
import random
def random_gen(start,end,num):
for i in range(num):
i = random.randint(start,end)
yield i
print(random_gen)
# Iterating through generator
for i in random_gen(1,10,10):
print(i)
# Problem 3
# Use the iter() function to convert the string below into an iterator:
# Problem 3
# Use the iter() function to convert the string below into an iterator:
string1 = "Example_string"
string1_iterator =iter(string1)
for i in string1_iterator:
print(i)
# Problem 4
# Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement.
# Ans- We can use it when the data that we are storing is extremely huge
# In that case we can use yield keyword retrieving values one by one, rather than
# storing it in a list
# Extra credit
# gencomp
list1 = [213,4,235,43,56,546,5]
list_comp = [ i for i in list1 if i>200]
print(list_comp)
gen_comp =(i for i in list1 if i>200)
print("gen_comp object: ",gen_comp)
# iterating thorugh generator
for i in gen_comp:
print (i)
| true |
cb3325872db59b2bfe03def9ef056b2fd6d5d18d | Pratham82/Python-Programming | /Practice_problems/Palindrome.py | 276 | 4.375 | 4 |
def Palindrome_Checker(str1):
rev = ''
for i in str1:
rev = i + rev
if rev == str1:
print("Entered string is palindrome")
else:
print("Entered string is not palindrome")
entry = input("Enter string here: ")
Palindrome_Checker(entry) | true |
b683976869fac9e578920e84e3abbca83fcb631c | Pratham82/Python-Programming | /25. Advanced objects and DS/Advanced dictionaries.py | 440 | 4.46875 | 4 |
#* Advanced Dictionaries
#* dictionary comprehension
dict1 = {'k1':1,'k2':2}
dict2 ={x:x**2 for x in range(1,11)}
print(dict2)
# assigning keys which are not based on the values
dict3 ={k:v**2 for k,v in zip(['a','b'],range(2))}
print(dict3)
#* Iteration over keys,values
for i in dict1.items():
print(i)
#* Iteration over keys
for i in dict1.keys():
print(i)
#* Iteration over values
for i in dict1.values():
print(i)
| false |
9bcf69e088454c38788983197bce0a2864ec2f6d | Pratham82/Python-Programming | /Practice_problems/Edabit/FizzBuzz.py | 783 | 4.53125 | 5 | # FizzBuzz Interview Question
# Create a function that takes a number as an argument and returns "Fizz", "Buzz" or "FizzBuzz".
# If the number is a multiple of 3 the output should be "Fizz".
# If the number given is a multiple of 5, the output should be "Buzz".
# If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz".
# If the number is not a multiple of either 3 or 5, the number should be output on its own as shown in the examples below.
# The output should always be a string even if it is not a multiple of 3 or 5.
def fizz_buzz(num):
return "FizzBuzz" if num % 3 == 0 and num % 5 == 0 else "Fizz" if num % 3 == 0 else "Buzz" if num % 5 == 0 else str(num)
print(fizz_buzz(15))
print(fizz_buzz(5))
print(fizz_buzz(3))
print(type(fizz_buzz(98))) | true |
d80e0ec670d642ed67400a61fee1bf56c8373b02 | Pratham82/Python-Programming | /Important Concepts/Conunter/counter_working.py | 514 | 4.3125 | 4 | """
Say you have a file that contains some text. You need to count the number of times each letter appears in the text. For example, say you have a file called sample.txt
"""
from collections import Counter
sample_file = open('sample.txt', 'r')
def count_letters(fileName):
letter_counter = Counter()
for line in fileName:
line_letters = [word for word in line.lower() if word.isalpha()]
letter_counter.update(line_letters)
return letter_counter
print(count_letters(sample_file))
| true |
c305d006acf8fcb4ec74baf48ef74bc58b3bead0 | Pratham82/Python-Programming | /Practice_problems/Edabit/Characters in shapes.py | 280 | 4.125 | 4 | # Characters in Shapes
# Create a function that counts how many characters make up a rectangular shape. You will be given a list of strings.
def count_characters(lst):
return len(sum(list(map(lambda x: list(x), lst)),[]))
print(count_characters([
"###",
"###",
"###"
])) | true |
8085ef8cf805f5d05f2ca16c0ab5d310f0c3a2bf | Pratham82/Python-Programming | /Exercises from books/Learn python the hard way/Exercise_16.py | 1,164 | 4.1875 | 4 | from sys import argv
import sys
script, filename = argv
val = False
prompt ="-->"
# Creating file objects for writing and reading
file_obj_read = open(filename)
print("_________________________________")
print("This is old content in your file")
print(file_obj_read.read())
print("_________________________________")
file_obj = open(filename,'w')
print(f"In order to write new text we have to erase {filename} file")
print("Do you want to continue?: enter 'y' ")
while val == False :
decision = input(prompt)
if not decision or decision!= 'y':
print("You didn't entered anything / you didn't entered correct input ")
decision = input(prompt)
pass
elif decision =='y':
print("Opening file...")
# Erasing file
print(f"No we are deleting file")
print("Are you sure: ?")
file_obj.truncate()
print("Files deleted")
# Taking input for new lines
print("Enter new text: ")
line1 = input(prompt)
# Adding our new lines to the file
file_obj.write(line1)
print("Lines added")
file_obj.close()
val = True
| true |
b42cd51545a1f0ff00d0c636bb53addc532c999e | Pratham82/Python-Programming | /Practice_problems/Edabit/GIven character count.py | 372 | 4.125 | 4 | # Count Instances of a Character in a String
# Create a function that takes two strings as arguments and returns the number of times the first string (the single character) is found in the second string.
# char_count("a", "edabit") ➞ 1
def char_count(txt1, txt2):
return len(list(filter(lambda v: v == txt1, list(txt2))))
print(char_count("c", "Chamber of secrets")) | true |
13fbdc883fe5e21af57f1881f38bc987f4e7d526 | Pratham82/Python-Programming | /Practice_problems/Edabit/Nth Smallest Element.py | 489 | 4.34375 | 4 | # Nth Smallest Element
# Given an unsorted list, create a function that returns the nth smallest element (the smallest element is the first smallest, the second smallest element is the second smallest, etc).
# example
# nth_smallest([1, 3, 5, 7], 1) ➞ 1
# nth_smallest([1, 3, 5, 7], 3) ➞ 5
# nth_smallest([1, 3, 5, 7], 5) ➞ None
def nth_smallest(lst, n):
return sorted(lst)[n-1] if len(lst)>= n else None
print(nth_smallest([1, 3, 5, 7], 3))
print(nth_smallest([1, 3, 5, 7], 5)) | true |
73ad4291b3dff6d954528839c039724f68088306 | Pratham82/Python-Programming | /23. Generators/Generators.py | 1,110 | 4.3125 | 4 | # Generator function allow us to write a function that can send back a value
# and later resume to pick up where it left off.
# It allows us to genrate a sequence of values over time,it uses yield statement
# When it is compiled they became object which supports and iteration protocol
# Create cubes
def get_cubes(num):
result =[]
for i in range (num):
result.append(i**3)
return result
print(get_cubes(10))
for x in get_cubes(10):
print(x)
# Genrators makes our program memory efficient. When we use list and returning
# it, teh list will be loaded in memory, if the list has large amount of numbers
# then it will hoard a lot of memory. For avoiding this we can use generators
# Rather than storing the values in the list we can yield the values and later
# iterate though them for retrieval.
def get_cubes2(num):
for i in range(num):
yield i**3
# if we try to retrun get_cubes2() then it will provides us the genearator object
print(get_cubes2(11))
# for getting the values we have to iterate though the generator
for i in get_cubes2(11):
print(i) | true |
e6f12fc7a3900cdef34d16a69f1e14efb6e68998 | Pratham82/Python-Programming | /22. Decorators/Decorators_1.py | 933 | 4.59375 | 5 | # Decorater allows you to decorate a function.
# It can be used when we wanted to add new functionality to old method
# Decorators allows us to add on extra functionality to an already existing function.
# They use the @ operator and are the placed on top of the original function
def func1():
return 2
# When we print it out we get: <function func1 at 0x0302DF58> this can be assigned to another functions
# variable func1 is actually assigned to func1()
# and this func1 variabale can be assigned to another variable
print("func1: ",func1)
def hello():
return "Hello there!!"
print("hello: ",hello)
greet = hello
print("greet: ",greet) # hello function objetc will be stored in greet variable
print(greet())
# hello function objetc will e stored in greet even after we delete hello function
del hello
print("After deleting")
try:
print(hello())
except:
print("Hello function is deleted. ")
print(greet())
| true |
bbd7a6c930c6fef6d9587ccbdbbfa43a77cc66d0 | Pratham82/Python-Programming | /Practice_problems/Edabit/25 Mile marathon.py | 649 | 4.46875 | 4 | # 25-Mile Marathon
# Mary wants to run a 25-mile marathon. When she attempts to sign up for the marathon, she notices the sign-up sheet doesn't directly state the marathon's length. Instead, the marathon's length is listed in small, different portions. Help Mary find out how long the marathon actually is.
# Return True if the marathon is 25 miles long, otherwise, return False.
# Examples
# marathon_distance([1, 2, 3, 4]) ➞ False
# marathon_distance([1, 9, 5, 8, 2]) ➞ True
def marathon_distance(*args):
return sum(list(map(lambda x: abs(x), d))) == 25
print(marathon_distance([1, 2, 3, -4]))
print(marathon_distance([1, 9, 5, 8, 2])) | true |
af284d82420a7841cfb7ead03aff2c8fc976b9be | catcheme/python | /prestudy/demo4.py | 1,481 | 4.28125 | 4 | name='张三'
age=20
print(type(name),type(age)) #说明name和age数据类型不同
#print('我叫'+name+'今年'+age+'岁') #当将str类型与int类型进行连接时,报错,解决方案,类型转换
print('我叫'+name+'今年'+str(age)+'岁')
print('---------str()将其他类型转换成str-------')
a=10
b=198.8
c=False
print(type(a),type(b),type(c))
print(str(a),str(b),str(c),type(str(a)),type(str(b)),type(str(c)))
print('----------------int()能将其他类型转换成int型---------')
s1='128'
f1=98.7
s2='76.77'
ff=True
s3='hello'
print(type(s1),type(f1),type(s2),type(ff),type(s3))
print(int(s1),type(int(s1))) #将str转成itn型,前提是字符串为数字串
print(int(f1),type(int(f1))) #float转成int型,截取整数部分,舍掉小数部分
#print(int(s2),type(int(s2))) #将str转成int型,报错,因为字符串为小数串
print(int(ff),type(int(ff)))
#print(int(s3),type(int(s3))) #将str转成int型,字符串必须为数字串(整数),非数字串不允许转换
print('------------float()函数,将其他数据类型转成float类型--------')
s1='128.98'
s2='76'
ff=True
s3='hello'
i=98
print(type(s1),type(s2),type(ff),type(s3),type(i))
print((float(s1),type(float(s1))))
print((float(s2),type(float(s2))))
print((float(ff),type(float(ff))))
#print((float(s3),type(float(s3)))) #字符串中的数据如果是非数字字符串,则不允许转换
print(float(i),type(float(i)))
| false |
82598b1ba676e1ac3cdffb9aed50d5cbfb01656c | jakubowiczish/codewars-solutions | /src/_8kyu/_8kyu_beginner_series_cockroach/cockroach.py | 389 | 4.1875 | 4 | """
The cockroach is one of the fastest insects.
Write a function which takes its speed in km per
hour and returns it in cm per second,
rounded down to the integer (= floored).
For example:
cockroach_speed(1.08) == 30
Note! The input is a Real number
(actual type is language dependent) and is >= 0.
The result should be an Integer.
"""
def cockroach_speed(s):
return s * 250 // 9 | true |
31990bcb90de8aa1a82aa47bef23b3fb709f0109 | diskpart123/xianmingyu | /2.python第四章学习/11身份运算符is.py | 883 | 4.34375 | 4 |
"""
is 成员运算符:判断内存地址是否一样
num1 = 3
num2 = 3
print(id(num1), id(num2))
if num1 is num2:
print("num1和num2是同一个内存地址")
num2=4 #变更了num2这个对象的值为4
if num1 is num2:
print("num1和num2是同一个内存地址")
else:
print("两个地址不一样了")
"""
"""
is not 成员运算符:判断不是同一个地址
num3=5
num4=6
if num3 is not num4:
print("两个变量对象的地址确实不一样....")
else:
print("两个变量对象的地址一样")
"""
"""
总结:
is和is not,结合上面的案例说明:编译器中有一个常量表,如num1=3,num2=4
其中值3和4就存在常量表当中,且它们的内存地址不一样,如:3这个值的内存地址
是:140712702931264,4这个值的内存地址是:140712702931296,这里的is和
is not 判断的就是内存地址是否一样
"""
| false |
cde2fbb82d60db6f6aac1deee647fa9432403f68 | Samuel001-dong/Thread_example | /literal_test/err&exception.py | 800 | 4.25 | 4 | """"
错误&异常学习示例
"""
# 除零异常
# def div(x, y): # 此时y是不能为0的
# return x/y
# 首先执行try,如果有异常则会执行except(此时try后面的代码不再执行),没有异常则不会执行except,但无论如何最后都会执行finally
# list1 = [1, 2, 3]
# try:
# print("try:----------------------")
# print(div(2, 1))
# print(list1[0])
# except Exception as e:
# print("except--------------------")
# print(e)
# else:
# print("无异常发生------------------")
# finally:
# print("finally:------------------")
# a = 1
def set_age(num):
if num <= 0 or num > 200:
raise ValueError(f"值错误:{num}") # 自己抛出一个异常
else:
print(f"设置年龄为:{num}")
set_age(-1)
| false |
f497b79bd95e5c05b29f723c09c9c6b1adcb205c | sns/playground | /leetcode/Microsoft/arrays_and_strings/rotate_image.py | 1,635 | 4.375 | 4 | """
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n < 2:
return
F=0
L=n-1
while F<L:
matrix[F][F], matrix[F][L] = matrix[F][L], matrix[F][F]
matrix[F][F], matrix[L][L] = matrix[L][L], matrix[F][F]
matrix[F][F], matrix[L][F] = matrix[L][F], matrix[F][F]
i=F+1
while i < L:
matrix[F][i], matrix[i][L] = matrix[i][L], matrix[F][i]
matrix[F][i], matrix[L][(L-F)-i] = matrix[L][i], matrix[F][i]
matrix[F][i], matrix[(L-F)-i][F] = matrix[i][F], matrix[F][i]
i+=1
F+=1
L-=1
s=Solution()
input=[[1,2,3],[4,5,6],[7,8,9]]
expectedOutput=[[7,4,1],[8,5,2],[9,6,3]]
s.rotate(input)
print(input==expectedOutput) | true |
e96e2c5461bcd093422beb7db9731795d64d0d03 | sns/playground | /leetcode/Microsoft/arrays_and_strings/reverse_words2.py | 1,865 | 4.125 | 4 | """
Reverse Words in a String II
Given an input string , reverse the string word by word.
Example:
Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
Note:
A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces.
The words are always separated by a single space.
Follow up: Could you do it in-place without allocating extra space?
"""
from typing import List
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
s.reverse()
start=0
for w in s:
end=start
while end < len(s) and s[end]!=" ":
end+=1
nextStart = end+1
while end-1 > start:
s[start], s[end-1] = s[end-1], s[start]
start+=1
end-=1
start=nextStart
def reverseWords1(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
self.reverseList(s, 0, len(s)-1)
i = 0
j = 0
while i < len(s):
while j < len(s) and s[j] != " ":
j+=1
self.reverseList(s, i, j-1)
j+=1
i=j
def reverseList(self, s: List[str], left, right):
while right > left:
s[left], s[right] = s[right], s[left]
left+=1
right-=1
s=Solution()
input=["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
expected=["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
s.reverseWords(input)
print('Output %s:'% input)
print('Expected: %s'% expected)
print('passed: %s'% (input==expected)) | true |
3465e6a572615f067bfc85089fc470fbc2c09eb7 | sns/playground | /leetcode/Microsoft/arrays_and_strings/set_matrix_zeroes.py | 2,043 | 4.1875 | 4 | """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
----------------------------------------------
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
----------------------------------------------
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
-----------------------------------------------
Follow up:
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
"""
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
# memo = ({}, {})
# m = len(matrix)
# n = len(matrix[0])
# for i in range(m):
# for j in range(n):
# if matrix[i][j] == 0:
# if i not in memo[0]:
# memo[0][i] = True
# if j not in memo[1]:
# memo[1][j] = True
# for i in memo[0]:
# matrix[i][:n]=[0]*n
# for i in range(m):
# for j in memo[1]:
# matrix[i][j] = 0
rows = set()
cols = set()
m = len(matrix)
n = 0 if len(matrix) == 0 else len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
if (i not in rows):
rows.add(i)
if (j not in cols):
cols.add(j)
for i in rows:
for j in range(n):
matrix[i][j] = 0
for j in cols:
for i in range(m):
matrix[i][j] = 0
s = Solution()
input = [[1,1,1],[1,0,1],[1,1,1]]
output = [[1,0,1],[0,0,0],[1,0,1]]
s.setZeroes(input)
print(input == output) | true |
cac7aba0882a5662051c02127b9d3a609b4bbb43 | sumitRaut/PythonTest | /tuples.py | 2,062 | 4.6875 | 5 | # tuple with integers
my_tuple = (1,2,3)
print(my_tuple)
#tuple with different datatypes
my_tuple = (1,'Hello',3)
print(my_tuple)
#nested tuple, conataining list and tuple also
my_tuple = (1,['Hello','World'],(10,25,'Python'))
print(my_tuple)
#packin of tuple
my_tuple = 1, 2.4,'Dog'
print(my_tuple)
#unpacking of a tuple
a, b, c = my_tuple
print(a)
print(b)
print(c)
#Having one element in a tuple is a string, and a tuple with a trailing comma is a tuple
my_tuple = 'Hello'
print(type(my_tuple))
my_tuple = 'Hello',
print(type(my_tuple))
my_tuple = ('Hello')
print(type(my_tuple))
my_tuple = ('Hello',)
print(type(my_tuple))
#indexing
my_tuple = ('p','r','o','g','r','a','m')
print(my_tuple[0])
print(my_tuple[5])
print('-----N tuple-------------------------')
n_tuple = (1,2.4,[8,4,6])
print(n_tuple[2][1])
print(n_tuple[2][2])
#negative indexing
print(my_tuple[-1])
print(my_tuple[-5])
#Slicing
print(my_tuple[0:4])
print(my_tuple[:-5])
print(my_tuple[1:])
print(my_tuple[:6])
print(my_tuple[:]) #print all elements
#changing a tuple
#tuples are immutable, but if tuple contains a list which is a mutable, we can chage it's elements
print('-----------Changing a tuple-------------------')
my_tuple = (1, 2, [2, 5,7])
print(my_tuple)
my_tuple[2][0] = 9
print(my_tuple)
#We can not change elements of tuple but can reassign elements
print('-----------Reassign a tuple-------------------')
my_tuple = (10, 11, 12, 13)
print(my_tuple)
print('-----------Concatenation of a tuple-------------------')
print(my_tuple + n_tuple)
print('-----------Repeation of a tuple-------------------')
print(('Repeat',)*3)
print('----------Deleting of a tuple-------------------')
del my_tuple
#print(my_tuple)
print('----------tuple Methods-------------------')
my_tuple = ('a', 'p', 'p', 'l', 'e')
print(type(my_tuple))
print(my_tuple.index('p')) #This will return index of 1st p
print(my_tuple.count('p'))
print('a' in my_tuple)
print('b' in my_tuple)
print('b' not in my_tuple)
#iterating through a tuple
for word in my_tuple:
print('Letter:', word) | false |
ad2e07259c27e1337da0692bde2064ad518591ac | sumitRaut/PythonTest | /setExamples.py | 2,853 | 4.5 | 4 | #set of integer data type
my_set = {1, 2, 3}
print(my_set)
#set of different data type
my_set = {1, 2.4, 'Hello', (5, 6, 7), 4, 'World', (1, 2, 3)}
print(my_set)
#set cannot have duplicate items
my_set = {1, 2, 3, 4, 2}
print('Duplicate items: ', my_set)
#a set cn be made from a list
my_set = set([1, 2, 3, 4, 2, 4])
print('A set from a list: ',my_set)
#Empty set
print('-------------------Creating Empty set--------------------')
my_set = {}
print(type(my_set))
my_set = set()
print(type(my_set))
#add elements in list
print('---------------Add elements in set-------------------------')
my_set = {1, 2}
print('Original set: ', my_set)
my_set.add(3)
print(my_set)
my_set.update([4, 5])
print(my_set)
#Add function can add only one item, and list can be added
#my_set.add([6])
#print(my_set)
#set, tuple, list can be treated as argument
my_set.update([7,8,1], {1, 2, 10})
print(my_set)
#removing an element from set
#discard, remove, pop, clear
print('-------------Removing an element from set----------------')
my_set = {1, 2, 3, 4}
print(my_set)
my_set.discard(2)
print('After removing 2: ',my_set)
my_set.remove(1)
print('Afer removing 1: ', my_set)
#discrad when element is not present
my_set.discard(6)
print('discrad when element is not present: ',my_set)
#remove when element is not present, it will raise exception
#my_set.remove(6)
#print(my_set)
print('---------Pop and clear examples--------')
my_set = set('HElloworld')
print(my_set)
my_set.pop()
print(my_set)
my_set.pop()
print(my_set)
my_set.clear()
print('Clear the set: ',my_set)
#set operations
print('-------Set operations--------------')
a = {1, 2, 3, 4, 5, 6}
b = {4, 5, 6, 7, 8, 9}
print('a: ', a)
print('b: ', b)
print('a|b: ', a|b)
print('a.union(b): ', a.union(b))
print('b.union(a): ', b.union(a))
print('-------Set Intersection------------')
print('a & b: ', a&b)
print('a.intersection(b): ',a.intersection(b))
print('b.intersection(a): ',b.intersection(a))
print('-----------Set difference-----------------')
print('a - b: ', a - b)
print('b - a: ', b - a)
print('a.difference(b): ',a.difference(b))
print('b.difference(a): ', b.difference(a))
print('-----------Set symmetric difference ------------------')
print('a^b: ', a^b)
print('a.symmetric_difference(b): ',a.symmetric_difference(b))
print('b.symmetric_difference(a): ',b.symmetric_difference(a))
print('----------------Membership test----------------')
my_set = {1, 2, 3, 4}
print(1 in my_set)
print(5 in my_set)
print(5 not in my_set)
print('------------------Iterating through a set-------')
my_set = set('HelloWorld')
for letter in my_set:
print('\n',letter)
print('-------------Frozen set----------------')
#frozen set is immutable
a = frozenset([1, 2, 3, 4])
b = frozenset([3, 4, 5, 6])
print(a.difference(b))
#a.add(2)#AttributeError: 'frozenset' object has no attribute 'add' | true |
ed5a8e837ef6da2c17f904624ba28b3081caa0cc | jacob-bonner/ICS3U-Unit6-03-Python | /smallestnumber.py | 941 | 4.3125 | 4 | #!/usr/bin/env python3
# Created by: Jacob Bonner
# Created on: September 2019
# This program finds the smallest number in an array
import random
def calculate(array_of_numbers):
# This function finds the smallest number in a list
# Variables
small_number = 100
# Process
for counter in array_of_numbers:
if counter < small_number:
small_number = counter
# Output
return small_number
def main():
# This function creates an array of 10 numbers then prints out the smallest
# Array
number_array = []
# Adding numbers to an array
for counter in range(10):
random_number = random.randint(1, 100)
print(random_number)
number_array.append(random_number)
# Process
smallest_number = calculate(number_array)
# Output
print("")
print("The smallest number in the array is", smallest_number)
if __name__ == "__main__":
main()
| true |
f037581c794715e050c551512638e4fa59a1e6bf | Lzm0010/cipher_python | /start.py | 2,228 | 4.125 | 4 | #imports
from affine import Affine
from caesar import Caesar
from mykeyword import Keyword
from transposition import Transposition
def run_cipher():
#print welcome and available ciphers
print("Welcome to myCipher. We can encrypt or decrypt using the following ciphers: \n")
print(" -Affine Cipher\n")
print(" -Caesar Cipher\n")
print(" -Keyword Cipher\n")
print(" -Transposition Cipher\n")
#variables
cipher_invalid = True
valid_ciphers = ["affine", "caesar", "keyword", "transposition"]
e_or_d_invalid = True
#Loop until valid cipher is chosen
while cipher_invalid:
cipher = input("Which cipher would you like to use? ").lower()
if cipher in valid_ciphers:
cipher_invalid = False
else:
print("\nNot valid cipher")
#loop until encrypt or decrypt is chosen
while e_or_d_invalid:
encrypt_or_decrypt = input("Excellent choice! Are you encrypting or decrypting? Type E/d ").lower()
if encrypt_or_decrypt == "e" or encrypt_or_decrypt == "d":
e_or_d_invalid = False
else:
print("\n Not sure whether to encrypt or decrypt! Type E/d?")
#give message to encrypt or decrypt
msg = input("What is your message? ")
#encrypt or decrypt branching
if encrypt_or_decrypt == "e":
if cipher == "caesar":
e_msg = Caesar().encrypt(msg)
elif cipher == "affine":
e_msg = Affine().encrypt(msg)
elif cipher == "keyword":
keyword = input("What is your keyword? ")
e_msg = Keyword(keyword).encrypt(msg)
elif cipher == "transposition":
e_msg = Transposition().encrypt(msg)
print(e_msg)
else:
if cipher == "caesar":
d_msg = Caesar().decrypt(msg)
elif cipher == "affine":
d_msg = Affine().decrypt(msg)
elif cipher == "keyword":
keyword = input("What is your keyword? ")
d_msg = Keyword(keyword).decrypt(msg)
elif cipher == "transposition":
d_msg = Transposition().decrypt(msg)
print(d_msg)
#only run when actually meant to run
if __name__ == "__main__":
run_cipher()
| true |
e734fac98baa22123aa56354e547b7c3034de51d | JingGH/Hello-Python3 | /ex33.py | 879 | 4.1875 | 4 | i = 0
numbers = []
while i < 6:
print(f"At the top i is {i}")
numbers.append(i)
i = i + 1
print("Numbers now: ",numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
# def
def my_while(loops): #step
i = 0
numbers = []
while i < loops:
print("At the top i is %d" %i)
numbers.append(i)
i += 1 #step
print("Numbers now:",numbers)
print("At the bottom is %d" %i)
print("\n--------------------------")
my_while(6)
print("The numbers:")
for num in numbers:
print(num)
#for & range
numbers = []
for i in range(6):
print(f"At the top i is {i}")
numbers.append(i)
print("Numbers now: ",numbers)
print(f"At the bottom i is {i}")
print("\n========================")
print("The numbers:")
for num in numbers:
print(num) | false |
aadeefbc217c0bf674c0810525c4d2d9bb46e7d4 | stccenter/book-reference-code | /4/code 4.13.py | 904 | 4.40625 | 4 | >>> import math
>>> class Point: ## define a point class
def __init__(self, x=0.0, y = 0.0):
self.x = x
self.y = y
def getDistance(self,other): ## declare getDistance as a method
return math.sqrt((other.x-self.x)**2+(other.y-self.y)**2)
#Declare three points
>>> p1,p2,p3 = Point(1,5), Point(2,8), Point(10,3)
## calculate the distances among random two points and keep them in a list
>>> dist1 = p1.getDistance(p2)
>>> dist2 = p1.getDistance(p3)
>>> dist3 = p2.getDistance(p3)
>>> distances = [dist1,dist2,dist3]
##Declare the biggestDistance variable
>>> biggestDistance = 0.0
>>> for i in range(len(distances)):
currentDistance = distances[i]
if currentDistance > biggestDistance:
biggestDistance = currentDistance
## Finish finding and print
>>> print('biggest distance is ->', biggestDistance)
biggest distance is -> 9.43398113206
>>>
| true |
f9cbc80bbf735083fa8d853d7228f65e556bb66e | safetydank/astar-strategy | /grid.py | 2,521 | 4.1875 | 4 | # Define a grid map
#
# A map is a square grid of faces.
#
# See http://www-cs-students.stanford.edu/~amitp/game-programming/grids/ for
# addressing scheme
class Face(object):
def __init__(self, (u, v)):
self.u = u
self.v = v
# edge orientation can be WEST or SOUTH from a vertex
W = 0
S = 1
class Edge(object):
def __init__(self, (u, v, o)):
"""An edge is defined by u,v co-ordinates and o orientation (S|w)"""
self.u = u
self.v = v
self.o = o
class Vertex(object):
def __init__(self, (u, v)):
"""A vertex is defined by u,v co-ordinates"""
self.u = u
self.v = v
def neighbours((u,v)):
"""Return neighbouring face co-ordinates of a given face"""
return ((u,v+1), (u+1,v), (u,v-1), (u-1,v))
def neighbours2((u,v)):
"""Return neighbouring face co-ordinates of a given face, including
diagonals"""
return ((u-1, v+1), (u,v+1), (u+1,v+1),
(u-1,v), (u+1,v),
(u-1,v-1), (u,v-1), (u+1,v-1))
def borders((u,v)):
"""Return border edge co-ords of a face"""
return ((u,v+1,S), (u+1,v,W), (u,v,S), (u,v,W))
def corners((u,v)):
"""Return corner vertex coords of a face"""
return ((u+1,v+1), (u+1,v), (u,v), (u,v+1))
def joins((u,v,o)):
"""Return adjoining faces of an edge"""
return { W : ((u,v), (u-1,v)),
S : ((u,v), (u,v-1)) }[o]
def continues((u,v,o)):
"""Return continuing edges of an edge"""
return { W : ((u,v+1,W), (u,v-1,W)),
S : ((u+1,v,S), (u-1,v,S)) }[o]
def endpoints((u,v,o)):
"""Return endpoint vertices of an edge"""
return { W : ((u,v+1), (u,v)),
S : ((u+1,v), (u,v)) }[o]
def touches((u,v)):
"""Return faces touching a given vertex"""
return ((u,v), (u,v-1), (u-1,v-1), (u-1,v))
def protrudes((u,v)):
"""Return edges protruding (like a +) about a given vertex"""
return ((u,v,W), (u,v,S), (u,v-1,W), (u-1,v,S))
def adjacent((u,v)):
"""Return adjacent vertices to a given vertex"""
return ((u,v+1), (u+1,v), (u,v-1), (u-1,v))
class Grid(object):
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.faces = {}
for i in range(cols):
for j in range(rows):
self.faces[(i,j)] = Face(i,j)
# Items are accessed as Map[(u,v)]
def __getitem__(self, key):
return self.faces[key]
| false |
5a3d106098406983e01116edded6443740bb92fd | Yue1Harriet1/GA-Data-Science | /Lab_20140910_Matrices.py | 921 | 4.21875 | 4 | #Lab: Matrices in Python
#1. vectorMatrix multiplication funtion
def vectorMatrixMultiplication(matrix,vector):
mvResult = [0]*len(matrix)
for i in range(len(matrix)):
for j in range(len(vector)):
mvResult[j] += matrix[i][j] * vector[j]
print '\n', "Matrix x Vector:"
print mvResult
matrix = [ [1,2,3],
[4,5,6],
[7,8,9] ]
vector = [1,2,3]
vectorMatrixMultiplication(matrix,vector)
#2. matrixMultiplication function
def matrixMultiplication(matrix1,matrix2):
mmResult = [[0 for col in range(len(matrix2[0]))] for row in range(len(matrix1))]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
mmResult[i][j] += matrix1[i][k] * matrix2[k][j]
print '\n', "Matrix1 x Matrix2:"
for r in mmResult:
print(r)
matrix1 = [ [1,2,3],
[4,5,6],
[7,8,9] ]
matrix2 = [ [1,2,1,2],
[3,4,3,4],
[5,6,5,6] ]
matrixMultiplication(matrix1,matrix2) | false |
a031042dd00ac0ee6d47c7209d395f13a9eb2661 | ApinyaMiew/workshop2.1 | /list/sort_list.py | 304 | 4.15625 | 4 | # EXAMPLE 1
thislist = [100, 50, 65, 82, 23]
thislist.sort() # น้อยไปมาก
print(thislist) # Output: [ 23, 50, 65, 82, 100]
# EXAMPLE 2
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse=True) # มากไปน้อย
print(thislist) # Output: [ 100, 82, 65, 50, 23] | false |
d6075cd39762e70f1257a3069899ef4afd13c9fb | dongheelee1/LeetCode | /617_mergeTrees.py | 1,360 | 4.28125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
617_mergeTrees
Time Complexity: O(n) where n is min number of nodes from the two given trees (you only go into the recursive case when t1 and t2 exists)
Space Complexity: O(n) --> worst case is when the tree is skewed (each node has one child); O(logn) --> average case, depth will be O(logn)
'''
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
'''
#Consider 4 cases
#t1 is None and t2 is None
#t1 exists and t2 exists
#t1 is None and t2 exists
#t1 exists and t2 is None
'''
if t1 is None and t2 is None:
return None
if t1 and t2 is None:
return t1
if t1 is None and t2:
return t2
if t1 and t2:
#sum the values of two nodes
t1.val = t1.val + t2.val
#preorder traversal: left -> right -> root
#bottom-up setting of left and right children
#will return 3 (the 1st node of newly updated t1) last
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
| true |
52d5604984ab431dd0bdf4455cd33faa53083532 | dongheelee1/LeetCode | /771_Jewels_and_Stones.py | 1,357 | 4.125 | 4 | '''
771. Jewels and Stones
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
'''
import collections
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
'''
TIME COMPLEXITY - O(n*m) given that n is length of J and m is length of string S
IDEA:
-create a frequency dictionary of the string S
-for each char in J, add count corresponding to the char to sum
l = collections.Counter(S)
sum = 0
for char in J:
if char in l:
sum += l[char]
return sum
'''
k = [s in J for s in S] #for each char in S (string), is the char a jewel?
return(sum(k))
#return sum
| true |
158abbfacb434f4497958f170a53b5f76a7b3a01 | AgnieszkaUcinska/Nordea | /collatz.py | 327 | 4.21875 | 4 | def collatz(number):
print(number)
if number==1:
return
elif number % 2:
return collatz(number * 3 + 1)
else:
return collatz (number // 2)
if __name__== '__main__':
number=int(input('Give a number: '))
print (f'Collatz sequence for number {number} is: ')
collatz(number)
| false |
e2f3d2903e93d03d8ad86068fd02b916620e3d1a | zanekoch/Interview-Practice | /leetCode/Validate_Binary_Search_Tree.py | 1,671 | 4.3125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
'''
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
[10,5,15,null,null,6,20]
10
5 15
6 20
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
#idea is to use a recursive algorithm to look at all nodes
#I think you can use either depth first or breadth first search bc you are guarenteed to hit all nodes either way
#ok lets do depth first cause I feel like it, what do we need to check at each node?
#check if its left left child is less than it and if so recursively call fxn on left, if false return false. same with right but >
#will this guarentee it is also a BST? no can have a "zig zag" => keep upper and lower bounds
#how to make sure it makes it all the way
def isValidBST(self, root) -> bool:
def recursor(node, lower, upper):
if not node:
return True
if node.val <= lower or node.val >= upper:
return False
if not recursor(node.left, lower, node.val):
return False
if not recursor(node.right, node.val, upper):
return False
return True
return recursor(root, float("-inf"), float("inf"))
| true |
f801c9efec5004363864613e278bddb089e8edf5 | melissaarliss/python-course | /hw/hw-4/rps.py | 1,271 | 4.21875 | 4 | import random
choices = ["rock", "paper", "scissors"]
def game_time():
player_choice = input("Make your choice: rock, paper, or scissors. ").lower().strip()
while player_choice not in choices:
player_choice = input("Try again: the choices are rock, paper, or scissors. ").lower().strip()
print(f"Your choice is {player_choice}.")
computer_choice = random.choice(choices)
print(f"The computer's choice is {computer_choice}.")
player_score = 0
computer_score = 0
if player_choice == computer_choice:
print("It's a tie!")
elif player_choice == "rock":
if computer_choice == "paper":
print("The computer won.")
computer_score += 1
else:
print("You won!")
player_score += 1
elif player_choice == "paper":
if computer_choice == "scissors":
print("The computer won.")
computer_score += 1
else:
print("You won!")
player_score += 1
elif player_choice == "scissors":
if computer_choice == "rock":
print("The computer won.")
computer_score += 1
else:
print("You won!")
player_score += 1
print(f"You have {player_score} points and the computer has {computer_score} points.")
if input(("Want to play again? Enter yes or no. ")).lower().strip() == "yes":
game_time()
else:
print("Goodbye!")
game_time()
| true |
ad8cc659e40afc5f186ad4eb13e98d633e8a7d1b | EliPreston/Contests | /DWITE Problems/DWITE_hourClock.py | 292 | 4.125 | 4 |
def convertTime(time):
h = time[0:2]
h = int(h)
m = time[3:5]
# m = int(m)
# Assume time is AM
x = "AM"
if (12 <= h <= 23):
x = "PM"
h = h - 12
print(str(h)+":"+str(m)+" "+x)
for i in range(0, 3, 1):
t = input()
convertTime(t)
| false |
7e125d62d57f150803277b135ed82e9519fd461a | TarunDabhi27/LearningPython | /05-modules/module02-builtins-data-structures/list/AddingAndDeletingElements.py | 638 | 4.25 | 4 | if __name__ == '__main__':
list_one = [1,2,3,4]
list_two = [6,7]
# Appending elements
list_one.append(5)
print(list_one)
list_one.extend(list_two)
print(list_one)
# Deleting Elements
list_three = [1,2,3,4]
del(list_three[0])
del (list_three[0:1])
print(list_three)
# remove : Used to delete specific element
list_three.remove(3)
print(list_three)
# Using pop() to Delete elements
list_four = [1, 3, 5, 7]
print(list_four.pop(1))
# Delete last element
print(list_four.pop())
# Clearing all elements
print(list_four.clear()) # Similar to del L[:]
| true |
7e6b9ea4467f3f66116bd0c42956c61dd01e9359 | bpPrg/TIL | /aug16/python_class.py | 1,321 | 4.3125 | 4 | #!python
# -*- coding: utf-8 -*-#
#
# Author : Bhishan Poudel; Physics Graduate Student, Ohio University
# Date : Aug 16, 2017 Wed
# Last update :
class Cat:
def __init__(self, name):
self.name = name
def meow(self):
print('Meow')
def __repr__(self):
return '<Cat object. Name: {0}>'.format(self.name)
class CatBox:
def __init__(self, size=3):
self.size = size
self.cats = []
def add_cat(self, cat):
if isinstance(cat, Cat):
if len(self.cats) <= self.size:
self.cats.append(cat)
else:
raise MemoryError('The box is full (it has {0} cats}.'.format(self.size))
else:
raise TypeError('Expected a Cat instance, got {0} instead'.format(type(cat)))
def __repr__(self):
return repr(self.cats)
def main():
"""Run main function."""
box = [Cat('Narancs'), Cat('Omlás'), Cat('Don Gatto'), Cat('Vörös Harry'), Cat('Félszemű Babylon')]
# for cat in box:
# print(cat)
my_box = CatBox()
my_box.add_cat(Cat('Narancs'))
my_box.add_cat(Cat('Omlás'))
my_box.add_cat(Cat('Don Gatto'))
print(my_box)
my_box.add_cat(Cat('Vörös Harry'))
# my_box.add_cat(Cat('Narancs')) # This gives error
if __name__ == "__main__":
main()
| false |
4bd2e14cb5948e7378a4f182457a4ab059256f24 | irfa89/LeetCode | /Practice/LL_insert.py | 1,844 | 4.3125 | 4 |
class Node:
def __init__(self,data):
self.data = data # Assigns data.
self.next = None # Initialize next as Null.
class linked_list:
def __init__(self):
self.head = None # Funtion to initialize linked List object.
# The function prints the content of linked list starting from head.
def prinList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def push(self,new_data):
# Allocates the new node and put in data
new_node = Node(new_data)
# Make the next of new node as head
new_node.next = self.head
# Move the head to point to new node
self.head = new_node
def insertAfter(self,prev_node,new_data):
#check if the given prev_node exists
if prev_node is None:
print("Does not exists")
return
# create new node and put in data
new_node = Node(new_data)
# Make next of new node as next of prev_node
new_node.next = prev_node.next
# make the next of prev_node as new_node
prev_node.next = new_node
def append(self,new_data):
# create a new node,put data,set next as none
new_node = Node(new_data)
# if the linked list is empty, then new_node as head.
if self.head is None:
self.head = new_node
return
# else traverse till last node
last = self.head
while(last.next):
last = last.next
# change the next of last node
last.next = new_node
def main():
ll = linked_list()
ll.head = Node(1)
n2 = Node(2)
n3 = Node(3) # Nodes created
ll.head.next = n2
n2.next = n3
ll.prinList()
if __name__ == "__main__":
main() | true |
c987c10fee4470403106f57e5efd9b463273a1b1 | irfa89/LeetCode | /Week-3/LRUCache.py | 1,737 | 4.25 | 4 | """
146. Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity,
it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
"""
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.cache = []
self.lookup = {}
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.lookup:
return -1
self.cache.remove(key)
self.cache.append(key)
return self.lookup[key]
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.lookup:
self.lookup[key] = value
self.cache.remove(key)
self.cache.append(key)
return
else:
if len(self.cache) == self.capacity:
delete = self.cache[0]
self.cache = self.cache[1:]
del self.lookup[delete]
self.cache.append(key)
self.lookup[key] = value
def main():
lru = LRUCache(2)
lru.put(1,1)
lru.put(2,2)
lru.get(2)
lru.put(4,4)
lru.get(3)
lru.get(3)
lru.get(4)
if __name__ == "__main__":
main() | true |
5d113a5b6cda0779be88bfca7614d76ea018666b | SDSS-Computing-Studies/004b-boolean-logical-operators-EliasNunes606 | /task3.py | 557 | 4.46875 | 4 | #! python3
"""
Ask the user to enter a number.
Tell them if the number is a positive integer
(2 points)
inputs:
a number of any type
outputs:
xx is a positive integer.
xx is not a positive integer
example:
Enter a number: -3
-3 is not a positive integer
Enter a number: 2.4
2.4 is not a positive integer
Enter a number: 5
5 is a positive integer
Enter a number: 4.0
4.0 is a positive integer
"""
x = float(input("Enter a number: "))
if x == int(x) and x>0:
print(f"{x} is a positive integer")
else:
print(f"{x} is not a positive integer") | true |
70ca89095ed457192d8926918e4c8a498c1a616d | kinsei/Learn-Python-The-Hard-Way | /ex3.py | 1,102 | 4.4375 | 4 | #this line prints out "I will now count my chickesn
print "I will now count my chickens:"
#these next two lines prints out how many hens and roosters you have and conducts the math to figure it out
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
#this line tells the user that it will now count the eggs
print "Now I will coount the eggs"
#this line has no strings to print out it strictly does the math and prints it out
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
#these next two lines asks a question and answers it
#it is preforming a boolean ie. true or false
print "Is ti true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
#this line askes a question and answers it
print "What is 3 + 2 ", 3 + 2
#this line asks a question and preformes the math to answer it
print "What is 5 - 7?", 5 - 7
s line simply makes a statement
print "Oh, thats why its false."
#this line makes a statement
print "how abut some more?"
#the last three lines shows greater than, equal to or less than
print "is it greater", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "is it less or equal?", 5 <= -2
| true |
e95a405c8561ddec8b0d5ba0f164d8bb9e1fd78a | TareqJudehGithub/flask_rest | /py_refresh/OOP/factories_class.py | 1,340 | 4.21875 | 4 | #factories_class.py
class Book:
TYPES = ("hardcover", "paperback")
def __init__(self, name, type, weight):
self.name = name.title()
self.type = type.capitalize()
self.weight = weight
def __repr__(self):
return f"<Book(Book title:{self.name}\nBook type:{self.type}\nBook weight: \
{self.weight}g.)>"
@classmethod
# adding 100 because hardcover weights heavier than paperback
def hardcover(cls, name, weight):
print("\n")
return cls(name, cls.TYPES[0], weight + 200)
@classmethod
def paperback(cls, name, weight):
print("\n")
return cls(name, cls.TYPES[1], weight + 200)
# accesssing Typles tuple inside class Book
Book.TYPES
# Creating an instance of Book class
book_1 = Book("harry potter", "hardcover", 1500)
# pass "harry potter" value as a param for name object, then it will be assigned
# to the name property of the self object (which is an empty container at this
# stage), and finally it will be printed using print(book_1.name)
print(book_1, end="\n")
# Now because we created a class method inside the class, we no longer need to
# create any new objects first, all we need to do now is call the class method
# we created:
book_hardcover = Book.hardcover("harry potter", 1700)
print(book_hardcover)
book_paperback = Book.paperback(" The hobbit", 700)
print(book_paperback)
| true |
be2e551f00088d495db3944f81fbe4c81b3e1a64 | patrickstleaton/patrickstleaton.github.io | /DiscreteMathematics/PropositionalLogic.py | 834 | 4.375 | 4 | #This program utilizes boolean and propositional logic to find the output of three input variables.
p = (str.upper(raw_input("Please enter truth-value of p: ")))
q = (str.upper(raw_input("Please enter truth-value of q: ")))
r = (str.upper(raw_input("Please enter truth-value of r: ")))
#Negation (not)
def neg(p):
if p == 'T':
return 'F'
else:
return 'T'
#Disjunction (or)
def dis(p,q):
if p or q == 'T':
return 'T'
else:
return 'F'
#Conjunction (and)
def con(p,q):
if p and q == 'T':
return 'T'
else:
return 'F'
#Implication (proposition)
def imp(p,q):
if p == 'T' and q == 'F':
return 'F'
else:
return 'T'
ans1 = con(imp(neg(p),q),imp(r,p))
ans2 = con(dis(neg(p),r),dis(q,neg(imp(r,p))))
print "\nTruth-value of statement 1 is:",ans1
print "Truth-value of statement 2 is:",ans2 | false |
80a9eadb06a294c5bdaa2d585bc843e333b35667 | HarrietLLowe/python_tip-calculator | /main.py | 675 | 4.21875 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
print("Welcome to the tip calculator.\n")
total_bill = float(input("What was the total bill? $"))
per = float(input("What percentage tip would you like to give? 10, 12, or 15? "))
percentage_1 = per / 100
percentage_2 = total_bill * percentage_1
bill_with_percent = total_bill + percentage_2
num_people = int(input("How many people to split the bill? "))
final_value = round(bill_with_percent / num_people, 2)
final_value = "{:.2f}".format(bill_with_percent)
print(f"Each person should pay: ${final_value}") | true |
9f3b4964d2b1f7c4d70f522c81c57f53cb995c12 | haydenwhitney/portfolio | /Credential Authorization/credential_check.py | 1,920 | 4.15625 | 4 | #Hayden Whitney
#10/18
#Credential Check
def check_account(username, password):
username = username
password = password
enter_username = input("Enter your username: ")
enter_password = input("Enter your password: ")
if username == enter_username and password == enter_password or enterusername == "admin":
print("Access Granted.")
return True
else:
print("Access Denied.")
check_account(username, password)
def get_password():
print("Your password must start with a capital letter, \n must contain at least 1 symbol, \n and must be at least 10 characters long.")
password = input("Enter your password: ")
if password.istitle() and not password.isalnum() and len(password) >= 10:
print("Your password is set.")
return password
else:
print("Your password didn't meet the requirements.")
get_password()
def get_username():
print("Usernames should only contain numbers and letters \n and no more than 20 characters.")
username = input("Enter your username: ")
if username.isalnum() and len(username) >= 3 and len(username) <= 20:
print("Your username is set.")
return username
else:
print("Your username didn't meet the requirements.")
get_username()
def menu():
choice = 0
while choice == 0:
print("To sign up: Press 1")
print("To sign in: Press 2")
choice = int(input("Enter your choice: "))
if choice == 1:
username = get_username()
password = get_password()
print(username, password)
choice = 0
elif choice == 2:
login = check_account(username, password)
return password, username, login
def main():
password, username, access = menu()
if access == True:
print("You're in!")
else:
print("That's incorrect.")
main()
| true |
7e3641e8001a35ab2a94dec7496174816b3077c8 | G00364778/46887_algorithms | /sort_code/02_selectionsort.py | 522 | 4.125 | 4 | # selection sort
def printArray(arr):
return (' '.join(str(i) for i in arr))
def selectionsort(arr):
N = len(arr)
for i in range(0, N):
small = arr[i]
pos = i
for j in range(i + 1, N):
if arr[j] < small:
small = arr[j]
pos = j
temp = arr[pos]
arr[pos] = arr[i]
arr[i] = temp
print ("After pass " + str(i) + " :", printArray(arr))
if __name__ == '__main__':
arr = [10, 7, 3, 1, 9, 7, 4, 3]
print ("Initial Array :", printArray(arr))
selectionsort(arr) | false |
ef4e4887cfd164b8d1ba0549f39ee3bce0e97ff3 | blueExcess/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/100-matrix_mul.py | 1,877 | 4.28125 | 4 | #!/usr/bin/python3
"""Function to multiply two matrices."""
def matrix_mul(m_a, m_b):
"""Multiply two matrices.
Args:
m_a: First matrix - must be a list of lists of ints or floats.
m_b: Second matrix - must be a list of lists of ints or floats.
Raises:
TypeError: raised if input is incorrect.
ValueError: raised if values of input is incorrect.
"""
recA = []
recB = []
if type(m_a) is not list:
raise TypeError('m_a must be a list')
if type(m_b) is not list:
raise TypeError('m_b must be a list')
for x in m_a:
recA.append(len(x))
if type(x) is not list:
raise TypeError('m_a must be a list of lists')
elif len(x) == 0:
raise ValueError("m_a can't be empty")
for x in m_b:
recB.append(len(x))
if type(x) is not list:
raise TypeError('m_b must be a list of lists')
elif len(x) == 0:
raise ValueError("m_b can't be empty")
if len(m_a) == 0:
raise ValueError("m_a can't be empty")
if len(m_b) == 0:
raise ValueError("m_b can't be empty")
for row in m_a:
for value in row:
if type(value) is not int or type(value) is not float:
raise TypeError('m_a should contain only integers or floats')
for row in m_b:
for value in row:
if type(value) is not int or type(value) is not float:
raise TypeError('m_b should contain only integers or floats')
if len(set(recA)) != 1:
raise TypeError("each row of m_a must should be of the same size")
if len(set(recB)) != 1:
raise TypeError("each row of m_b must should be of the same size")
if len(m_a) != len(m_b[0]) or len(m_a[0]) != len(m_b):
raise ValueError('m_a and m_b can't be multiplied')
for row in m_a:
| true |
c76e6d8d8c2a3bd586060060a33b34ad337021d9 | Feez/Algo-Challenges | /SlidingWindow/SmallestWindowContainingSubstr.py | 1,195 | 4.125 | 4 | # Smallest Window containing Substring (hard)
# https://www.educative.io/courses/grokking-the-coding-interview/3wDJAYG2pAR
#
# Given a string and a pattern, find the smallest substring in the given string
# which has all the characters of the given pattern.
import collections
def find_substring(chars, pattern):
windowStart = 0
pattern_counts = collections.defaultdict(int)
matched = 0
for pattern_char in pattern:
pattern_counts[pattern_char] += 1
min_length = len(chars) + 1
substr_start = 0
for windowEnd, char in enumerate(chars):
if char in pattern_counts:
pattern_counts[char] -= 1
if pattern_counts[char] >= 0:
matched += 1
while matched == len(pattern):
curr_window_len = (windowEnd - windowStart + 1)
if min_length > curr_window_len:
substr_start = windowStart
min_length = curr_window_len
left_char = chars[windowStart]
if left_char in pattern_counts:
if pattern_counts[left_char] == 0:
matched -= 1
pattern_counts[left_char] += 1
windowStart += 1
if min_length > len(chars):
return ""
return chars[substr_start : substr_start + min_length] | true |
b8f6b0f531011d4d20dd9b4e8552667b077b06b5 | DawnBee/01-Learning-Python-PY-Basics | /Decorator/Decorator-2.py | 1,293 | 4.28125 | 4 | # DECORATOR II
# PASSING ANY NUMBER OF POSITIONAL & KEYWORD ARGUMENTS
# TO OUR WRAPPER FUNCTION:
def decorator_function(original_function):
def wrapper_function(*args,**kwargs): #This will allow us to pass any number of keyword & positional arguments.
print('Wrapper executed this before {}'.format(original_function.__name__))
return original_function(*args,**kwargs) #You can of course name this whatever you want,
return wrapper_function #but in convention programmers use 'args' & 'kwargs'
@decorator_function #Decorator Syntax
def display_info(name,age):
print("Ran with arguments '({},{})' ".format(name,age))
display_info('John',25)
'''
Take Note:
* --> Positional Arguments
** --> Keyword Arguments
'''
# CLASSES AS DECORATORS:
class decorator_class(object):
def __init__(self,original_function):
self.original_function = original_function
#'__call__' method will mimic the functionality of our 'wrapper_function'.
def __call__(self,*args,**kwargs): #Will behave like the previous 'wrapper_function'
print('__call__ method executed this before {}'.format(self.original_function.__name__))
return self.original_function(*args,**kwargs)
@decorator_class
def display(name,age):
print('Ran with arguments [{}:{}]'.format(name,age))
display('Avril',39)
| true |
a59cc29abcbcbbd8edc8531ea20cb9f597740538 | DawnBee/01-Learning-Python-PY-Basics | /PY Practice problems/Guessing Game One.py | 1,252 | 4.375 | 4 | # GUESSING GAME ONE
'''
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to
guess the number, then tell them whether they guessed too low, too high, or exactly
right. (Hint: remember to use the user input lessons from the very first exercise)
Extras:
1. Keep the game going until the user types “exit”
2. Keep track of how many guesses the user has taken, and when the game ends, print this out.
'''
import random
def guess_game():
rand_num = random.randint(1,9)
guess = 0
guess_count = 0
while guess != rand_num and 'exit':
guess = input('Enter Guess: ')
guess_count += 1
if guess == 'exit':
print('Number of Guesses:',guess_count-1)
print('Thanks For Playing!')
break
guess = int(guess)
if guess < rand_num:
print('too low')
elif guess > rand_num:
print('too high')
else:
print('You Won!')
print('Number of Guesses:',guess_count)
print('====================')
guess_game()
guess_game()
'''
# SOLUTION 2:
guess_count = 0
while True:
ask_usr = int(input('Enter Guess: '))
guess_count += 1
if ask_usr < rand_num:
print('too low')
elif ask_usr > rand_num:
print('too high')
else:
print('You Won!')
print('Number of Guesses:',guess_count)
break
''' | true |
ad94b18a73b8a4367af2af4c23f06881ef67a901 | DawnBee/01-Learning-Python-PY-Basics | /OOP Projects & Exercises/Exercise-4.py | 608 | 4.125 | 4 | # OOP Exercise 4: Class Inheritance
# Create a Bus class that inherits from the Vehicle class. Give the capacity
# argument of Bus.seating_capacity() a default value of 50.
class Vehicle:
def __init__(self,name,max_speed,mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
def seating_capacity(self,capacity):
return f"The seating capacity of '{self.name}' is {capacity} passengers. "
class Bus(Vehicle):
def seating_capacity(self,capacity=50):
return super(). seating_capacity(capacity=50)
vehicle_1 = Bus('School Volvo',180,12)
print(vehicle_1.seating_capacity()) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.