blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
165662dd2df0759cb43172f690558cdd2b62e9cc | one-last-time/python | /Data Types and Operators/ArithmeticOperators.py | 665 | 4.1875 | 4 | #addtion,subtraction,multiplication,division,mod are same as other language
print(((1+2+3)*(4/2)-5)%3)
#power
#get 2^3
print(2**3)
#integer divison
#it rounds the result
print(8//3)
print(-8//3)
"""
Quiz: Calculate
In this quiz you're going to do some calculations for a tiler. Two parts of a floor need tiling. One part is 9 tiles wide by 7 tiles long, the other is 5 tiles wide by 7 tiles long. Tiles come in packages of 6.
1.How many tiles are needed?
2.You buy 17 packages of tiles containing 6 tiles each. How many tiles will be left over?
"""
#1
total=(7*9)+(7*5)
print("total tiles need=",total)
#2
print("tiles remain =",(6*17)%total)
| true |
46ca34ac7cff4689deb3f0acbede5503534c2ca6 | FinchyG/Python_testing_fridge_temperatures | /Testing_fridge_temperatures.py | 920 | 4.28125 | 4 | # Test whether fridge temperatures are between 1 and 5 degrees Celsius
# function with one parameter, temperatures: a list of numbers
def test_temperature(temperatures):
# initialise empty list to store temperatures outside of range 1 to 5
unacceptable_temperatures = []
# iterate through input list
for temperature in range(len(temperatures)):
# filter unacceptable temperatures outside of range 1 to 5
if temperatures[temperature] < 1 or temperatures[temperature] > 5:
# append temperature to list of unacceptable temperatures
unacceptable_temperatures.append(temperatures[temperature])
# output list of unacceptable temperatures
print(unacceptable_temperatures)
# check that test_temperatues works
def check_test_temperatures():
assert test_temperatures([1,2,3,4,5]) == []
assert test_temperatures([-1,2,4,6]) == [-1,6]
| true |
b9dac96e603a2af6b4db973904175d7e808dc9c8 | DeepankJain/Python-Programs | /Prog3.py | 238 | 4.3125 | 4 | #To check whether a number is postive, negative or Zero
num1 = int(input("Enter any number:"))
if num1 > 0:
print("Number is positive")
elif num1 == 0:
print("Number entered is Zero")
else:
print("Number is negative")
| true |
42838d219ffd6d447c796649fe4cc9579a1348d4 | raezir/The-Hoodrat-Repository | /test1.py | 551 | 4.125 | 4 | #!/usr/bin/env python
#import sys
'''
Created on Jan 28, 2017
This code opens a text file and reads it, saving it to line and then printing it.
@author: rkbergsma
'''
f = open('Article1.txt','r') #open to read
line = f.readlines() #reads all lines in file
#line = [x.strip() for x in line] #strip gets rid of newline characters
#print(line) #prints as list with bad formatting
print(*line, end='\n') #print the text only in a list, can replace '\n' with ' '
f.close()
| true |
08f6f7b1c7fa5c063ce5be8f1d8e7213ac9c7b01 | Melwyn12/Python-Projects | /simpleAdditionQuiz.py | 2,166 | 4.125 | 4 | # Math game quiz
# prompts users to answer simple addition problems using random numbers from 0-100
# added subtraction, multiplication, and division
def printBanner():
print("\t\t\t ##################### ")
print("\t\t\t Math Quiz ")
print("\t\t\t By Falconscrest123 ")
print("\t\t\t #####################\n\n\n")
def calculateAverage():
sum = num1 + num2
return sum
def calculateDiffernce():
difference = num1 - num2
return difference
def multiplyNumber():
product = num1 * num2
return product
def divideNumber():
divide = float(num1 / num2)
divide = round(divide, 2)
return divide
import random
printBanner()
counter = 0
while True:
num1 = random.randrange(0,100)
num2 = random.randrange(0,100)
quizType = input("Do you want to add,subtract,multiply or divide:")
quizType = quizType.lower()
if quizType == "add" or quizType == "addition":
answer = calculateAverage()
userInput = input("What is the answer to %i + %i or press (done) to quit:" %(num1,num2))
userInput = userInput.lower()
elif quizType == "subtract" or quizType == "subtraction":
answer = calculateDiffernce()
userInput = input("What is the answer to %i - %i or press (done) to quit:" %(num1,num2))
userInput = userInput.lower()
elif quizType == "multiply" or quizType == "multiplication":
answer = multiplyNumber()
userInput = input("What is the answer to %i * %i or press (done) to quit:" %(num1,num2))
userInput = userInput.lower()
elif quizType == "divide" or quizType == "division":
answer = divideNumber()
userInput = input("What is the answer to %i / %i or press (done) to quit:" %(num1,num2))
userInput = userInput.lower()
else:
print("Invalid input")
continue
if userInput == "done":
print("Good-Bye")
break
try:
userInput = float(userInput)
except:
userInput = input("Bad input Please enter an integer only:")
if userInput == answer:
counter += 1
print("\nThe answer is %4.2f" %(answer))
print("Good Job! Your score is %i\n" %(counter))
elif userInput != answer:
print("Wrong Answer You got 0 points for this question")
print("The right answer is %4.2f" %(answer)
| true |
4c73f3903714e956a47065cfb51c2438159bcfa9 | teosss/HomeWorkPyCore | /lesson_8/task_1.py | 938 | 4.25 | 4 | import super_module_t1
def input_area(value):
""""
This function determines the type of figure
Input:
value(str)
Result:
(int,float)
""""
if value is '1':
s = int(input("Enter first side: "))
b = int(input("Enter second side: "))
return super_module_t1.rectangle_area(s,b)
elif value is '2':
s = int(input("Enter the base of the triangle: "))
h = int(input("Enter the height of the triangle: "))
return super_module_t1.triangle_area(s,h)
elif value is '3':
r = int(input("Enter radius of circle: "))
return super_module_t1.circle_area(r)
else:
value = input("You have entered incorrect data, please try again (1,2,3): ")
return input_area(value)
value = input("The area of which figure you want to count: \n 1 - rectangle \n 2 - triangle \n 3 - circle \n Enter number: ")
print(input_area(value)) | true |
dae37bc59b17b2e7e9b6118b19a3bcac1fadc43b | Panic-point1/Algorithmia | /python/binary_search.py | 857 | 4.25 | 4 | '''
In binary search,
- Compare x with the middle element.
- If x matches with the middle element, we return the mid index.
- Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray after the mid element.
Then we apply the algorithm again for the right half.
- Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the left half.
'''
def binary(a,f,l,x):
if l >= f:
m = (l+f) // 2
if a[m] == x:
return m
elif a[m] > x:
return binary(a,m+1,l,x)
else:
return binary(a,m+1,l,x)
else:
return -1
a = [560,50000,55773,88883,672728]
x = int(input("Enter the number you want to search:-"))
result = binary(a,0,len(a)-1,x)
if result != -1:
print("Element is present at "+str(result)+"th index")
else:
print("Sorry! element is not present") | true |
57ba2c2cfe3ab44fc716e148322c16268f2204a3 | JessicaJang/cracking | /Chapter 3/q_3_5.py | 1,185 | 4.15625 | 4 | # Chapter 3 Stacks and Queues
# 3.5 Sort Stack
# Write a program to sort a stack such that the smallest items are on the top
# You can use an additiona temporary stack, but you may not copy the elements
# into any other data structure (such as an array). The stack supports
# the following operations: push, pop, peek and isEmpty
import os
from stack import Stack
class sortStack:
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def push(self, item):
flag = True
while not self.stack2.isEmpty():
tmp = self.stack2.pop()
if tmp >= item:
self.stack1.push(item)
self.stack1.push(tmp)
flag = False
else: self.stack1.push(tmp)
if flag == True:
self.stack1.push(item)
while not self.stack1.isEmpty():
self.stack2.push(self.stack1.pop())
def pop(self):
if self.stack2.isEmpty():
return
return self.stack2.pop()
def isEmpty(self):
return self.stack2.isEmpty()
def peek(self):
if self.stack2.isEmpty():
return
return self.stack2.peek()
if __name__=="__main__":
print("test")
sstack = sortStack()
sstack.push(3)
sstack.push(2)
sstack.push(5)
sstack.push(1)
print(sstack.pop())
print(sstack.peek()) | true |
0e447a93b2db7926b93b73bad2ea46111e7a493e | JessicaJang/cracking | /Chapter 2/q_2_3.py | 453 | 4.28125 | 4 | # Chapter 2 Linked Lists
# Interview Questions 2.3
# Delete middle node:
# Implement an algorithm to delete a node in the middle
import os
from LinkedList import LinkedList
from LinkedList import LinkedListNode
def delete_middle_node(node):
node.value = node.next.value
node.next = node.next.next
ll = LinkedList()
ll.add_multiple([1, 2, 3, 4])
middle_node = ll.add(5)
ll.add_multiple([7, 8, 9])
print(ll)
delete_middle_node(middle_node)
print(ll) | true |
9baa2091eff6073b7f0642899a0ee3f07fbf96c0 | Cosmo767/Practice | /Udemy_Python_refresher/review_2_getting_input.py | 304 | 4.1875 | 4 | # name = input("Enter your name: ")
# print(name)
# input gives you a string, not a number
size_input = input("How big your house in sq feet?:" )
square_feet = int(size_input)
sqr_meters = square_feet /10.8
string = f"{square_feet} square feet is equal to {sqr_meters:.2f} square meters"
print(string) | true |
1114f176bb5c3b78c22c54aad4c61f258b5a1579 | Cosmo767/Practice | /jason_algos_one/most_common_letter.py | 1,906 | 4.25 | 4 | def most_common_letter(text):
"""Returns the letter of the alphabet that occurs most frequently. If there is a tie, choose the letter that comes first in the alphabet.
If there are no letters, return the empty string"""
'''
create a dictionary with a value for each key that counts how many time
the letter appears.
keep track of the max value and the respective key as we iterate over the string.
return the letter at the end.
'''
lower_case_text = text.lower()
my_dict = {}
current_largest = ""
my_dict[current_largest] = 0
for char in lower_case_text:
if char >= "a" and char <= "z": #the char is a letter
if char in my_dict: #the letter is already in the dict
my_dict[char] += 1
else: #the letter is not in the dict
my_dict[char] = 1
if (my_dict.get(char) > my_dict.get(current_largest)):
current_largest = char
elif (my_dict.get(char) == my_dict.get(current_largest)):
current_largest = current_largest if char > current_largest else char #ternary expression
# print(current_largest, "Current Largest")
# print(my_dict, "my dict")
return current_largest
'''
test cases
input expected vs output
'''
def test(my_input, expected_output):
actual_output = most_common_letter(my_input)
successful_test = actual_output == expected_output
success_notification = "PASS" if successful_test else "FAIL"
output_message = ("{}: \n INPUT: {}\n OUTPUT: \n\t expected: {} \n\t actual: {}".
format(success_notification, my_input, expected_output, actual_output))
print(output_message)
# test("aab", "a")
# test("beta", "a" )
# test("", "")
#test("5,2,3,3,3","") #21
# test("2,2,2z", "z") #21
# test("TaeaTt","t")
test("ABCabc","a")
| true |
0d4a3ed33566dd1980674c2ad18336f3c3b6b597 | Cosmo767/Practice | /Udemy_Python_refresher/33_unpacking_args.py | 748 | 4.28125 | 4 |
def add(*args):
total = 0
for arg in args:
total = total + arg
return total
def mutliphy(*args):
# print(args)
total = 1
for arg in args:
total = total*arg
return total
# print(mutliphy(1,3,5))
def apply(*args, operator): # creates a named operator at the end, must pass in a named arg at end
if operator == "*":
return mutliphy(*args)
elif operator == "+":
return add(*args)
else:
return "No valid operator"
print(apply(1,3,5,2,operator="+"))
#########################
# def add(x,t):
# return x+t
# nums = [3,5]
# print(add(*nums))
# # or
# nums ={"x":15, "t": 25}
# print(add(x=nums["x"], t=nums["t"]))
# # same as this
# print(add(**nums))
| true |
0906b7cc9dda5c140134c5a68fde84daa6453166 | 100sun/python_programming | /chp5_ex.py | 1,340 | 4.28125 | 4 | # 5.1 Capitalize the word starting with m:
song = """ When an eel grabs your arm, ... And it causes great harm, ... That's - a moray!"""
song = song.replace('m', ' M')
print(song)
# 5.2 Print each list question with its correctly matching answer in the form: Q: question A: answer > > >
questions = [
"We don't serve strings around here. Are you a string?",
"What is said on Father's Day in the forest?",
"What makes the sound 'Sis! Boom! Bah!'?"
]
answers = [
"An exploding sheep.",
"No, I'm a frayed knot.",
"' Pop!' goes the weasel."
]
for i in range(0, 3):
print(f'Q: {questions[i]}\nA: {answers[i]}')
# 5.3 Write the following poem by using old-style formatting. Substitute the strings 'roast beef', 'ham', 'head', and 'clam' into this string:
poem = '''My kitty cat likes %s, My kitty cat likes %s, My kitty cat fell on his %s And now thinks he's a %s'''
args = ('roast beef', 'ham', 'head', 'claim')
print(poem % args) # ∵ must be immutable values.. -> set
names = ['duck', 'gourd', 'spitz']
# 5.6 old style
for name in names:
print("%sy Mc%sface" % (name.capitalize(), name.capitalize()))
# 5.7 new style
for name in names:
print("{}y Mc{}face".format(name.capitalize(), name.capitalize()))
# 5.8 newest tysle
for name in names:
print(f"{name.capitalize()}y Mc{name.capitalize()}face")
| true |
e5eccbc671e5225f8da0c3dbf9666ef6b81ec8c2 | tomasvalda/dt211-3-cloud | /Euler/solution7.py | 616 | 4.21875 | 4 | #!/usr/bin/python
def is_prime(num): # function for check if the number is prime, returns true or false
if num == 2:
return true
if num < 2:
return false
if not num & 1:
return false
# for x in range # number is prime when we can divide it only by the exact number or 1
#################
return true
def main():
isprime = true # prime check
number = 1
prime_count = 1 # primes count
while isprime == true:
if is_prime(number):
prime_count = prime_count + 1
if prime_count == 10001: # 10001st prime number
print number
isprime = false
number = number + 2 # next prime number
| true |
4189cbe031375dd974083eb6e006b04852b29392 | Snehal2605/Technical-Interview-Preparation | /ProblemSolving/450DSA/Python/src/string/MinimumSwapsForBracketBalancing.py | 1,674 | 4.3125 | 4 | """
@author Anirudh Sharma
You are given a string S of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets.
A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2
are balanced strings.
We can make an unbalanced string balanced by swapping adjacent characters.
Calculate the minimum number of swaps necessary to make a string balanced.
Note - Strings S1 and S2 can be empty.
"""
def minimumNumberOfSwaps(S):
# Number of swaps required
swaps = 0
# Special case
if S is None or len(S) == 0:
return swaps
# Variable to track open brackets
openBrackets = 0
# Loop through the string
for c in S:
# If we encounter the left bracket,
# we will increment the count
if c == '[':
openBrackets += 1
# If we encounter the right bracket,
# then any of the two conditions can
# happen
else:
# If there are open brackets to the
# left of the current bracket,
# close the last encountered open
# bracket
if openBrackets != 0:
openBrackets -= 1
# If not, we will have to perform
# swap
else:
swaps += 1
# Reset the count of open brackets
openBrackets = 1
# We will need n/2 inversions for extra open brackets
# to make the string balanced
return swaps + openBrackets // 2
if __name__ == "__main__":
S = "[]][]["
print(minimumNumberOfSwaps(S))
S = "[[][]]"
print(minimumNumberOfSwaps(S))
S = "][][]["
print(minimumNumberOfSwaps(S))
| true |
3ea12eeb1275db5ca2a730ad5cd55e8f9da5e755 | Snehal2605/Technical-Interview-Preparation | /ProblemSolving/450DSA/Python/src/binarytree/LevelOrderTraversal.py | 1,314 | 4.21875 | 4 | """
@author Anirudh Sharma
Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree.
Constraints:
1 <= Number of nodes<= 10^4
1 <= Data of a node <= 10^4
"""
def levelOrderTraversal(root):
# Special case
if root is None:
return None
# List to store the result
result = []
# Queue to store nodes of the tree
nodes = []
# Add root node to the queue
nodes.append(root)
# Loop until the queue is empty
while nodes:
# Get the current node
current = nodes.pop(0)
# Add this node to the result
result.append(current.data)
# Check if the left child exists
if current.left:
nodes.append(current.left)
# Check if the right child exists
if current.right:
nodes.append(current.right)
return result
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
if __name__ == "__main__":
root = Node(1)
root.left = Node(3)
root.right = Node(2)
print(levelOrderTraversal(root))
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(60)
print(levelOrderTraversal(root))
| true |
355c5ba49e9a5ee0d5862f1155800456b10fdb6c | Snehal2605/Technical-Interview-Preparation | /ProblemSolving/450DSA/Python/src/dynamicprogramming/MobileNumericKeypad.py | 1,471 | 4.28125 | 4 | """
@author Anirudh Sharma
Given the mobile numeric keypad. You can only press buttons that are up, left, right, or down to
the current button.
You are not allowed to press bottom row corner buttons (i.e.and # ).
Given a number N, the task is to find out the number of possible numbers of the given length.
"""
def getCount(N):
# Array to store the allowed keys which can
# be pressed before a certain key
allowedKeys = [
[0, 8],
[1, 2, 4],
[1, 2, 3, 5],
[2, 3, 6],
[1, 4, 5, 7],
[2, 4, 5, 6, 8],
[3, 5, 6, 9],
[4, 7, 8],
[5, 7, 8, 9, 0],
[6, 8, 9]
]
# Lookup table to store the total number of
# combinations where i represents the total
# number of pressed keys and j represents the
# actual keys present
lookup = [[0 for y in range(10)] for x in range(N + 1)]
# Populate the table
for i in range(1, N + 1):
for j in range(10):
if i == 1:
lookup[i][j] = 1
else:
# Loop for all the allowed previous keys
for previous in allowedKeys[j]:
lookup[i][j] += lookup[i - 1][previous]
# Total sum
totalSum = 0
for value in lookup[N]:
totalSum += value
return totalSum
if __name__ == "__main__":
print(getCount(1))
print(getCount(2))
print(getCount(3))
print(getCount(4))
print(getCount(5))
print(getCount(16))
| true |
a0faf6dc0aaddd8e0cfbf57ff9ed2a53b47a380c | Snehal2605/Technical-Interview-Preparation | /ProblemSolving/450DSA/Python/src/dynamicprogramming/LongestIncreasingSubsequence.py | 1,346 | 4.125 | 4 | """
@author Anirudh Sharma
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements
without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence
of the array [0,3,1,6,2,2,7].
Constraints:
1 <= nums.length <= 2500
-10^4 <= nums[i] <= 10^4
"""
def lengthOfLIS(nums):
# Special case
if nums is None or len(nums) == 0:
return 0
# Length of the array
n = len(nums)
# Lookup table to store the longest increasing
# subsequence until a certain index.
# lookup[i] => length of longest increasing sub
# -sequence endding at index i
# Since every element is an increasing sequence of
# length 1.
lookup = [1] * n
# Loop through the array
for i in range(n):
for j in range(i):
if nums[i] > nums[j] and lookup[i] < lookup[j] + 1:
lookup[i] = lookup[j] + 1
# Find the maximum value in the lookup table
longest = 0
for x in lookup:
longest = max(longest, x)
return longest
if __name__ == "__main__":
nums = [10,9,2,5,3,7,101,18]
print(lengthOfLIS(nums))
nums = [0,1,0,3,2,3]
print(lengthOfLIS(nums))
nums = [7,7,7,7,7,7,7]
print(lengthOfLIS(nums)) | true |
e7d9e7d85e9e3912415fb2947c392157ab7414e3 | mdcowan/SSL | /Lecture_Files/Wk1_2/python.py | 722 | 4.375 | 4 | # To get user input, you must first import system functionality
import sys
# You can then use 'raw user input' to get data from the user
name = raw_input("What is your name?")
# From there you can use the variable with the user input data
# Writing to a file
# a = append, w = overwrite
# Template to open a file to write: declaredVariable = ("nameOfFile", "aOrW")
# Step one - open the file
f = open("myfile.txt","w")
# Step two - write data
f.write("Here is my text " + name + ".")
# Step three - close the file
f.close()
# Reading from a file
# r = read
# Template to read from a file: declaredVariable = ("nameOfFile", "r")
f = open("myfile.txt","r")
# ouput what was read
print(f.read())
#close the name
f.close()
| true |
c6a687f92ae05d2411702febf255dd02ca34d561 | ishitach/AI-and-PyTorch | /Neural network using relu.py | 714 | 4.15625 | 4 | #Creating a neural network with 128,64 hidden layers and 10 output layers and ReLU activation
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
# Inputs to hidden layer linear transformation
self.hidden1 = nn.Linear(784, 128)
self.hidden2 = nn.Linear(128, 64)
# Output layer, 10 units - one for each digit
self.output = nn.Linear(64, 10)
def forward(self, x):
# Hidden layer with relu function
x = self.hidden1(x)
x= relu(x)
x = self.hidden2(x)
x= relu(x)
x = F.softmax(self.output(x), dim=1)
return x
model = Network()
model
| true |
0a61e216e7bbade2dd5090e75285384bc92159f3 | clagunag/Astr-119 | /HW_1_1.py | 489 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Cesar Laguna
Python 3.6.1
'''
import numpy as np
'''
# 1
Takes inputs (b, c) and provides output of A (area of a rectangle)
Rectangle = rec
'''
b = int(input('Base (rec) :')) #input allows for user to input their own data/ numbers
c = int(input('Height (rec) :'))
A_rec = b*c
print ('Area of Rectangle', A_rec)
'''
# 1
For area of a triangle
'''
h0 = int(input('Base (tri) :'))
B = int(input('Height (tri) :'))
A_tri = 0.5*h0*B
print ('Area of Triangle', A_tri)
| true |
b84e10fbca2bba78cad0cd936f4902e5cd06af8d | Data-Winnower/Python-Class-Projects | /Turtle Star Drawing.py | 2,866 | 4.40625 | 4 | # Kale Perry
# Programming Concepts and Applications
# CSC1570-4914 Fall 2020
# 01 October 2020
# Repeating Turtle
# Repeating Turtle
# Repeating Turtle
# Did I remember to say, Repeating Turtle?
import turtle
turtle.speed(5)
again = "Yes"
print ("LET'S DRAW A STAR!")
while again =="Yes" or again == "Y" or again == "yes" or again =="y":
points = int(input("How many points would you like on your star? Pick 5 - 30: "))
print ("")
if points >=5 and points <= 30:
print ("OK, a ",points,"-pointed star it is.")
else:
print ("What part of pick a number from 5 to 30 did you not understand?")
# Set the turning angle for each possible point count
if points == 5:
angle = 36
elif points==7:
angle = 180/7
elif points == 8:
angle = 45
elif points == 9:
angle = 20
elif points == 10:
angle = 72
elif points == 11:
angle = 180/11
elif points == 12:
angle = 30
elif points ==13:
angle = 180/13
elif points == 14:
angle = 540/10.5
elif points == 15:
angle = 12
elif points == 16:
angle = 22.5
elif points == 17:
angle=180/17
elif points == 18:
angle = 40
elif points == 19:
angle = 180/19
elif points == 20:
angle = 18
elif points == 21:
angle = 180/21
elif points == 22:
angle = 360/11
elif points == 23:
angle = 180/23
elif points == 24:
angle = 15
elif points == 25:
angle = 7.2
elif points == 26:
angle = 90-(180/26)
elif points == 27:
angle = 180/27
elif points == 28:
angle = 540/14
elif points == 29:
angle = 180/29
elif points == 30:
angle = 24
# I could keep going and add as many more
# as I feel like figuring out the angle for
turtle.clear()
if points >=5 and points <= 30 and points!=6:
for x in range (points):
turtle.pencolor("magenta")
turtle.forward(250)
turtle.left(angle+180)
elif points == 6:
for x in range (6):
turtle.pencolor("blue")
turtle.forward(80)
turtle.right (60)
turtle.forward (80)
turtle.left(120)
again = input("Would you like to draw another?")
# Don't judge me - this was fun for me!
# Figuring out the angles was quite the challenge.
# And yeah, I cheated a little by not making all of them
# really pointy -
# compare 25 points to 26 points.
# Once I got it to work -
# Pointy or not, I called it good!
# And I had to go a whole other route
# to make a 6 pointed star.
# But, hey.....geometry wasn't the point
# of the assignment.
| true |
0276d2004f3ec6f8ac3fa40257e53460485caf46 | RaspiKidd/PythonByExample | /Challenge44.py | 542 | 4.28125 | 4 | # Python By Example Book
# Challenge 044 - Ask how many people the user wants to invite to a party. If they enter a number below 10.
# ask for the names and after each name display "(name) has to be invited to the party". If they enter a number which is
# 10 or higher display the message "Too many people".
invite = int(input("How many people are coming to the party? "))
if invite < 10:
for i in range (0, invite):
name = input("what is their name? ")
print(name, "has been invited")
else:
print("Too many people") | true |
75ba36c9c802dfbdb8f96e10a7a417a6f99c338e | RaspiKidd/PythonByExample | /Challenge72.py | 448 | 4.5 | 4 | # Python By Example Book
# Challenge 072 - Create a list of six school subjects. Ask the user which of these subjects they
# don't like. Delete the subject they have chosen from the list before you display the list again.
subjects = ["maths", "english", "p.e", "computing", "science", "history"]
print (subjects)
print ()
dislike = input("Which subject do you not like? ")
delete = subjects.index(dislike)
del subjects [delete]
print (subjects) | true |
4a139d8ec093a78e7f7dad5bc47fbd67c4edc808 | RaspiKidd/PythonByExample | /Challenge92.py | 615 | 4.28125 | 4 | # Python By Example Book
# Challenge 092 - Create two arrays (one containing three numbers that the user enters and
# one containing a set of five random numbers). Join these two arrays together into one large array.
# Sort this large array and display it so that each number appears on a seperate line.
from array import *
import random
num1 = array('i', [])
num2 = array('i', [])
for i in range (0,3):
num = int(input("Enter a number: "))
num1.append(num)
for y in range (0,5):
num = random.randint(1, 100)
num2.append(num)
num1.extend(num2)
num1 = sorted(num1)
for i in num1:
print (i) | true |
2113eeb68b5b660c78d568123082b411750f3a4a | RaspiKidd/PythonByExample | /Challenge54.py | 552 | 4.4375 | 4 | # Python By Example Book
# Challenge 054 - Randomly chose heads or tails ("h" or "t"). Ask the user to make their choice.
# If their choice is the same as the randomly selected value, display the message "You win",
# otherwise display "bad luck". At the end, tell the user if the computer selected heads or tails.
import random
coin = random.choice(["h", "t"])
guess = input("Enter (h)eads or (t)ails: ")
if guess == coin:
print ("You win")
else:
print ("Bad luck")
if coin == "h":
print ("It was heads")
else:
print ("It was tails") | true |
40c6fccf41c2424e1d787d59e3c42bf8724004d0 | RaspiKidd/PythonByExample | /Challenge87.py | 402 | 4.4375 | 4 | # Python By Example Book
# Challenge 087 - Ask the user to type in a word and then display it backwards on seperate lines.
# For instance, if they type in "Hello" it should display as shown below:
'''
Enter a word: Hello
o
l
l
e
H
'''
word = input("Enter a word: ")
length = len(word)
num = 1
for x in word:
position = length - num
letter = word[position]
print (letter)
num = num + 1 | true |
a4264a9c28edd71030c523ff9f18de6f01e76e38 | RaspiKidd/PythonByExample | /Challenge83.py | 462 | 4.375 | 4 | # Python By Example Book
# Challenge 083 - Ask the user to type a word in uppercase. If they type it in lowercase, ask them to try again.
# Keep repeating this until they type in a message all in uppercase.
msg = input("Enter a message in uppercase: ")
tryAgain = False
while tryAgain == False:
if msg.isupper():
print ("thank you")
tryAgain = True
else:
print ("Try again")
msg = input("Enter a message in uppercase: ") | true |
ab858ab774b8f552cd18e61d31dae22f7d2de6b0 | RaspiKidd/PythonByExample | /Challenge17.py | 574 | 4.21875 | 4 | # Python By Example Book
# Challenge 017 - Ask the users age. If they are 18 or over , display the message "You can vote", if they are aged 17, display the
# message "You can learn to drive", if they are 16 , display the message "You can buy a lottery ticket", if they are under 16, display
# the message "You can go trick or treating".
age = int(input("How old are you? "))
if age >= 18:
print("You can vote")
elif age == 17:
print("You can learn to drive")
elif age == 16:
print("You can buy a lottery ticket")
else:
print("You can go trick or treating") | true |
663de86686531f0522892249b03b0169d46cdb62 | gomsvicky/PythonAssignmentCaseStudy1 | /Program13.py | 318 | 4.28125 | 4 | list1 = []
num = input("Enter number of elements in list: ")
num = int(num)
for i in range(1, num + 1):
ele = input("Enter elements: ")
list1.append(ele)
print("Entered elements ", list1)
max1 = list1[0]
for x in list1:
if x > max1:
max1 = x
print("Biggest number is ", max1)
| true |
a3c327eacdfddf49ddaaff474414f2eaffae397c | brittany-morris/Bootcamp-Python-and-Bash-Scripts | /python/learndotlab/evenorodd.py | 272 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
list = sys.argv[1]
with open(list, 'r') as f:
for num in f:
num = num.strip()
value = int(num)
if value % 2 == 0:
print(num, True)
# True means number is Even
else:
print(num, False)
# False means number is Odd
| true |
bfa6ad316c5a87c2b3c724ed7e1129c01e0a193f | Sam-stiner/science-fairproject | /science fair.py | 1,697 | 4.15625 | 4 | def convertString(str):
try:
returnValue = int(str)
except ValueError:
returnValue = float(str)
return returnValue
print 'welcome to satilite tracker 0.2.1'
print 'what object would you like find the orbit around?'
print ' 1: earth'
print ' 2: the sun'
print ' 3: a custom object (beta)'
print ' *note as of now this is not 100% accurate*'
menue = raw_input()
if a == '1':
print 'what is the mass of the satilite (kg):'
m=input()
print 'what is the vilosity of the satilite (m/s):'
v=input()
print 'how far is the satilite from earth (km):'
d=input()
print 'how long has the object been in orbit (days):'
t=input()
r=d+6378.1
f=(m*v**2)/r
print 'the net centripital force is:', f, 'newtons'
G=6.673*10**(0-11)*r**2/m**2
l=(4*3.14**2)/G*(5.97219*10**24)
k=l/r**3
T=k**.5
e=T/365
print 'the orbital period of the object is:', e, 'days'
F=(e*k)*t
h=2*3.14*r
H=h*F
print 'the object has traveled', H , 'km'
if a == '2':
print 'what is the mass of the satilite (kg):'
m=input()
print 'what is the vilosity of the satilite (m/s):'
v=input()
print 'how far is the satilite from the sun (km):'
d=input()
print 'how long has the object been in orbit (days):'
t=input()
r=d+695500
f=(m*v**2)/r
print 'the net centripital force is:', f, 'newtons'
G=6.673*10**(0-11)*r**2/m**2
l=(4*3.14**2)/G*(1.1891*10**30)
k=l/r**3
T=k**.5
e=T/365
print 'the orbital period of the object is:', T, 'days'
F=(e*k)*t
h=2*3.14*r
H=h*F
print 'the object has traveled', H , 'km'
if menue == '3'
| true |
40e018205dbc3671f3751ab5d0f359282f3150a4 | DivyangPDev/automate-Boring-Stuff-With-Python | /Chapter 6/Chapter_6.py | 2,374 | 4.1875 | 4 | #! /usr/bin/env python3
#Practice Questions
# 1. What are escape characters?
# Escape characters lets you use characters that otherwise impossible to put into a string. An escape character
# consists of a backslash (\n) followed by the character you want to add to the string
# 2. What do the \n and \t escape characters represent?
# \n escape character represents new newlines
# \t escape characters represents tab
# 3. How can you put a \ backslash character in a string?
# You can put a \backslash character in a string by making it a raw string.
# 4. The string value "Howl's Moving Castle" is a valid string. Why isn’t it
#a problem that the single quote character in the word Howl's isn’t escaped?
# Because it is enclosed by double quotes
# 5. If you don’t want to put \n in your string, how can you write a string with newlines in it?
# By using triple quotes
# 6. What do the following expressions evaluate to?
# • 'Hello world!'[1]
# 'e'
# • 'Hello world!'[0:5]
# 'Hello'
# • 'Hello world!'[:5]
# 'Hello'
# • 'Hello world!'[3:]
# 'lo world!'
# 7. What do the following expressions evaluate to?
# • 'Hello'.upper()
# 'HELLO'
# • 'Hello'.upper().isupper()
# True
# • 'Hello'.upper().lower()
# 'hello'
# 8. What do the following expressions evaluate to?
# • 'Remember, remember, the fifth of November.'.split()
# ['Remember,', 'remember,', 'the', 'fifth', 'of', 'November.']
# • '-'.join('There can be only one.'.split())
# 'There-can-be-only-one'
# 9. What string methods can you use to right-justify, left-justify, and center a string?
# right-justify - rjust()
# left-justify - ljust()
# center a string - center()
# 10. How can you trim whitespace characters from the beginning or end of a string?
# beginning - lstrip()
# end - rstrip()
# Practise Project
tableDataList = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(tableData):
colWidths = [0] * len(tableData)
for i in range(len(tableData)):
del colWidths[i]
colWidths.insert(i,len(max(tableData[i], key=len)))
maxWidth = max(colWidths)
tableLength = len(tableData[0])
for i in range(tableLength):
for j in range(len(tableData)):
print(tableData[j][i].rjust(maxWidth),end=" ")
print("")
printTable(tableDataList)
| true |
1bfb612ed8408426e7cc5c6a28ad3393e797844d | ardenercelik/Python | /convert_to_alt_caps.py | 1,093 | 4.40625 | 4 | """
Write a function named convert_to_alt_caps that accepts a string as a parameter and returns a version of the
string where alternating letters are uppercase and lowercase, starting with the first letter in lowercase.
For example, the call of convert_to_alt_caps("Pikachu") should return "pIkAcHu".
"""
def convert_to_alt_caps(word):
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = wordList[i].lower()
else:
wordList[i] = wordList[i].upper()
print("".join(wordList))
# convert_to_alt_caps("Pikacu")
# convert_to_alt_caps("arden")
# convert_to_alt_caps("isbank")
"""
Write a function named count_words that accepts a string as
its parameter and returns the number of words in it. A word is a
sequence of one or more non-space characters. For example, the call of
count_words("What is your name?") should return 4.
"""
def count_words(sentence):
sList = sentence.split()
print("There are {} words in this sentence.".format(len(sList) ) )
count_words("What is your name?")
| true |
5ae848cedbd3dd5b0cc94f0404dd7e9daf40b638 | Bashir63/pands | /code/Week02/bmi.py | 454 | 4.28125 | 4 | # This is my first weekly problem solving program for this course
# This program calculates the user's BMI using their inputs
# Author : Bashir Ahammed
# inputs for user's height and weight
weight = float (input ("Enter weight: "))
height = float (input ("Enter height: "))
# Conversion of centimeters to meter squared
metersquared = (height / 100) **2
# Calculation of BMI
BMI = round(weight / metersquared, 2)
#BMI output
print("BMI is {}". format(BMI)) | true |
a6589717a9591f153892ead3989283aa4e676401 | PriyankaSahu1/Practise-Python | /handson/handson15.py | 409 | 4.125 | 4 | #handson 15
list=["abc","bcd","jkl","xyz","mno"]
#using membership operator
if("abc" in list):
print("abc is available")
else:
print("abc is not present")
#without using membership operator
for i in range(5):
if(list[i]=="abc"):
print("available")
break
else:
print("not available")
#printing list in reverse direction
list.reverse()
print(list)
| true |
d425842338650746eb7de3fc1a2ad7d922c0deaa | stellakaniaru/simple-python-games | /tictactoe.py | 1,375 | 4.125 | 4 | '''
Tic Tac Toe game.
'''
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
drawBoard([''] * 10)
def inputPlayerLetter():
# Lets the player type which letter they want to be.
# Returns a list with the player’s letter as the first item, and the computer's letter as the second.
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
# the first element in the list is the player’s letter, the second is the computer's letter.
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again,otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y') | true |
3821a69333bbbe017c04c25f68df88c3b3c61706 | ramesh1990/Python | /Easy/stock.py | 894 | 4.28125 | 4 | '''
Stock Buy Sell to Maximize Profit
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.
For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
'''
def stock(lst):
if ( len(lst) < 2) :
return 0
min_val = lst[0]
min_ind = 0
for i in range(len(lst)):
if ( lst[i] < min_val ) :
min_val = lst[i]
min_ind = i
max_val = lst[min_ind]
for j in range(min_ind+1,len(lst)):
if ( lst[j] > max_val ):
max_val = lst[j]
return max_val - min_val
print (" Stock : ",stock([5,2,6,1,7,8,10,3]))
| true |
aa9e99206b9458bbb76c6e2d557d63301e5662ce | lavenderLatte/python_practice | /word_autoCorrection/edit_distance.py | 2,024 | 4.28125 | 4 | """
Function to compute edit distance between two words.
Edit distance -- the minimum number of +, -, r operations that are needed to convert str2 to str1.
+, -, r are addition, subtraction and replacement.
For example:
str1 = "abc", str2 = "ac". edit distance is 1 --> addition of b str2.
str1 = "abc", str2 = "axc". edit distance is 1 --> replace x with b in str2.
str1 = "a", str2 = "xc". edit distance is 2 --> remove c, replace x with a.
str1 -- first input string.
str2 -- second input string.
out -- edit distance.
usage:
from edit_distance import edit_distance
edit_distance(str1, str2)
"""
import numpy as np
def edit_distance(str1, str2):
""" edit_distance("", "") == 0 """
""" edit_distance("a", "") == 1 """
""" edit_distance("", "a") == 1 """
""" edit_distance("b", "a") == 1 """
""" edit_distance("xyz", "abc") == 3 """
# get length of str1 and str2
n1 = len(str1)
n2 = len(str2)
#create a 2d array
dp = np.zeros(shape=(n2+1, n1+1)).astype('int')
#dp[0][0] is the distance between two empty strings. Hence 0.
dp[0][0] = 0 # redundant but for clarity
#initialize the dp array
for i1 in range(1, n1+1):
# edit distance of empty string to another string of length i1 is i1.
dp[0][i1] = i1
for i2 in range(1, n2+1):
# edit distance of a string of length i2 to be converted to empty is i2
dp[i2][0] = i2
# dp for non trivial strings
for i1 in range(1, n1+1):
for i2 in range(1, n2+1):
if(str1[i1-1] == str2[i2-1]):
# if the characters are the same, then get the distance from prefixes of both str1 and str2
dp[i2][i1] = dp[i2-1][i1-1]
else:
dp[i2][i1] = np.min([ dp[i2-1][i1-1] +1, # replacing str2[i2] with str1[i1]
dp[i2-1][i1] +1, # remove str2[i2]
dp[i2][i1-1] +1 ]) # add str1[i1] at the end
out = dp[n2][n1]
return out | true |
c8acc4486cb24f3219cda93255d5c0a822483cf9 | GeburtstagsTorte/Homework | /Projects/Genetic Algorithm/Bubble Arena/Populations.py | 1,105 | 4.46875 | 4 | """
Step 1:
Initialize:
Create a population of N elements, each with randomly generated DNA (genes)
(drawing)
Step 2:
Selection:
Evaluate the fitness of each element of the population and create a pool (mating pool)
Step 3:
Reproduction:
a) Pick two parents with probability according to their relative fitness
b) Replicate: create a child by combining the DNA of these two parents
c) Mutation: mutate the child's DNA based on a given probability
d) add new child to a new population
Step 4:
New generation:
Replace the old population with the new population and return to Step 2 until task is accomplished
"""
class Populations:
population = []
generation = 0
# best = object
# average_fitness = 0
def __init__(self):
pass
def update(self):
pass
def calc_fitness(self):
pass
def calc_average_fitness(self):
pass
def calc_best_individual(self):
pass
def selection(self):
pass
def reproduction(self):
pass
def mutation(self):
pass
| true |
45b58f45a716e59aea24bf7b11b81b1815a408e9 | riadassir/MyFirstRepository | /ex_06_02.py | 973 | 4.5 | 4 | #############################################################
# Riad Assir - Coursera Python Data Strucutres Class - ex_06_02.py
# Dealing with Files
#############################################################
#FileHandle = open('mbox-short.txt')
FileName = input('Enter the file name: ')
try:
FileHandle = open(FileName)
except:
print('File cannot be opened: ', FileName)
quit()
for line in FileHandle:
print((line.rstrip()).upper())
#content = FileHandle.read()
#UpperCaseContent = content.upper()
#print (UpperCaseContent)
#################################### testing code for previous work
#count = 0
#for line in FileHandle:
# line.rstrip()
# if line.startswith('Subject:'):
# count = count + 1
# if not line.startswith('From:'): #If you don't see the word From in the line, skip it..
# continue
# print(line)
#
#print('There were', count, 'subject lines in', FileName)
######################################
| true |
92e6e640eca88f65c651ef4b156992b7fb8c52fb | dtauxe/hackcu-ad | /plot.py | 2,690 | 4.15625 | 4 | #!/bin/python
# From:
# https://stackoverflow.com/questions/6697259/interactive-matplotlib-plot-with-two-sliders
from numpy import pi, sin
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
import math
# Draw the plot
def do_plot(sigstr):
def signal(t):
return eval(sigstr)
axis_color = 'lightgoldenrodyellow'
fig = plt.figure()
ax = fig.add_subplot(111)
# Adjust the subplots region to leave some space for the sliders and buttons
fig.subplots_adjust(left=0.25, bottom=0.25)
x_axis = 2*pi
#t = np.arange(0.0, x_axis, x_axis/1000)
t = np.linspace(0, x_axis, num=1000)
# Draw the initial plot
# The 'line' variable is used for modifying the line later
[line] = ax.plot(t, signal(t), linewidth=2, color='red')
ax.set_xlim([0, x_axis])
ax.set_ylim([-10, 10])
# Add two sliders for tweaking the parameters
# Define an axes area and draw a slider in it
xax_slider_ax = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axis_color)
xax_slider = Slider(xax_slider_ax, 'X-Axis', pi/64, 64*pi, valinit=x_axis)
# Draw another slider
#freq_slider_ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axis_color)
#freq_slider = Slider(freq_slider_ax, 'Freq', 0.1, 30.0, valinit=freq_0)
# Define an action for modifying the line when any slider's value changes
def sliders_on_changed(val):
x_axis = val
#t = np.arange(0.0, x_axis, x_axis/1000)
t = np.linspace(0, x_axis, num=1000)
[line] = ax.plot(t, signal(t), linewidth=2, color='red')
print (x_axis)
ax.set_xlim([0, x_axis])
line.set_ydata(signal(t))
fig.canvas.draw_idle()
xax_slider.on_changed(sliders_on_changed)
#freq_slider.on_changed(sliders_on_changed)
# Add a button for resetting the parameters
reset_button_ax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
reset_button = Button(reset_button_ax, 'Reset', color=axis_color, hovercolor='0.975')
def reset_button_on_clicked(mouse_event):
#freq_slider.reset()
xax_slider.reset()
reset_button.on_clicked(reset_button_on_clicked)
# Add a set of radio buttons for changing color
color_radios_ax = fig.add_axes([0.025, 0.5, 0.15, 0.15], axisbg=axis_color)
color_radios = RadioButtons(color_radios_ax, ('red', 'blue', 'green'), active=0)
def color_radios_on_clicked(label):
line.set_color(label)
fig.canvas.draw_idle()
color_radios.on_clicked(color_radios_on_clicked)
plt.show()
### MAIN
if __name__ == '__main__':
while (True):
sigstr = input("---> ")
do_plot(sigstr)
| true |
8bf9e58c2d775db3e3c77f7e852de92dc521be55 | jjennas/web-ohjelmointi | /assignment2/2.py | 621 | 4.21875 | 4 | import re, statistics
#function finds numbers in string
def finding_numbers(s):
return re.findall(r"-?\d+",s)
answer = input("Give integers, can be separated by any character")
if not answer:
print("Please input integers separated by any character")
else:
numbers = finding_numbers(answer)
# Tries to convert string of numbers into list of integers
try:
int_list = [int(i) for i in numbers]
print(f"Sum is {sum(int_list)}, mean is {statistics.mean(int_list):.1f} and median is {statistics.median(int_list):.1f}")
except ValueError:
print("Error! No integers was given")
| true |
98eb13251a8780adc7acdb61c5db8fec32e1a741 | lw2533315/leetcode | /uniquePaths_test.py | 876 | 4.40625 | 4 | # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
# The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
# How many possible unique paths are there?
# 递归法超时,只是用来测验和查找规律
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
l = [0]
self.move(1,1,m,n,l)
return l[0]
def move(self, row,col,m,n,l):
if row == m and col == n:
l[0] += 1
elif row > m or col > n:
pass
else:
self.move(row + 1, col,m,n,l)
self.move(row, col + 1, m,n, l)
s = Solution()
print (s.uniquePaths(3,2))
| true |
9346d7d92949c4037d1bf5a76b65b48b2a398276 | newmayor/pythonlearning | /selectionSort.py | 666 | 4.1875 | 4 | def selSort(L):
"""Assumes that L is a list of elements that can be compared using >.
Sorts L in ascending order. """
suffixStart = 0
while suffixStart != len(L):
#look at each element in suffix
for i in range(suffixStart, len(L)):
if L[i] < L[suffixStart]:
#swap position of elements
L[suffixStart], L[i] = L[i], L[suffixStart]
suffixStart += 1
#this program consists of two loops that increment thru a length of list. The inside one is O(len(L)) and the outside one is O(len(L)). Therefore, this program has complexity O(len(L^2)). This is known as quadratic time complexity. | true |
c947b7d0e412238a284ce7a8ca8515b77ff454a6 | newmayor/pythonlearning | /ex_IO.py | 2,724 | 4.1875 | 4 |
def print_numbers(numbers):
print("These are the currently stored phone numbers: ")
for k, v in numbers.items():
print("Name:", k, "\tNumber:", v)
print()
def add_number(numbers, name, number):
numbers[name] = number #use a dict to define name as the dict key and the associated number as the dict value
def remove_number(numbers, name):
if name in numbers:
del numbers[name]
else:
print(name, " was not found")
def lookup_number(numbers, name):
if name in numbers:
return "The number belonging to " + name + "is " + numbers[name]
else:
return name + " was not found."
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, number = in_line.split(",")
numbers[name] = number
in_file.close()
def save_numbers(numbers, filename):
out_file = open(filename, "wt")
for k, v in numbers.items():
out_file.write(k + ", " + v + "\n")
out_file.close()
def print_menu():
print("1. Print phone numbers")
print("2. Add a phone number")
print("3. Remove a phone number")
print("4. Lookup a phone number")
print("5. Load phone numbers FROM txt file")
print("6. Save phone numbers INTO txt file")
print("7. Quit program")
print()
phone_list = {}
menu_choice = 0
print_menu()
while True:
menu_choice = int(input("Type in menu selection number (1-7):"))
if menu_choice == 1:
print_numbers(phone_list)
elif menu_choice == 2:
print("Adding a name and number to the phonebook.")
name = input("Name?: ")
phone = input("Enter the phone number: ")
add_number(phone_list, name, phone)
elif menu_choice == 3:
print("Remove a name and associated number.")
name = input("Name of the phone number to remove? ")
remove_number(phone_list, name)
elif menu_choice == 4:
print("Looking up a number")
name = input("Enter the name of the person whose phone number you want to lookup: ")
print(lookup_number(phone_list, name))
elif menu_choice == 5:
print("Loading phone numbers from a txt file...")
filename = input("Please enter the file name or path to load:")
load_numbers(phone_list, filename)
elif menu_choice == 6:
print("Saving the numbers to a txt file...")
filename = input("Enter the filename or path to which you'd like to save these numbers to: ")
save_numbers(phone_list, filename)
elif menu_choice == 7:
break
else:
print_numbers
print("Goodbye!")
| true |
a4ce076b6389af67d906657b1653cdaad0e5996e | the-aerospace-corporation/ITU-Rpy | /tiler.py | 1,472 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Turns a rectangle into a number of square tiles.
Created on Thu Oct 15 17:24:31 2020
@author: MAW32652
"""
def tiler(m, n, dimList = []):
"""
Tiler outputs the size of the tiles (squares), that are required to fill
a rectangle of arbitrary dimension.
Note: It does not find the minimum number of squares, but finds a number of squares.
m = len of horz dimension
n = len of vert dimension
output = dimList, a list of the dimensions of the squares that are required to
fill the rectangle.
"""
#if the input lists are of the same length
if len(m) == len(n):
#add the length of either dimension to the list.
dimList.append(len(m))
#return the lsit of results.
return dimList
#case where the m dimension is larger than the n dimension
elif len(m) > len(n):
#append the length of the smaller dimension, n.
dimList.append(len(n))
#do tiler on the rest of the rectangle
#start at len(n) to the end and all of n.
return tiler(m[len(n):], n, dimList)
#case where the n dimension is larger than the m dimension.
elif len(n) > len(m):
#append the length of the smaller dimension, m.
dimList.append(len(m))
#do tiler on the rest of the rectangle
#start at all of m and at len(m)
return tiler(m, n[len(m):], dimList)
| true |
a429f0cf76e5617d958e23514f1a4ba2d67d6e4f | rock-chock/leetcode | /412_fizzbuzz.py | 804 | 4.125 | 4 | """
https://leetcode.com/problems/fizz-buzz/
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and
for the multiples of five output “Buzz”. For numbers which are multiples of
both three and five output “FizzBuzz”.
"""
def main():
n = 30
res = fizzbuzz(n)
for i in res:
print(i)
def fizzbuzz(n):
r =[]
for i in range(1, n+1):
div_by_3 = (i % 3 == 0)
div_by_5 = (i % 5 == 0)
if div_by_3 and div_by_5:
r.append('FizzBuzz')
elif div_by_3:
r.append('Fizz')
elif div_by_5:
r.append('Buzz')
else:
r.append(str(i))
return r
if __name__ == "__main__":
main()
| true |
e3551871af7f069111a413ee63db06796503aa90 | Tylerman90/PythonPractice | /odd_even_funk.py | 821 | 4.375 | 4 | #Write a program that reads a list of integers,
#and outputs whether the list contains
#all even numbers, odd numbers, or neither.
#The input begins with an integer
#indicating the number of integers that follow.
def user_values():
my_list = []
num_in_list = int(input())
for num in range(num_in_list):
my_list.append(int(input()))
return my_list
def is_list_even(my_list):
for i in my_list:
if (i % 2 == 1):
return False
return True
def is_list_odd(my_list):
for i in my_list:
if (i % 2 == 0):
return False
return True
if __name__ == '__main__':
user_list = user_values()
if is_list_even(user_list):
print('all even')
elif is_list_odd(user_list):
print('all odd')
else:
print('not even or odd') | true |
f145873536f4f3fcdec1bfc5fcc8cb065f5742f6 | kapiltiwari1411/python-lab | /kapil4reverse.py | 246 | 4.25 | 4 | #program to find reverse of enterd number.
num=int(input("please enter any number"))
reverse=0.
while(num>0):
reminder=num%10
reverse=(reverse*10)+reminder
num=num//10.
print(" reverse of the entered number\n", reverse)
| true |
a37d0bfdb5defc86998701657f9c11ff27113a1a | ItsPepperpot/hangman | /hangman.py | 2,362 | 4.125 | 4 | # Hangman.
# Made by Oliver Bevan in July 2019.
import random
print("Welcome to hangman!")
menu_choice = 0
while menu_choice != 3:
print("Please pick an option.")
print("1. Begin game")
print("2. Show rules")
print("3. Exit")
menu_choice = int(input())
if menu_choice == 1: # Begin game.
print("Thinking of a word...")
dictionary = open("words.txt", "r")
word_list = []
for line in dictionary:
word_list.append(line)
dictionary.close()
word_to_guess = word_list[random.randint(0, len(word_list) - 1)]
print("Let's begin.")
user_has_won = False
lives_remaining = 8
matched_characters = [" "] * len(word_to_guess)
while not user_has_won and lives_remaining > 0:
for i in range(0, len(word_to_guess)):
if matched_characters[i] is not " ":
print(matched_characters[i], end=" ")
else:
print("_", end=" ")
print(
f"\n Please enter a guess. ({lives_remaining} lives remaining)")
guess = input()
if len(guess) > 1:
# User is guessing the word.
if guess == word_to_guess:
user_has_won = True
else:
lives_remaining -= 1
print("Sorry, that's not the correct word.")
else:
# User is guessing a letter.
if guess in word_to_guess:
for i in range(0, len(word_to_guess)):
if word_to_guess[i] == guess:
matched_characters[i] = guess
else:
print("Sorry, that's not in the word.")
lives_remaining -= 1
if user_has_won:
print("Congratulations! You got it.")
else:
print("Sorry, you lose!")
print(f"The word was {word_to_guess}")
elif menu_choice == 2: # Show rules.
print("How to play:")
print("Hangman is a simple guessing game.")
print("The computer thinks of a word. To win, you simply guess the word by suggesting letters.")
print(
"If you cannot guess the word within the maximum number of guesses, you lose.")
print("Good luck!")
| true |
cbd3e856cce1ba5c088408c9722989b82ee30709 | JamieBort/LearningDirectory | /Python/Courses/LearnToCodeInPython3ProgrammingBeginnerToAdvancedYourProgress/python_course/Section3ConditionalsLoopsFunctionsAndABitMore/22ExerciseLoops.py | 1,226 | 4.28125 | 4 | # First of two.
# Create a program that asks a user for 8 names of people.
# Store them in a list.
# When all the names have been given, pick a random one and print it.
# Second of two.
# Create a guess game with the names of colors.
# At each round pick a random color and let the user guess it.
# After a successful guess, ask the user if they want to play again.
# Keep playing until the user types "no"
import random #used for both
# First of two.
mylist = []
while len(mylist) < 8:
another = input("One by one, please type the name of a person.\n")
mylist.append(another)
print("Your list of people is: ", mylist)
print("Here is the name from your list that has been picked randomly: ", random.choice(mylist))
# Second of two.
guess = "yes"
listOfColors = ["red", "orange", "blue", "green"]
while guess != "no":
guess = input("Make a guess. Type 'red', 'orange', 'blue', or 'green'. If it matches the computer, you win. The game will be over. If not, guess again.\n")
print("You guessed: ", guess)
if random.choice(listOfColors) == guess:
print("They guessed correctly. Game over.")
break
else:
print("They guessed incorectly. Guess again.")
print("Out of while loop.") | true |
7096d9987e86cdc601fa4d2fbb6f748b69a4eb00 | Youngjun-Kim-02/ICS3U-Assignment2-python | /volume_of_cone.py | 726 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Youngjun Kim
# Created on: April 2021
# This program calculates the volume of a cone
# with radius and height inputted from the user
import math
def main():
# this function calculates the volume of a cone
# main function
print("We will be calculating the area of a cone. ")
# input
radius_of_cone = int(input("Enter radius of a cone (mm): "))
height_of_cone = int(input("Enter height of a cone (mm): "))
# process
volume_of_cone = 1/3 * math.pi * radius_of_cone * radius_of_cone * height_of_cone
# output
print("")
print("Volume is {0} mm³.".format(volume_of_cone))
print("")
print("Done.")
if __name__ == "__main__":
main()
| true |
4b80e51dc0a98003cf82bc271886b0b61ff284e7 | sinugowde/PythonWorkSpace | /PP_006.py | 433 | 4.21875 | 4 | # PythonPractice_006: Polindrome
def checkPolindrome(stringVar):
for i in range(0, len(stringVar)//2):
if stringVar[i] != stringVar[-i-1]:
resVar = False
break
resVar = True
return resVar
# Main Function/Method
stringVar = input()
resVar = checkPolindrome(stringVar)
if resVar:
print("the Entered string: " + stringVar + ", is a POLINDROME")
else:
print("the Entered string: " + stringVar + ", is not a POLINDROME") | true |
a2cbae5516ae86338884900c57ea0a60433b8260 | bradweeks7/CPE202 | /Labs/Lab1/lab1/lab1.py | 933 | 4.3125 | 4 |
def max_list_iter(int_list): # must use iteration not recursion
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
if int_list == None:
raise ValueError
# An empty list should return None
if len(int_list) == 0:
return None
for number in range(len(int_list)):
maximum = 0
new_max = int_list[number]
if new_max > maximum:
maximum = new_max
return maximum
def reverse_rec(int_list): # must use recursion
"""recursively reverses a list of numbers and returns the reversed list
If list is None, raises ValueError"""
pass
def bin_search(target, low, high, int_list): # must use recursion
"""searches for target in int_list[low..high] and returns index if found
If target is not found returns None. If list is None, raises ValueError """
pass
| true |
a93d3bd1ef9fee237e33689359553aef83b26b22 | sdawn29/cloud-training | /list_ex.py | 1,317 | 4.375 | 4 | #list -> class
l1 = list([10, 20, 30]) # a list of 3 elements
l2 = [10, 12.5, 'python', ['a','b']] #shortcut of creating a list
print(l2)
print(l2[1])
print(l2[2][1])
print(l2[-1:1:-1])
#add element ot the list
l2.append(200)
print('append=',l2)
l2.insert(2,300)
print('Insert=',l2)
l3 = [10,20]
l4 = ['a', 'b']
l5 = l3 + l4
l6 = l3 * 10
print(l5, l6, sep = '\n')
l3.extend(l4)
print('extends =', l3)
#remove elements from list
r1 = l5.pop()
print('r1=', r1, l5)
r2 = l5.pop(2)
print('r2 =', r2, l5)
r3 = l5.remove(20) #in this case we are passing the value, it will remove the first occurance of the value
print('remove=', r3, l5)
del l5[0]
print('After del=', l5)
#update elements to the list
print('l3=',l3)
l3[1] = 'Java'
print('after update=',l3)
#some other methods
l6 =[10, 30, 20]
l6.sort() #ascending order
print('sort ascend =', l6)
l7 = ['z','a','b']
l7.sort(reverse = True) #descending order
print('sort desc =', l7)
l8 = [10, 'a', 20, 'b']
l8.reverse() # print the reverse of the list
print('reverse=',l8)
l8.clear()
print('l8=',l8)
#copy
l = [10, ['a', 'b']]
m = l # Reference copy
n =l.copy() #shallow copy
#copy module -> copy(), deepcopy()
import copy
p = copy.deepcopy(l)
print(id(l[0]), id(p[0]))
print(id(l[1]), id(p[1]))
| true |
8eb9843678140e25e75f2a9030c2480d0fdd649c | SafiyatulHoque/Bootcamp-NSU | /Bootcamp 11/Pre Bootcamp Contest 11 (1)/Q.py | 436 | 4.625 | 5 | # Python3 code to demonstrate
# to extract words from string
# using split()
# initializing string
test_string = 'Adventures in Disneyland Two blondes were going to Disneyland when they came to a fork in the road. The sign read: "Disneyland Left." So they went home.'
# printing original string
print ("The original string is : " + test_string)
# using split()
# to extract words from string
res = test_string.split()
print (res)
| true |
66ea622dc4018f5849cb4a2f938a7837ae418635 | shreyansh-tyagi/leetcode-problem | /power of 2.py | 808 | 4.25 | 4 | '''
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
Example 4:
Input: n = 4
Output: true
Example 5:
Input: n = 5
Output: false
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
''''
import math
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
a,b=0,0
if n==0:
return False
while(a!=n and a<n):
a=2**b
b+=1
if a==n:
return True
else:
return False
| true |
0c121b96785c7586221dd6a08d0a5ec24ee5abaf | shreyansh-tyagi/leetcode-problem | /wildcard matching.py | 1,248 | 4.28125 | 4 | '''
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input: s = "adceb", p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input: s = "acdcb", p = "a*c?b"
Output: false
Constraints:
0 <= s.length, p.length <= 2000
s contains only lowercase English letters.
p contains only lowercase English letters, '?' or '*'.
'''
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if p=='*' and p=='?':
p.remove('*')
p.remove('?')
if p in s :
return 'true'
else:
return 'false' | true |
926c7b7076a25daef60b3d3b300670b30e73e575 | shreyansh-tyagi/leetcode-problem | /backspace string compare.py | 1,175 | 4.125 | 4 | '''
Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Example 2:
Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".
Example 3:
Input: s = "a##c", t = "#a#c"
Output: true
Explanation: Both s and t become "c".
Example 4:
Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".
Constraints:
1 <= s.length, t.length <= 200
s and t only contain lowercase letters and '#' characters.
Follow up: Can you solve it in O(n) time and O(1) space?
'''
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
a,b=[],[]
for i in s:
if i!='#':
a.append(i)
else:
if a!=[]:
a.pop()
for j in t:
if j!='#':
b.append(j)
else:
if b!=[]:
b.pop()
return a==b | true |
4d5d7368ff9248788d9fbd3acf136b51a8f35c00 | shreyansh-tyagi/leetcode-problem | /planning a meeting.py | 1,748 | 4.25 | 4 | '''
You have to organize meetings today. There are meetings for today. Meeting must start at time and end at time . Unfortunately, there are only two meeting rooms available today. Consider meetings and intersecting in time if .
You cannot conduct two meetings in the same room at the same time.
Your task is to determine whether it is possible to hold all meetings using only two rooms. If yes, then print . Otherwise, print .
Function description
Complete the isPossible function in the editor. It contains the following parameters:
Parameter name:
Type: INTEGER
Description: Number of meetings
Parameter name:
Type: INTEGER ARRAY
Description: Start time of meetings
Parameter name:
Type: INTEGER ARRAY
Description: End time of meetings
Return
The function must return an INTEGER denoting the answer to the problem.
If it is possible to hold all the meetings using only two rooms, then it is . Otherwise, it is .
Input format
The first line contains an integer denoting the number of elements in .
Each line of subsequent lines (where ) contains an integer describing .
Each line of subsequent lines (where ) contains an integer describing .
Constraints
SAMPLE INPUT
3
1
2
4
2
3
5
SAMPLE OUTPUT
1
Explanation
Hold the first ([1; 2]) and the third ([4; 5]) meetings in the first room.
Hold the second meeting ([2; 3]) in the second room.
'''
def isPossible(n,s,e):
# Write your code here
for i in range(n):
if max(s)>=min(e):
return 1
else:
return 0
return # Write your code here
n = int(input())
start = []
end = []
for _ in range(n):
start.append(int(input()))
for i in range(n):
end.append(int(input()))
out_ = isPossible(n, start, end)
print(out_) | true |
18e31179f424c66e561bcd7d88536f73381c423e | shreyansh-tyagi/leetcode-problem | /permutations.py | 662 | 4.125 | 4 | '''
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1]
Output: [[1]]
Constraints:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
All the integers of nums are unique.
'''
from itertools import permutations
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
b=(list(permutations(nums)))
c=[]
for i in range(len(b)):
c.append(list(b[i]))
return c | true |
cc19150ea53ef523c336039b30c3d79dfd12fdd2 | ElizabethRoots/python_practice | /mini_projects/ft_converter.py | 711 | 4.40625 | 4 | #!/usr/bin/env python3
import sys
height = float(input("Enter your height in the format: ft.in "))
inches = height * 12
dvd = 7.48
creditCard = 3.375
iPadAir = 9.4
select = int(
input("Select unit of measurement: 1 = DVD case, 2 = Credit Cards, 3 = iPad Air Gen-One "))
def divide(inches, select):
formatted_float = "{:.2f}".format(inches / select)
return formatted_float
if select == 1:
print("You are", divide(inches, dvd), "DVD cases tall.")
if select == 2:
print("You are", divide(inches, creditCard),
"Credit cards tall.")
if select == 3:
print("You are", divide(inches, iPadAir),
"iPad Air gen-one's tall.")
else:
print("Not a valid input.")
| true |
351ecae3df591709bba7a5ad0e0c44005338b615 | calebhews/Ch.08_Lists_Strings | /8.0_Jedi_Training.py | 1,650 | 4.46875 | 4 | # Sign your name: Caleb Hews
'''
1.)
Write a single program that takes any of the three lists, and prints the average.
Use the len function. There is a sum function I haven't told you about.
Don't use that. Sum the numbers individually as shown in the chapter.
Also, a common mistake is to calculate the average each time through the loop
to add the numbers. Finish adding the numbers before you divide.
'''
a_list = [3,12,3,5,3,4,6,8,5,3,5,6,3,2,4]
b_list = [4,15,2,7,8,3,1,10,9]
c_list = [5,10,13,12,5,9,2,6,1,8,8,9,11,13,14,8,2,2,6,3,9,8,10]
a_total = 0
b_total = 0
c_total = 0
for item in a_list:
a_total += item
a_num=len(a_list)
for item in b_list:
b_total += item
b_num=len(b_list)
for item in c_list:
c_total += item
c_num=len(c_list)
a_ave=a_total/a_num
b_ave=b_total/b_num
c_ave=c_total/c_num
print(a_ave)
print(b_ave)
print(c_ave)
'''
2.) Write a program that will strip the username (whatever is in front of the @ symbol)
from any e-mail address and print it. First ask the user for their e-mail address.
'''
# done=False
# while True:
# email=input("What is your email address? ")
# username=" "
# for item in email:
# if item=="@":
# done=True
# break
# username += item
# print(username)
'''
TEXT FORMATTING:
3.) Make following program output the following:
Score: 41,237
High score: 1,023,407
Do not use any plus sign (+) in your code.
You should only have two double quotes in each print statement.
'''
# score = 41237
# highscore = 1023407
# print("Score: " + str(score) )
# print("High score: " + str(highscore) )
| true |
fa2880ed5dfb7e0fe4986a84097af2ca38aa0eb4 | FazeelUsmani/Scaler-Academy | /017 String Algorithm/A3 reverseString.py | 1,038 | 4.28125 | 4 | /*
Reverse the String
Problem Description
Given a string A of size N. Return the string A after reversing the string word by word. NOTE:
A sequence of non-space characters constitutes a word.
Your reversed string should not contain leading or trailing spaces, even if it is present in the input string.
If there are multiple spaces between words, reduce them to a single space in the reversed string.
Problem Constraints
1 <= N <= 105
Input Format
The only argument given is string A.
Output Format
Return the string A after reversing the string word by word.
Example Input
Input 1:
A = "the sky is blue"
Input 2:
A = "this is ib"
Example Output
Output 1:
"blue is sky the"
Output 2:
"ib is this"
Example Explanation
Explanation 1:
We reverse the string word by word so the string becomes "the sky is blue".
*/
class Solution:
# @param A : string
# @return a strings
def solve(self, A):
A = A.split()
A = A[::-1]
return ' '.join(A)
| true |
37209057e5842fb3a827b0588918d4ee291bcdfd | k4u5h4L/algorithms | /leetcode/Symmetric_Tree.py | 935 | 4.34375 | 4 | '''
Symmetric Tree
Easy
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
return self.is_symmetric(root.left, root.right)
def is_symmetric(self, left, right):
if left == None or right == None:
return left == right
if left.val != right.val:
return False
return self.is_symmetric(left.left, right.right) and self.is_symmetric(left.right, right.left)
| true |
a8ffbc2d433ae45bf4f87875e663b4853be83cc2 | k4u5h4L/algorithms | /nuclei/max_profit.py | 486 | 4.15625 | 4 | '''
For the given array of length and price find the maximum profit that can be gained.
'''
def maxProfit(prices):
max_profit = 0
min_price = prices[0]
for price in prices:
min_price = min(price, min_price)
max_profit = max(max_profit, price - min_price)
return max_profit
def main():
prices = [2,4,2,5,8,2,3]
res = maxProfit(prices)
print(f"Max profit of {prices} is {res}")
if __name__ == "__main__":
main() | true |
fb775e5361af5b84e1b1be3bae5f526bab67ea19 | k4u5h4L/algorithms | /leetcode/ZigZag_Conversion.py | 1,955 | 4.34375 | 4 | '''
ZigZag Conversion
Medium
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
'''
class Solution:
def convert(self, s: str, numRows: int) -> str:
if len(s) == 1 or numRows == 1:
return s
zig_zag = []
for _ in range(numRows):
zig_zag.append([" "] * (len(s)))
i = 0
j = 0
point = 0
down_or_slant = True
while point < len(s):
if down_or_slant:
while i < numRows and point < len(s):
zig_zag[i][j] = s[point]
i += 1
point += 1
down_or_slant = not down_or_slant
j += 1
else:
i -= 2
while i >= 0 and point < len(s):
zig_zag[i][j] = s[point]
i -= 1
j += 1
point += 1
i += 2
down_or_slant = not down_or_slant
res = ""
for i in range(len(zig_zag)):
for j in range(len(zig_zag[i])):
if zig_zag[i][j] != " ":
res += zig_zag[i][j]
return res
| true |
f6846b1ccb90f6eb86bee2970132941cf498c102 | k4u5h4L/algorithms | /leetcode/Second_Largest_Digit_in_a_String.py | 1,017 | 4.28125 | 4 | '''
Second Largest Digit in a String
Easy
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
'''
class Solution:
def secondHighest(self, s: str) -> int:
max_num = 0
for char in s:
try:
max_num = max(max_num, int(char))
except ValueError:
pass
s = s.replace(str(max_num), "")
max_num = -1
for char in s:
try:
max_num = max(max_num, int(char))
except ValueError:
pass
return max_num
| true |
0a7df1ce50f54435c9a653bd0c4c5bc54e6179a9 | k4u5h4L/algorithms | /leetcode/Rotate_Image.py | 1,123 | 4.46875 | 4 | '''
Rotate Image
Medium
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
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:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2:
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Example 3:
Input: matrix = [[1]]
Output: [[1]]
Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
'''
# Intuition is to take transpose and then reverse each row
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
res = []
for i in range(len(matrix)):
res.append(matrix[i].copy())
for i in range(len(res)):
for j in range(len(res[i])):
matrix[i][j] = res[j][i]
matrix[i].reverse()
| true |
cc9934f6d827570fd8bb3ad05b6acc36b3c37495 | k4u5h4L/algorithms | /leetcode/Add_to_Array-Form_of_Integer.py | 508 | 4.1875 | 4 | '''
Add to Array-Form of Integer
Easy
The array-form of an integer num is an array representing its digits in left to right order.
For example, for num = 1321, the array form is [1,3,2,1].
Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.
'''
class Solution:
def addToArrayForm(self, num: List[int], k: int) -> List[int]:
res = [str(n) for n in num]
res = str(int(''.join(res)) + k)
return [int(char) for char in res] | true |
f2da2236b2af5e8cc428d8bc6dac3e08b19e574c | k4u5h4L/algorithms | /leetcode/Set_Matrix_Zeroes.py | 926 | 4.28125 | 4 | '''
Set Matrix Zeroes
Medium
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.
You must do it in place.
Example 1:
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Example 2:
Input: matrix = [[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]]
'''
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
res = []
for i in range(len(matrix)):
res.append(matrix[i].copy())
for i in range(len(res)):
for j in range(len(res[i])):
if res[i][j] == 0:
for k in range(len(res)):
matrix[k][j] = 0
for k in range(len(res[i])):
matrix[i][k] = 0
| true |
8a91d4bf14c9215077834ed74748ee2e6b8fa163 | TheHugeHaystack/Solucion-a-problemas-con-Programacion | /temperature.py | 1,636 | 4.65625 | 5 | #Code by: rghost Academic Purposes
#This code is to do the following:
# Write a program that will prompt the user for a temperature asking the user between Fahrenheit and Celsius;
# then, convert it to the other. You may recall that the formula is C = 5 ∗ (F − 32)/9.
# Modify the program to state whether or not water would boil at the temperature given.
import string
if __name__ == '__main__':
c = True;
while c:
t=0;
opt = input("Please enter if you would like to convert from Celsius or Fahrenheit to the other (C/F): ");
if opt.lower() == "c":
t = input("Enter your temperature in Celsius ");
print("A temperature of " + str(t) + " degrees Celsius is "+ str(float(t)*(9/5)+32) +" in Fahrenheit");
if float(t)*(9/5)+32 >= 100:
print ("Water boils at this temperature (under typical conditions).")
else:
print("Water does not boil at this temperature (under typical conditions).")
elif opt == "f":
t = input("Enter your temperature in Fahrenheit ");
print("A temperature of " + str(t) + " degrees Fahrenheit is "+ str((float(t)-32)*5/9) +" in Celsius");
if (float(t)-32)*5/9 >= 212:
print ("Water boils at this temperature (under typical conditions).")
else:
print("Water does not boil at this temperature (under typical conditions).")
else:
print("Not a valid answer");
a = input("Would you like to enter another temperature? Y/AnyKey* ")
if a.lower() != "y":
break;
| true |
69ba50bcd982901a944ae4c5be100dce7ceebe79 | mrinfosec/cryptopals | /c10.py | 2,265 | 4.15625 | 4 | #!/usr/bin/python
# Implement CBC mode
# CBC mode is a block cipher mode that allows us to encrypt irregularly-sized
# messages, despite the fact that a block cipher natively only transforms
# individual blocks.
#
# In CBC mode, each ciphertext block is added to the next plaintext block before
# the next call to the cipher core.
#
# The first plaintext block, which has no associated previous ciphertext block, is
# added to a "fake 0th ciphertext block" called the initialization vector, or IV.
#
# Implement CBC mode by hand by taking the ECB function you wrote earlier, making
# it encrypt instead of decrypt (verify this by decrypting whatever you encrypt to
# test), and using your XOR function from the previous exercise to combine them.
#
# The file here is intelligible (somewhat) when CBC decrypted against
# "YELLOW SUBMARINE" with an IV of all ASCII 0 (\x00\x00\x00 &c)
#
# Don't cheat.
# Do not use OpenSSL's CBC code to do CBC mode, even to verify your results.
# What's the point of even doing this stuff if you aren't going to learn from it?
# pseudocode
#
# Encrypt:
# Assign IV vector
# XOR together
# ECB first block
# XOR together
# ECB second block
# repeat until done
# Decrypt:
# Read last block
# ECB decrypt it
# Read previous block
# XOR against plaintext
# Continue until done
from Crypto.Cipher import AES
from base64 import b64decode
aeskey = 'YELLOW SUBMARINE'
ciphertext = b64decode(open('10.txt', 'r').read())
iv = chr(0)*16
if len(ciphertext) % 16 != 0:
raise Exception('String is not a list of 16-byte blocks')
def xor(s1, s2):
result = ''
if len(s1) != len(s2):
raise Exception('Strings to XOR are different lengths')
for i in range(len(s1)):
result += chr(ord(s1[i]) ^ ord(s2[i]))
return result
def blockify(s, blocklen):
return [s[i:i+blocklen] for i in range(0, len(s), blocklen)]
def aescbc_decrypt(iv, s, key):
aesobj = AES.new(key, AES.MODE_ECB)
blocks = blockify(s, 16)
blocks.insert(0,iv)
ret = []
for i in range(1, len(blocks), 1):
a = aesobj.decrypt(blocks[len(blocks)-i])
b = blocks[len(blocks)-i-1]
ret.insert(0,xor(a, b))
return ''.join(ret)
if __name__ == '__main__':
print aescbc_decrypt(iv, ciphertext, aeskey)
| true |
8be0d2e9a8d67dcad48786a68b37d216bee1b28d | cdean00/PyNet | /pynetweek4_excersise3.py | 1,361 | 4.21875 | 4 | """
Week 4, Excersise 3
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
III. Create a program that converts the following uptime strings to a time in seconds.
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
For each of these strings store the uptime in a dictionary using the device name as the key.
During this conversion process, you will have to convert strings to integers. For these string to integer conversions use try/except to catch any string to integer conversion exceptions.
For example:
int('5') works fine
int('5 years') generates a ValueError exception.
Print the dictionary to standard output.
"""
uptime1 = 'twb-sf-881 uptime is 6 weeks, 4 days, 2 hours, 25 minutes'
uptime2 = '3750RJ uptime is 1 hour, 29 minutes'
uptime3 = 'CATS3560 uptime is 8 weeks, 4 days, 18 hours, 16 minutes'
uptime4 = 'rtr1 uptime is 5 years, 18 weeks, 8 hours, 23 minutes'
uptime1_weeks = uptime1[uptime1.find("weeks")-2]
uptime1_days = uptime1[uptime1.find("days")-2] | true |
aa7924e7483d1757d0ebf8e3b8ed6008f143060d | nilskingston/String-Jumble | /stringjumble.py | 1,277 | 4.28125 | 4 | """
stringjumble.py
Author: Nils Kingston
Credit: Roger
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, but letters within each word in
the correct order.
* With all words in correct order, but letters reversed within
the words.
Output of your program should look like this:
Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
string = input("Please enter a string of text (the bigger the better): ")
print('You entered "'+string+'". Now jumble it: ')
b = list(string)
b.reverse()
for x in b:
print(x, end="")
print()
words = string.split()
words.reverse()
for y in words:
print(y, end=" ")
print()
swim = string.split()
for w in swim:
f = list(w)
f.reverse()
print(''.join(f), end=" ")
| true |
a60fd066512a2fe60e465b8556d046b344e94dc3 | Kalpesh14m/Python-Basics-Code | /Basic Python/8 Function.py | 756 | 4.34375 | 4 | # The idea of a function is to assign a set of code, and possibly variables, known as parameters, to a single bit of text.
# You can think of it a lot like why you choose to write and save a program, rather than writing out the entire program every time you want to execute it.
#
# To begin a function, the keyword 'def' is used to notify python of the impending function definition, which is what def stands for.
# From there, you type out the name you want to call your function.
# It is important to choose a unique name, and also one that wont conflict with any other functions you might be using.
# For example, you wouldn't want to go calling your function print.
def example():
print('this code will run')
z = 3 + 9
print(z)
example()
| true |
124765cd61ad7ba8518b3027531cfc5b535ad353 | Kalpesh14m/Python-Basics-Code | /Basic Python/TKinter/33 Tkinter intro.py | 1,268 | 4.3125 | 4 | """
The tkinter module is a wrapper around tk, which is a wrapper around tcl, which is what is used to create windows and graphical user interfaces.
Here, we show how simple it is to create a very basic window in just 8 lines.
We get a window that we can resize, minimize, maximize, and close! The tkinter module's purpose is to generate GUIs.
Python is not very popularly used for this purpose, but it is more than capable of doing it.
"""
"Simple enough, just import everything from tkinter."
from tkinter import *
"""
Here, we are creating our class, Window, and inheriting from the Frame class.
Frame is a class from the tkinter module.
(see Lib/tkinter/__init__)
Then we define the settings upon initialization. This is the master widget."""
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
"""The above is really all we need to do to get a window instance started.
Root window created.
Here, that would be the only window, but you can later have windows within windows.
"""
root = Tk()
"Then we actually create the instance."
app = Window(root)
"Finally, show it and begin the mainloop."
root.mainloop()
"The above code put together should spawn you a window that looks like:"
| true |
b4b3bff8bf1922b70e8d3e38af1fbb69e30f318e | smrmkt/project_euler | /problem_001.py | 822 | 4.21875 | 4 | #!/usr/bin/env python
#-*-coding:utf-8-*-
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
import timeit
# slow
# simple loop
def loop(n):
t = 0
for i in range(1, n+1):
if i % 3 == 0 or i % 5 == 0:
t += i
return t
# fast
# calculate each numbers' sum and subtract common multiplier
def calc(n):
t03 = 3*(n/3)*(n/3+1)/2
t05 = 5*(n/5)*(n/5+1)/2
t15 = 15*(n/15)*(n/15+1)/2
return t03 + t05 - t15
if __name__ == '__main__':
print loop(999)
print calc(999)
print timeit.Timer('problem_001.loop(999)', 'import problem_001').timeit(100)
print timeit.Timer('problem_001.calc(999)', 'import problem_001').timeit(100)
| true |
262e88040edd2f5724ed93e282e5945b07d52d01 | ismailasega/Python_Cert_2019 | /Python Basics/Q2.py | 267 | 4.28125 | 4 | #accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically.
str = input("type 7 names, then press enter: \n ")
names = str.split()
names.sort()
print("The names in alphabetic order:")
for name in names:
print(name) | true |
833c17c00e98c40643bf0db2a04220a48e77b7a2 | ismailasega/Python_Cert_2019 | /Data visualisation/CaseStudy1/Qn1.py | 616 | 4.34375 | 4 | # You are given a dataset, which is present in the LMS, containing the number of
# hurricanes occurring in the United States along the coast of the Atlantic. Load the
# data from the dataset into your program and plot a Bar Graph of the data, taking
# the Year as the x-axis and the number of hurricanes occurring as the Y-axis.
import pandas as pd
import matplotlib.pyplot as plt
data_set = pd.read_csv("Hurricanes.csv")
print(data_set)
height = [3, 12, 5, 18, 45]
plt.bar(data_set, height=height)
plt.title(' Hurricanes Bar Graph')
plt.xlabel('Year')
plt.ylabel('The number of hurricanes occurring')
plt.show()
| true |
177170fd7f050b898cb18642d6e22e9ab45dccad | Falsaber/mhs-python | /Basics Tutorial #1 - Python.py | 2,065 | 4.125 | 4 | #This is a comment.
#Comments are ignored during code activation.
print("The shell will print what is contained within this area.")
var = input("var will now become a variable that can be called upon later. var is now:")
print(var)
#This will print the text in the variable "var" and require a response.
#input asks for a response to the text provided.
if var == "a variable":
print("Correct! Nice job.")
elif var == "why should I care":
print("Now, now, you WANT to pass thic class, right? Right???")
else:
print("Come on, the answer was right there in front of you!")
#This will cause different text to print based on your answer to the input text.
#If you answer correctly, the "if" statement will trigger, if you don't, "else" will trigger.
print("=-" * 30)
#This is a good way to make a divider, which will separate the printed text in the shell between before this point and after this point.
#Now, here's an example of all these components in action!
#Input Section
name = input("Your name:")
color = input("Your favorite color:")
sport = input("Favorite sport, if any:")
hobby = input("Favorite hobby:")
thundurus = input("PokeDex #642:")
#Divider
print("=-" * 60)
#Output
print("Your name is... " + name + "!")
print("Your favorite color is... " + color + "!")
print("Your favorite sport is... " + sport + "!")
print("Your favorite hobby is... " + hobby + "!")
if thundurus == "Thundurus":
print("That's right! Totally didn't use Google, right? =)")
elif thundurus == "Bulbasaur":
print("That's #1. You were close, though, only 641 Pokemon off!")
else:
print("Nope. That's fine, though, I didn't really expect you to know this off the top of your head.")
#Divider
print("=-" * 30)
#When this is used, a fully interactive questionnaire will start, which will ask you about your name, favorite color/sport/hobby, and what #642 in the PokeDex is.
#Try it out if you want!
#With this, you should have a basic understanding of "print", "input", variables and dividers. You should also understand if, elif, and else statements.
| true |
60db9080ef8cf89aed97749191a024bc2bb50e42 | jvillega/App-Academy-Practice-Problems-I | /SumNums.py | 456 | 4.4375 | 4 | #!/usr/bin/env python3
# Write a method that takes in an integer `num` and returns the sum of
# all integers between zero and num, up to and including `num`.
#
# Difficulty: easy.
# Precondition: num is a defined integer
# Postcondition: sum of all integers between zero and num are returned
def sumNums( num ):
total = 0
for x in range( num + 1 ):
total += x
return total
print( sumNums( 6 ) )
print( sumNums( 5 ) )
| true |
ea70a815fe1af0e4a9d744be5e65716583d905b0 | shefreyn/Exercise_1-100 | /Ex_(2).py | 498 | 4.21875 | 4 | print('__ Tip Calculator __')
totalBill = input('Total bill amount : ')
totalBill = int(totalBill)
percentage = input('Percentage you would like to tip : ')
percentage = int(percentage)
totalPeople = input('Total no of people you want to split the bill : ')
totalPeople = int(totalPeople)
tip = percentage/totalBill * 100
perPerson = totalBill/totalPeople
totalPerPerson = tip + perPerson
print(f"Each have to pay tip of {tip} and a bill amount of {perPerson} that is : {totalPerPerson}") | true |
7cf1e38bed3059b0e455ee77a91c394c7307b3d4 | gitBlackburn/Learn-Python-The-Hard-Way | /ex15.py | 614 | 4.21875 | 4 | # uses argv from the sys lib
# adds arguments
# from sys import argv
# # two arguments scripts and filename
# script, filename = argv
# # opens the text file and stores it in txt
# txt = open(filename)
# # notifies the user
# print "Here's your file %r:" %filename
# # reads the text file
# print txt.read()
# prompts the user for more action
print "Type the file name again:"
# stores the usrs imput in file_again
file_again = raw_input("> ")
# i think that this makes a references to txt
txt_again = open(file_again)
# shows the users the txt file again
print txt_again.read()
#txt.close
txt_again.close() | true |
84252e3008a9d3e59636948801cff89ef25ae676 | samfrances/coding-challenges | /codewars/6kyu/write_number_in_expanded_form.py | 875 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Solution to https://www.codewars.com/kata/5842df8ccbd22792a4000245/
You will be given a number and you will need to return it as a string in
Expanded Form. For example:
expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
"""
def expanded_form(num):
place_values = times10()
face_values = mods(num, 10)
face_with_place = zip(place_values, face_values)
expanded = filter(lambda x: x > 0, (f * p for (f, p) in face_with_place))
return ' + '.join(reversed([str(i) for i in expanded]))
def mods(num, divide_by):
while num != 0:
num, rem = num // divide_by, num % divide_by
yield rem
def times10():
n = 1
while True:
yield n
n *= 10
| true |
959d90c339a63bc8fe81a2c82cf03d06fed6a3d6 | samfrances/coding-challenges | /codewars/5kyu/calculating_with_functions.py | 1,685 | 4.40625 | 4 | #!/usr/bin/env python2
"""
Solution to https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39/
This time we want to write calculations using functions and get the results.
Let's have a look at some examples:
JavaScript:
seven(times(five())); // must return 35
four(plus(nine())); // must return 13
eight(minus(three())); // must return 5
six(dividedBy(two())); // must return 3
Ruby:
seven(times(five)) # must return 35
four(plus(nine)) # must return 13
eight(minus(three)) # must return 5
six(divided_by(two)) # must return 3
Requirements:
There must be a function for each number from 0 ("zero") to 9 ("nine")
There must be a function for each of the following mathematical
operations: plus, minus, times, dividedBy (divided_by in Ruby)
Each calculation consist of exactly one operation and two numbers
The most outer function represents the left operand, the most inner
function represents the right operand
Divison should be integer division,
e.g eight(dividedBy(three()))/eight(divided_by(three))
should return 2, not 2.666666...
"""
from operator import add, mul, floordiv, sub
def _number(n):
def numfunc(operator=None):
if operator:
return operator(n)
return n
return numfunc
def _operator(f):
def op(n):
def op_n(i):
return f(i, n)
return op_n
return op
zero = _number(0)
one = _number(1)
two = _number(2)
three = _number(3)
four = _number(4)
five = _number(5)
six = _number(6)
seven = _number(7)
eight = _number(8)
nine = _number(9)
plus = _operator(add)
minus = _operator(sub)
times = _operator(mul)
divided_by = _operator(floordiv)
| true |
f688003052f4e3dff5422dc4eb669322434fc3b4 | Biraja007/Python | /Looping-Statements.py | 1,423 | 4.625 | 5 | # Looping statements is used to repeatedly perform a block of operations.
# For loop: It is used to iterate over a sequence starting from first value to the last.
Numbers = [1,2,3,4,5]
for number in Numbers:
print (number , end=' ')
print()
print()
# While loop: It is used to repeatedly execute a block of statements as long as the condition mentioned holds true.
length = 1
while length <= 3:
print ("Value of the length is" , length )
length = length + 1
print()
# Nested loop: A loop within another loop is called as Nested loop.
adj = ["red" , "big" , "tasty"]
fruits = ["apple" , "banana" , "cherry"]
for x in adj:
for y in fruits:
print (x , y)
print()
# Break: Break is used to stop a loop from further execution.
length = 1
while length > 0:
if length == 3:
break
print ("Length =" , length)
length = length + 1
print()
# Continue: It is used to skip a particular iteration.
length = 1
while length <= 4:
if length == 2:
length = length + 1
continue
print ("Length =" , length)
length = length + 1
print ()
# Else: The block os statement in else block is executed if the break statement in the loop was executed.
length = 1
while length <= 3:
if length == 5:
break
print ("Length =" , length)
length = length + 1
else:
print ("Break statement was not executed")
| true |
027f5fd55ea60cddc723d52fd8bcba69789f7f8c | bondarum/python-basics | /examples/ex19_object_and_classes.py | 2,575 | 4.375 | 4 | # class
# Tell Python to make a new type of thing.
# object
# Two meanings: the most basic type of thing, and any instance of some thing.
# instance
# What you get when you tell Python to create a class.
# def
# How you define a function inside a class.
# self
# Inside the functions in a class, self is a variable for the instance/object being accessed.
# inheritance
# The concept that one class can inherit traits from another class, much like you and your parents.
# composition
# The concept that a class can be composed of other classes as parts, much like how a car has wheels.
# attribute
# A property classes have that are from composition and are usually variables.
# is-a
# A phrase to say that something inherits from another, as in a "salmon" is-a "fish."
# has-a
# A phrase to say that something is composed of other things or has a trait, as in "a salmon has-a mouth."
# A class definition can be compared to the recipe to bake a cake. A recipe is needed to bake a cake.
# The main difference between a recipe (class) and a cake (an instance or an object of this class) is obvious.
# A cake can be eaten when it is baked, but you can't eat a recipe, unless you like the taste of printed paper.
# Like baking a cake, an OOP program constructs objects according to the class definitions of the program program.
# A class contains variables and methods. If you bake a cake you need ingredients and instructions to bake the cake.
# Accordingly a class needs variables and methods.
# There are class variables, which have the same value in all methods and there are instance variables,
# which have normally different values for different objects. A class also has to define all the necessary methods,
# which are needed to access the data.
class Animal(object):
pass
class Dog(Animal):
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name):
self.name = name
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
class Fish(object):
pass
class Salmon(Fish):
pass
class Halibut(Fish):
pass
rover = Dog("Rover")
satan = Cat("Satan")
mary = Person("Mary")
mary.pet = satan
frank = Employee("Frank", 120000)
frank.pet = rover
flipper = Fish()
crouse = Salmon()
harry = Halibut()
| true |
2c0499d4e9b9a35f6b5157932fa2d58bcdf5f7d3 | bnsreenu/python_for_microscopists | /052-GMM_image_segmentation.py | 2,975 | 4.125 | 4 | #!/usr/bin/env python
__author__ = "Sreenivas Bhattiprolu"
__license__ = "Feel free to copy, I appreciate if you acknowledge Python for Microscopists"
# https://www.youtube.com/watch?v=kkAirywakmk
"""
@author: Sreenivas Bhattiprolu
NOTE: I was alerted by one of the viewers that m.bic part needs more explanation so here it is. Both BIC and AIC are included as built in methods as part of Scikit-Learn's GaussianMixture. Therefore we do not need to import any other libraries to compute these. The way you compute them (for example BIC) is by fitting a GMM model and then calling the method BIC. In the video I tried to achieve multiple things in one single line, compute BIC for each GMM calculated by changing number of components and also to plot them. Let me elaborate...
Instead of changing number of components in a loop let us compute one at a time, for example let us define n = 2. Then fit a gmm model for n=2 and then calculate BIC. The code would look like ...
import numpy as np
import cv2
img = cv2.imread("images/Alloy.jpg")
img2 = img.reshape((-1,3))
from sklearn.mixture import GaussianMixture as GMM
n = 2
gmm_model = GMM(n, covariance_type='tied').fit(img2)
#The above line generates GMM model for n=2
#Now let us call the bic method (or aic if you want).
bic_value = gmm_model.bic(img2) #Remember to call the same model name from above)
print(bic_value) #You should see bic for GMM model generated using n=2.
#Do this exercise for different n values and plot them to find the minimum.
Now, to explain m.bic, here are the lines I used in the video.
n_components = np.arange(1,10)
gmm_models = [GMM(n, covariance_type='tied').fit(img2) for n in n_components]
plt.plot(n_components, [m.bic(img2) for m in gmm_models], label='BIC')
Here, we are computing multiple GMM models each by changing n value from 1 to 10.
Then, for each n value we are computing bic via m.bic(img2) where m is replaced by gmm_models for each of the model generated. Think of this as typing gmm_model.bic(img2) each time you change n and generate a new GMM model.
I hope this explanation helps better understand the video content.
"""
import numpy as np
import cv2
#Use plant cells to demo the GMM on 2 components
#Use BSE_Image to demo it on 4 components
#USe alloy.jpg to demonstrate bic and how 2 is optimal for alloy
img = cv2.imread("images/BSE_Image.jpg")
# Convert MxNx3 image into Kx3 where K=MxN
img2 = img.reshape((-1,3)) #-1 reshape means, in this case MxN
from sklearn.mixture import GaussianMixture as GMM
#covariance choices, full, tied, diag, spherical
gmm_model = GMM(n_components=4, covariance_type='tied').fit(img2) #tied works better than full
gmm_labels = gmm_model.predict(img2)
#Put numbers back to original shape so we can reconstruct segmented image
original_shape = img.shape
segmented = gmm_labels.reshape(original_shape[0], original_shape[1])
cv2.imwrite("images/segmented.jpg", segmented)
| true |
15acd9528c16d6b48e195e8d34fec459cd356560 | hossainlab/numpy | /book/_build/jupyter_execute/notebooks/07_ChangingShapeOfAnArray.py | 1,828 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Array Shape Manipulation
# In[1]:
import numpy as np
# ### 1. Flattening
# In[2]:
a = np.array([("Germany","France", "Hungary","Austria"),
("Berlin","Paris", "Budapest","Vienna" )])
# In[3]:
a
# In[4]:
a.shape
# #### The ravel() function
# The primary functional difference is that flatten is a method of an ndarray object and hence can only be called for true numpy arrays. In contrast ravel() is a library-level function and hence can be called on any object that can successfully be parsed. For example ravel() will work on a list of ndarrays, while flatten will not.
# In[5]:
a.ravel()
# ##### T gives transpose of an array
# In[6]:
a.T
# In[7]:
a.T.ravel()
# ### 2. Reshaping
# reshape() gives a new shape to an array without changing its data.
# In[8]:
a.shape
# In[9]:
a.reshape(4,2)
# In[10]:
np.arange(15).reshape(3,5)
# In[16]:
np.arange(15).reshape(5,3)
# ##### The reshape() dimensions needs to match the number of values in the array
# Reshaping a 15-element array to an 18-element one will throw an error
# In[11]:
np.arange(15).reshape(3,6)
# #### Specify only one dimension (and infer the others) when reshaping
# Another way we can reshape is by metioning only one dimension, and -1. -1 means that the length in that dimension is inferred
# In[12]:
countries = np.array(["Germany","France", "Hungary","Austria","Italy","Denmark"])
countries
# ##### Here the unspecified value is inferred to be 2
# In[13]:
countries.reshape(-1,3)
# ##### Here the unspecified value is inferred to be 3
# In[14]:
countries.reshape(3,-1)
# ##### If the values of the dimensions are not factors of the number of elements, there will be an error
# In[15]:
countries.reshape(4,-1)
# In[ ]:
| true |
aa0b0faf17e8610c304726adae4c0ec31b4ecdc4 | subramario/Data_Structures_Algos_Practice | /Sorting/Quicksort.py | 1,711 | 4.15625 | 4 | #Classic quicksort - chooses the first element in the array as the pivot point and sorts accordingly
class Solution:
def partition(self, array, start, end):
# [start|low_ _ _ _ _ _high] --> Three pointers
pivot = array[start]
low = start + 1
high = end
while True:
# Continue iterating high and low pointers toward each other until an unsorted value is found or if pointers cross each other
while low <= high and array[low] <= pivot:
low = low + 1
while low <= high and array[high] >= pivot:
high = high - 1
# If both pointers have unsorted values, swap them into correct position, else if they have crossed each other, break
if low <= high:
array[low], array[high] = array[high], array[low]
else:
break
# Sort the pivot value into its respective place by switching with high/low pointer
array[start], array[high] = array[high], array[start]
return high # Note: values are swapped, but pointer locations are the same! Return the location of the now sorted pviot
def quicksort(self,array,start,end):
if start >= end:
return
p = self.partition(array, start, end) #Retrieves the index of the pivot point after each sort
self.quicksort(array, start, p-1) #Recursively sorts array on left side of the pivot
self.quicksort(array, p+1, end) #Recursively sorts array on right side of the pivot
array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
quick = Solution()
quick.quicksort(array, 0, len(array)-1)
print(array) | true |
a0e48325dedb2e416c7ac28f68cf33202886cdc5 | laomao0/Learn-python3 | /Function/ex20.py | 876 | 4.125 | 4 | from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
# Each time you do f.seek(0) you're moving to the start of the file
# seek(0) moves the file to the 0 byte(first byte) in the file
def rewind(f):
f.seek(0)
# each time you do f.readline() you're reading a line from the file and
# moving the read head to right after the \n that ebds that line.
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file) | true |
cfe855ef9cdf7a05a083fd5c3b39ef1b20e16589 | sushmitaraii1/Python-Datatypes-Fucntions | /Function/15.py | 226 | 4.15625 | 4 | # 15. Write a Python program to filter a list of integers using Lambda.
lst = [1, 5, 6, 4, 8, 5, 6, 9, 5, 3, 5, 9]
sorted_list = list(filter(lambda x:x%2==0,lst))
print("The even numbers from list are: ")
print(sorted_list) | true |
158c692aa383ca6f426cabf70d2dc45db3de20b5 | sushmitaraii1/Python-Datatypes-Fucntions | /Function/16.py | 319 | 4.25 | 4 | # 16. Write a Python program to square and cube every number in a given list of
# integers using Lambda.
lst = [1, 5, 6, 4, 8, 5, 6, 9, 5, 3, 5, 9]
print(lst)
print("After squaring items.")
square = list(map(lambda x:x**2,lst))
print(square)
print("After cubing items.")
cube = list(map(lambda x:x**3,lst))
print(cube) | true |
f3a5622a1badea10083c9a1990aefbcdef124dfa | sushmitaraii1/Python-Datatypes-Fucntions | /Datatype/2.py | 480 | 4.40625 | 4 | # 2. Write a Python program to get a string made of the first 2 and the last 2 chars
# from a given a string. If the string length is less than 2, return instead of the empty string.
# Sample String : 'Python'
# Expected Result : 'Pyon'
# Sample String : 'Py'
# Expected Result : 'PyPy'
# Sample String : ' w'
# Expected Result : Empty String
sample = input("Enter a string: ")
if len(sample) >= 2:
newchar = sample[:2] + sample[-2:]
print(newchar)
else:
print("")
| true |
8ccf58ee6e37889d78fff8fdc2a21a5ec99c10e3 | sushmitaraii1/Python-Datatypes-Fucntions | /Function/17.py | 201 | 4.125 | 4 | # 17. Write a Python program to find if a given string starts with a given character
# using Lambda.
start = lambda x: True if x.startswith('P') else False
print(start('Python'))
print(start('Java'))
| true |
e089c675631f21a21b35ab49e805bc7016d337f1 | jingyiZhang123/leetcode_practice | /dynamic_programming/62_unique_paths.py | 824 | 4.1875 | 4 | """
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
"""
class Solution(object):
def uniquePaths(self, m, n):
if not m or not n:
return 0
board = [[0 for j in range(n)] for i in range(m)]
for i in range(n):
board[0][i] = 1
for i in range(m):
board[i][0] = 1
for i in range(1, m):
for j in range(1,n):
board[i][j] = board[i-1][j] + board[i][j-1]
return board[m-1][n-1]
print(Solution().uniquePaths(0,1))
| true |
2b31d4a4790e35c9d384e9c8f3e8c1bd3eb19696 | jingyiZhang123/leetcode_practice | /recursion_and_backtracking/17_letter_combinations_of_a_phone_number.py | 1,025 | 4.15625 | 4 | """
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
2: abc
3: def
4: ghi
5: jkl
6: mno
7: pqrs
8: tuv
9: wxyz
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
"""
mapping = {'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'}
class Solution(object):
def _comb(self, soFar, rest):
if not rest:
if soFar: self.result.append(soFar)
return
for char in mapping[rest[0]]:
next = char
remaining = rest[1:]
self._comb(soFar+next, remaining)
def letterCombinations(self, digits):
self.result = []
self._comb("", digits)
return self.result
print(Solution().letterCombinations(''))
| true |
830e22e15f52ce5d1d0eb65a39c1ea345caadf5a | gokarna123/Gokarna | /classwork.py | 333 | 4.125 | 4 | from datetime import time
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.append(value)
num.sort()
print(num)
num=[]
x=int(input("Enter the number:"))
for i in range(1,x+1):
value=int(input(" Please Enter the number: "))
num.reverse()
print(num)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.