blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
88cb18925a67570cc548a039b40ea70fcf473889 | Woutah/AutoConvert | /timer.py | 2,290 | 4.25 | 4 | """Simple timer which can be used to get the wall/cpu time of a process.
Implements the "with x:" to measure timings more easily.
"""
from time import process_time
import time
class CpuTimer:
def __init__(self):
self._start_time = process_time()
self._paused = True
self._pause_time = process_time()
self._paused_time = 0
def start_timer(self):
if self._paused:
self._paused = False
self._paused_time = process_time() - self._pause_time
else:
print("Warning: timer has already started")
def __enter__(self):
self.start_timer()
def __exit__(self, exc_type, exc_value, tb):
self.pause_timer()
def pause_timer(self):
if self._paused:
print("Warning: timer already paused")
else:
self._paused = True
self._pause_time = process_time()
def get_time(self) -> float:
if self._paused: #If current paused time needs to be subtracted as well
return process_time() - self._start_time - self._paused_time - (process_time() - self._pause_time)
else: #If only total paused time needs to be subtracted
return process_time() - self._start_time - self._paused_time
class WallTimer:
def __init__(self):
self._start_time = time.time()
self._paused = True
self._pause_time = time.time()
self._paused_time = 0
def __enter__(self):
self.start_timer()
def __exit__(self, exc_type, exc_value, tb):
self.pause_timer()
def start_timer(self):
if self._paused:
self._paused = False
self._paused_time = time.time() - self._pause_time
else:
print("Warning: timer has already started")
def pause_timer(self):
if self._paused:
print("Warning: timer already paused")
else:
self._paused = True
self._pause_time = time.time()
def get_time(self) -> float:
if self._paused: #If current paused time needs to be subtracted as well
return time.time() - self._start_time - self._paused_time - (time.time() - self._pause_time)
else: #If only total paused time needs to be subtracted
return time.time() - self._start_time - self._paused_time
if __name__ == "__main__":
print("Now testing timer")
thetimer = CpuTimer()
print(thetimer.get_time())
thetimer.start_timer()
time.sleep(1.0)
thetimer.pause_timer()
for i in range(100000):
print("kaas")
print(thetimer.get_time())
print("Done")
| true |
8c25a31f8dd7dba671150a51ef052880bdc5c402 | Garce09/ShirleysMentees | /logic_recursion.py | 1,856 | 4.375 | 4 | ############ Q1. Ask the user for an integer, multiply it by itself + 1, and print the result
# Topic: user input
############ Q2. Ask the user for an integer
# If it is an even number, print "even"
# If it is an odd number, print "odd"
# Topic: conditionals, user input
############# Q3. Iterate through each element in the list USING A FOR LOOP, add 5 to it, and print them
# Topic: loops + lists
numbers = [1, 2, 3, 4, 5]
# Code here
# ############# Q4. Iterate through the list and only print values that are divisible by 3 ############
# Topic: lists, loops, conditions, comparison operators
numbers = list(range(0, 500))
# Code Here
counter = 0
for number in numbers:
if number %2 == 0:
counter +=1
print(counter)
# ############# Q5. Iterate through the list and count the number of even numbers within the list ############
# Topic: lists, loops, conditions, comparison operators
numbers = list(range(0, 500))
# Code Here
############# Q6. Iterate through each element in the list, add 5 to it, and print them
# MUST USE A WHILE LOOP
# Topic: loops + lists
# Hint: You can use len() function
numbers = [1, 2, 3, 4, 5]
# Code here
i = 0
#run this for total # of elements in a list
while i < len(numbers):
print(numbers[i] + 5)
print("ran", i + 1, "time(s)")
i += 1
############# Q7. For the following list:
# Print ALL numbers divisible by 7 and label them like so: "Divisible by 7: 70"
# Print ALL numbers divisible by 3 and label them like so: "Divisible by 3: 6"
# Print ALL numbers divisible by 3 and 7 and label them like so: "Divisible by 3 and 7: 21"
############
# Topic: lists, loops, conditions, string concatenation
numbers = list(range(0, 500))
# Code here
| true |
b4eddaa8ceada22cdf3d2c3f12e441752cfb6425 | larlyssa/checkio | /home/house_password.py | 1,648 | 4.1875 | 4 | """
DIFFICULTY: ELEMENTARY
Stephan and Sophia forget about security and use simple passwords for everything. Help Nikola develop a password security check module. The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least one digit, as well as containing one uppercase letter and one lowercase letter in it. The password contains only ASCII latin letters or digits.
Input: A password as a string (Unicode for python 2.7).
Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean. In the results you will see the converted results.
Precondition:
re.match("[a-zA-Z0-9]+", password)
0 < len(password) ≤ 64
"""
def checkio(data):
length = len(data) >= 10
upper = False
lower = False
number = False
for character in data:
if character in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
upper = True
elif character in "abcdefghijklmnopqrstuvwxyz":
lower = True
elif character in "0123456789":
number = True
return upper and lower and number and length
#Some hints
#Just check all conditions
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio('A1213pokl') == False, "1st example"
assert checkio('bAse730onE4') == True, "2nd example"
assert checkio('asasasasasasasaas') == False, "3rd example"
assert checkio('QWERTYqwerty') == False, "4th example"
assert checkio('123456123456') == False, "5th example"
assert checkio('QwErTy911poqqqq') == True, "6th example"
| true |
f1053a896ab4d62501f8f1930514e2d0e2e08dde | RodrigoAk/exercises | /solutions/ex13.py | 545 | 4.3125 | 4 | '''
You are given a positive integer N which represents the number of steps
in a staircase. You can either climb 1 or 2 steps at a time. Write a function
that returns the number of unique ways to climb the stairs
'''
import math
def staircase(n):
spaces = n//2 + n % 2
num2 = n//2
answer = 0
while(spaces <= n):
answer += math.factorial(spaces) / \
(math.factorial(spaces-num2)*math.factorial(num2))
num2 -= 1
spaces += 1
return answer
print(staircase(4))
# 5
print(staircase(5))
# 8
| true |
74ec0c3112aea6992d54a59e2cec323143085df8 | hitanshkadakia/Python_Tutorial | /function.py | 1,419 | 4.75 | 5 | # Creating a Function
# In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
# Calling a Function
# To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
# Arguments
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
# Number of Arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
# Arbitrary Arguments, *args
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
# Keyword Arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
# Default Parameter Value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
# Return Values
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
# Passing a List as an Argument
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
# The pass Statement
def myfunction():
pass | true |
5f2b869fad97bd52b0381a4f95ebce15c54c6568 | hitanshkadakia/Python_Tutorial | /if-elsestatement.py | 711 | 4.21875 | 4 | #If statement
a = 33
b = 200
if b > a:
print("b is greater than a")
#elif
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
#One line if statement:
if a > b: print("a is greater than b")
#One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
#pass statement
#if statements cannot be empty
#but if you for some reason have an if statement with no content
#put in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass | true |
17aeb081b24147badad1e1945acae197fe287d43 | BawangGoh-zz/ELEC0088-Lab | /Exercise2.py | 1,122 | 4.125 | 4 | ## Part 1) Implement a DNS querying program that stores the mapping between the names
## into IP addresses. Explicitly define the name of the network into the databases
## Part 2) Allow for the user to query several types of NS record (NS, MX, etc).
# IP addresses query
def IPquery(dct, string):
return dct.get(string)
def NS_MX(dct, string):
if(string.find('NS') == True):
print(str(dct.get(string)))
else:
print(str(dct.get(string)))
def main():
## Part 1) Defining DNS query name and IP addresses databases
IPdatabase = {"www.ee.ucl.ac.uk": '144.82.8.143',
"www.google.com": '8.8.8.8'}
website = str(input("Enter a website: "))
print("Requested IP address: " + IPquery(IPdatabase, website))
print("Print all records: ")
print (IPdatabase)
## Part 2) Defining DNS query name and IP addresses for NS and MX databases
lookup = {'NS': {"www.bbc.co.uk": '212.58.244.26'},
'MX': {"www.google.com": '173.194.202.27'}}
dnstype = str(input("Enter type of lookup: "))
NS_MX(lookup, dnstype)
if __name__ == "__main__":
main() | true |
8a0a9d68892f0dbac3b8e55eb69e82f1788cc05e | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-4-Partition.py | 1,801 | 4.3125 | 4 | # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "right partition"; it does not need to appear between the left and right partitions.
# EXAMPLE
# Input:
# Output:
# 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition= 5]
# 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def append(self, x):
n = self
while n.next:
n = n.next
n.next = ListNode(x)
# recursion, time O(n), unstable
def partition1(n,x):
if not n.next:
return n,n
first, end = partition(n.next, x)
if n.val < x:
n.next = first
first = n
else:
end.next = n
n.next = None
end = n
return first, end
# maintain two lists and combine, O(n), stable
def partition2(n,x):
small = None
big = None
first = None
mid = None
while n:
if n.val < x:
if small:
small.next = n
small = small.next
else:
small = n
first = n
else:
if big:
big.next = n
big = big.next
else:
big = n
mid = n
n = n.next
small.next = mid
big.next = None
return first, big
# n = ListNode(3)
# n.append(5)
# n.append(8)
# n.append(5)
# n.append(10)
# n.append(2)
# n.append(1)
# n,_ = partition2(n,5)
# while n:
# print(n.val)
# n = n.next
| true |
6c3b5c12c863b87a0c1d0cdb3ddc164caafb5862 | jimsun25/python_practice | /turtle_race/main.py | 927 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_pos = [-75, -45, -15, 15, 45, 75]
turtles = []
for i in range(6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[i])
new_turtle.penup()
new_turtle.goto(x=-235, y=y_pos[i])
turtles.append(new_turtle)
if user_bet:
race_on = True
while race_on:
cur_turtle = random.choice(turtles)
cur_turtle.forward(random.randint(0, 5))
if cur_turtle.xcor() > 230:
race_on = False
win = cur_turtle.pencolor()
if win == user_bet:
print("You've won the bet!!!")
else:
print(f"You've lost. The {win} turtle is the winner.")
screen.exitonclick() | true |
b8ee4804c73a956a36f4b00d94d50551149a2ad5 | sdahal1/pythonoctober | /fundamentals/python_fun/bootleg_functionsbasic2.py | 1,213 | 4.65625 | 5 | # CountUP - Create a function that accepts a number as an input. Return a new list that counts up by 1, from 1 (as the 0th element) up to num (as the last element).
# Example: countup(5) should return [1,2,3,4,5]
# Print and Return - Create a function that will receive a list with three numbers. Print the second value and return the third.
# Example: print_and_return([1,2,3]) should print 2 and return 3
# Second times Length - Create a function that accepts a list and returns the product of the second value in the list times the list's length.
# Values less than third - Write a function that accepts a list and creates a new list containing only the values from the original list that are smaller than its 3rd value. Print how many values this is and then return the new list. If the list has less than 3 elements, have the function return False
# This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
| true |
1a03184e8ca72e019f6afc71915f90837ecf2c34 | spacecase123/cracking_the_code_interview_v5_python | /array_strings/1.2_reverse_string.py | 788 | 4.3125 | 4 | '''
Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string.
'''
def reverse(string):
'''reverse in place'''
string_len = len(string)
if string_len <= 1 : return string
last = string_len - 1
string = list(string)
for i in range(string_len / 2):
string[i], string[last - i] = string[last -i], string[i]
return "".join(string)
def reverse_words(string):
'''reverse words in a string'''
r = []
for words in string.split():
r.insert(0, words)
return [r for r in reversed(string.split())]
if __name__ == "__main__":
print reverse_words("see the dog jump")
print reverse('abcdefghijk')
print reverse('abcdefghij')
print reverse('ab')
print reverse('aaaabbb')
| true |
acf1238f2f25e2ba32b1c0086b1a75bcc0c6905a | gauravbachani/Fortran-MPI | /Matplotlib/tutorial021_plotColourFills.py | 1,484 | 4.15625 | 4 | # Plotting tutorials in Python
# Fill colours inside plots
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('default')
x = np.linspace(-2.0*np.pi, 2.0*np.pi, 201)
C, S = np.cos(x), np.sin(x)
plt.plot(x, C, color='g', label='Cosine')
plt.plot(x, S, color='r', label='Sine')
# Upper value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# curves can be in any order
# Simply: area above the curve from a reference above the curve
# plt.fill_between(x, S, 1)
# mid value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# Simply: area under the curve with the reference intersecting the curve
# plt.fill_between(x, 0, S)
# lower value fill: xvalues, Boundary Curve 1 and Boundary Curve 2
# Simply: area below the curve from a reference below the curve
# plt.fill_between(x, -1, S)
# Area between curves
# Simply: Area between the curves
# plt.fill_between(x, S, C, color='orange', alpha=0.3)
# Area between curves
# Limited regions
# plt.fill_between(x[20:41], C[20:41], S[20:41], color='red', alpha=0.7)
# Using where option
# plt.fill_between(x, C, S, where=C>=S, color='green', alpha=0.3)
# plt.fill_between(x, C, S, where=C<=S, color='red', alpha=0.3)
# using interpoldiff = C-S
plt.fill_between(x, C, S, where=(C>=S), color='green', alpha=0.3, interpolate=True)
plt.fill_between(x, C, S, where=(C<=S), color='red', alpha=0.3, interpolate=True)
plt.grid()
plt.legend()
plt.title('Sample Sine and Cosine curves')
plt.show() | true |
60a97cefda9fa31dda0b46740b8dc5de42bc17fe | StephenH69/CodeWars-Python | /8-total-amount-of-points.py | 1,606 | 4.25 | 4 | # Our football team finished the championship. The result of each match look like "x:y".
# Results of all matches are recorded in the collection.
# For example: ["3:1", "2:2", "0:1", ...]
# Write a function that takes such collection and counts the points of our team in the championship.
# Rules for counting points for each match:
# if x>y - 3 points
# if x<y - 0 point
# if x=y - 1 point
# Notes:
# there are 10 matches in the championship
# 0 <= x <= 4
# 0 <= y <= 4
def points(games):
total = 0
for x in games:
if x[0] > x[2]:
total += 3
elif x[0] == x[2]:
total += 1
return total
print(points(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']))
print(points(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']))
print(points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']))
print(points(['1:0', '2:0', '3:0', '4:0', '2:1', '1:3', '1:4', '2:3', '2:4', '3:4']))
print(points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']))
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2', '4:3']), 30)
# Test.assert_equals(points(['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4', '4:4']), 10)
# Test.assert_equals(points(['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4', '3:4']), 0)
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:0', '2:1', '1:3', '1:4', '2:3', '2:4', '3:4']), 15)
# Test.assert_equals(points(['1:0', '2:0', '3:0', '4:4', '2:2', '3:3', '1:4', '2:3', '2:4', '3:4']), 12)
| true |
57f3618fc797fa6bec6c896585f94685b2265337 | StephenH69/CodeWars-Python | /8-blue-and-red-marbles.py | 1,517 | 4.1875 | 4 | # You and a friend have decided to play a game to drill your
# statistical intuitions. The game works like this:
# You have a bunch of red and blue marbles. To start the game you
# grab a handful of marbles of each color and put them into the bag,
# keeping track of how many of each color go in. You take turns reaching
# into the bag, guessing a color, and then pulling one marble out. You
# get a point if you guessed correctly. The trick is you only have three
# seconds to make your guess, so you have to think quickly.
# You've decided to write a function, guessBlue() to help automatically
# calculate whether you should guess "blue" or "red". The function should take four arguments:
# the number of blue marbles you put in the bag to start
# the number of red marbles you put in the bag to start
# the number of blue marbles pulled out so far (always lower than the starting number of blue marbles)
# the number of red marbles pulled out so far (always lower than the starting number of red marbles)
# guessBlue() should return the probability of drawing a blue marble, expressed as a float.
# For example, guessBlue(5, 5, 2, 3) should return 0.6.
def guess_blue(blue_start, red_start, blue_pulled, red_pulled):
return((blue_start - blue_pulled)/((blue_start + red_start) - (blue_pulled + red_pulled)))
print(guess_blue(5, 5, 2, 3))
print(guess_blue(5, 7, 4, 3))
print(guess_blue(12, 18, 4, 6))
# guess_blue(5, 5, 2, 3), 0.6)
# guess_blue(5, 7, 4, 3), 0.2)
# guess_blue(12, 18, 4, 6), 0.4) | true |
7c86e26e0bea599be21bc9a00c788f2e9e63cef4 | VaishnaviBandi/6063_CSPP1 | /m4/p3/longest_substring.py | 1,431 | 4.3125 | 4 | '''Assume s is a string of lower case characters.
Write a program that prints the longest
substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring.
For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Note: This problem may be challenging.
We encourage you to work smart.
If you've spent more than a few hours on
this problem, we suggest that you move on
to a different part of the course.
If you have time, come back to this problem
after you've had a break and cleared your head.'''
def main():
"""This program prints the longest sequence of alphabets"""
STRING_INPUT = input()
STRING_A = STRING_INPUT + "!"
TEMP = ''
TEMP_1 = ''
BEG_VAL = 0
MOV_VAL = 1
LEN = len(STRING_A)
COUNT = 1
LENGTH = 1
while MOV_VAL <= LEN-1:
COUNT = 1
TEMP = STRING_A[BEG_VAL]
while STRING_A[BEG_VAL] <= STRING_A[MOV_VAL] and MOV_VAL < LEN:
COUNT = COUNT + 1
TEMP = TEMP+STRING_A[MOV_VAL]
BEG_VAL = MOV_VAL
MOV_VAL = MOV_VAL + 1
BEG_VAL = MOV_VAL
MOV_VAL = MOV_VAL + 1
if COUNT == LENGTH:
TEMP_1 = TEMP_1
if COUNT > LENGTH:
LENGTH = COUNT
TEMP_1 = ""
TEMP_1 = TEMP
print(TEMP_1)
if __name__ == "__main__":
main()
| true |
b61b666855df35a0968802a9018d3baf29187cc2 | VaishnaviBandi/6063_CSPP1 | /m22/assignment1/read_input.py | 426 | 4.375 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
"""python program to read multiple lines of text
input and store the input into a string."""
string = ''
no_of_lines = int(input())
for each_line in range(no_of_lines):
string = string + (input()) + "\n"
each_line += 1
print(string)
if __name__ == '__main__':
main()
| true |
264245a0748c7c261abf311076a164b9cd1f4379 | aaronspindler-archive/CSCI1030U | /Labs/lab04.py | 1,453 | 4.375 | 4 | #Date: October 8th 2015
#Practising printing the statment testing 1 2 3...
print("testing 1 2 3...")
#Printing numbers, variables, and num equations
x=8
print(x)
print(x*2)
#Defining other variable types
name = "Carla Rodriguez Mendoza"
length = 14.5
width = 7.25
#Printing statments
print("X: ")
print(x)
print("Name:", name)
#Printing nums attached to words
print("length:" + str(length))
print("width:",)
#Defining more variables
firstName = "Maya"
lastName = "Pandit"
age = 20
birthMonth = "December"
#Printing longer statments with multiple data types
print(firstName, lastName, "is", age, "years old. Her next birthday is in",birthMonth + ".")
#Inputing a number and then using if statments to determine what to print
num = int(input("Enter a number:"))
secretNum = 6
if(num > secretNum):
print("Lower")
elif(num < secretNum):
print("Higher")
elif(num == secretNum):
print("You got it!")
num = int(input("Enter a number:"))
if num >= 5 and num <= 10:
print "This number is between 5 and 10"
elif num < 5 or num >10:
print "This number is not between 5 and 10"
#Inputing a grade number and determining what grade letter is corresponds to
#using if statements
gradeNum = int(input("Enter a grade number:"))
if(gradeNum < 50):
print("F")
elif(gradeNum > 49 and gradeNum < 60):
print("D")
elif(gradeNum > 59 and gradeNum < 70):
print("C")
elif(gradeNum > 69 and gradeNum < 80):
print("B")
elif(gradeNum > 79):
print("A")
| true |
8e1997b194cd3c70b844333b9a91b1a8ffee002b | fergatica/python | /triangle.py | 578 | 4.21875 | 4 | from math import sqrt
def area(first, second, third):
total = (first + second + third) / 2
final = sqrt(total*(total-first)*(total-second)*(total-third))
return final
def main():
first = input("Enter the length of the first side: ")
first = float(first)
second = input("Enter the length of the second side: ")
second = float(second)
third = input("Enter the length of the third side: ")
third = float(third)
final = area(first, second, third)
print("The triangle's area is ", end="")
print("{:.1f}".format(final))
main()
| true |
e63094b8a8351924742363fd1e2517272fd2a7e2 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/114_flatten_binary_tree_to_linked_list.py | 1,223 | 4.40625 | 4 | # Given a binary tree, flatten it to a linked list in -place.
# For example, given the following tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# 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 flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None
stack = [root]
while stack:
curr = stack.pop()
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
if stack:
curr.right = stack[-1]
curr.left = None
"""
create stack with root in stack
traverse through the tree inorder (append right, append left)
if there's anything in the stack, then set curr.right to last element in stack
set curr.left to None
"""
| true |
e34f79a5dbe72d7e8fff2f46b5f89f9de50f673a | hjungj21o/Interview-DS-A | /lc_88_merge_sorted_arr.py | 959 | 4.21875 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space(size that is equal to m + n) to hold additional elements from nums2.
# Example:
# Input:
# nums1 = [1, 2, 3, 0, 0, 0], m = 3
# nums2 = [2, 5, 6], n = 3
# Output: [1, 2, 2, 3, 5, 6]
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
p = n + m - 1
p1 = m - 1
p2 = n - 1
while p1 >= 0 and p2 >= 0:
if nums2[p2] > nums1[p1]:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
if p2 >= 0:
nums1[:p+1] = nums2[:p2+1]
| true |
d647fc1babadb96e9d4268d9cd97255efa479bc1 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/21_merge_sorted_list.py | 913 | 4.15625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l2.val > l1.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
"""
two pointers
create a dummy node
curr point to dummy
create a loop to iterate through both l1 and l2
if l2.val > l1.val:
dummy.next = l1
move l1 along
vice versa for l2
if there's any left over in l1 or l2, attach it to curr.next
return dummy.next
"""
| true |
a8242252ac207c8121d7f75859a97bcd9b873875 | orsnes-privatskole/python-oppgaver | /calculator-deluxe.py | 2,869 | 4.125 | 4 | import time
# Calculator - Deluxe Edition
# Name and version info
version_info = "MyCalculator - Deluxe Edition v0.3"
# Function for getting menu choice
def get_menu_choice():
# Variable used to align the menu to a common width
menu_width = 30
# List of available menu options
valid_menu_choice = ['+', '-', '*', '/', 'e']
# Loop until valid choice is made. If illegal input, ask the user again
while True:
print('\n')
print('*' * menu_width)
print("Welcome to " + version_info)
print('*' * menu_width)
print("Choose type of calculation or exit")
print('*' * menu_width)
print("* Addition: +")
print("* Subtraction: -")
print("* Multiplication: *")
print("* Division: /")
print("* Exit: e")
print('*' * menu_width)
choice = input("Please choose your option: ")
# If the user input is valid, exit the loop by returning from the function with the user choice
if choice in valid_menu_choice:
return choice
# If the user did not input a valid choice, inform about valid options, and ask again
else:
print(f"\n\t** Illegal menu option, please use one of {valid_menu_choice}")
time.sleep(1)
# Function for reading in a number, and ensuring that the input is valid
def read_input_number():
while True:
input_number = input("Please input number: ")
if input_number.isdigit():
return int(input_number)
else:
print(f"\n\t** {input_number} is not valid, try again")
time.sleep(1)
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
def calculate(a, b, operator):
if operator == '+':
return addition(a, b)
elif operator == '-':
return subtraction(a, b)
elif operator == '*':
return multiplication(a, b)
elif operator == '/':
return division(a, b)
# Variable for storing the user menu choice
menu_choice = get_menu_choice()
# Loop the whole program until the user choice is 'e' (exit)
while menu_choice != 'e':
# Get the two numbers from the user
number_a = read_input_number()
number_b = read_input_number()
# Calculate based on chosen operator and input numbers
result = calculate(number_a, number_b, menu_choice)
# Print results of calculation
print(f"\n** Calculation {number_a} {menu_choice} {number_b} = {result}\n")
time.sleep(1)
menu_choice = get_menu_choice()
# The loop is finished and we exit the program
print(f"\nThank you for using {version_info}")
print("Goodbye")
| true |
deab4c799195b9bd5b92f3052f10a7ec2c1f1826 | MarcosRS/python_practice | /01_strings.py | 1,548 | 4.21875 | 4 | #escaping characters \' , \" , \t, \n, \\
alison = 'That is Alison\'s cat'
print(alison)
#you can also use raw string and everythig will be interpreted as a string
rawStr = r'nice \' \n \" dfsfsf '
print(rawStr)
# multiline strings. this iincludes new lines as tab directly. Useful when you have a large string
mul = '''
Once Upon a time
Little red hidding hood
was walking in the forrest.
And you know the rest :D
'''
print(mul)
# You can use lists/array list in strings too:
print(alison[0])
print(alison[1:])
print(alison[-1])
print('al' in alison)
print('123' not in alison)
# String Methods
strText = 'once upon! SHREK! donkey'
print(strText.upper())
print(strText.lower())
print(strText.title())
print(strText.isupper()) #boolean
print(strText.islower()) # boolean
print(strText.upper().isupper())
# Other methods : isalpha, isalnum, isdecimal,
# isspace, istitle, startswith, endswith,
# ljust, rjust (second argument specifies the fill character)
# center (second argument specifies the fill character)
# strip, rstrip, lstrip (removes spaces)
# replace (same :D)
#join example:
print (','.join(['cat', 'rat', 'bat']))
#split example
print('bat,mat,fat'.split(','))
#Additional: pyperclip (needs to be installed)
#pyperclip is used to grab
#pyperclip.copy() , copies to the clipboard
#pyperclip.paste() , brings back the text from the clipboard
# STING FORMATTING - Similar to templating
stingTest = 'nice' + 'coding'
name = 'Alice'
time = '10:00:'
print('%s You are invited to a party at %s' % (name, time))
| true |
c899ae39957dc75221110be441670016040002d4 | Rachelami/Pyton_day-1 | /ex 03.py | 291 | 4.125 | 4 |
num = 3
def is_even(number):
if isinstance(number, int) == True:
if number == num:
print("True")
return True
else:
print("False")
return False
else:
print ("This is NOT an integer")
exit()
is_even(5)
| true |
376c45f4b21df79d6505234d5d14f4e1e61411c7 | Akansha0211/PythonPrograms | /Assignment4.6.py | 1,295 | 4.40625 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation.
# The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly.
# Do not name your variable sum or use the sum() function.
def computepay(h,r):
try:
h = float(hrs)
r = float(rate)
except:
print("Error . please enter numeric input")
quit() # if we don't use quit it will again give us traceback instead of placing it inside except block
if (h > 40): # once got appropriate value (without traceback error)
grossPay = h * r + (h - 40) * 1.5 * r;
else:
grossPay = h * r
return grossPay
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
p = computepay(10,20) # invoke function
print("Pay",p) | true |
258d58764350aab386c1fd047b0d72ef47906114 | WangsirCode/leetcode | /Python/valid-parenthesis-string.py | 1,892 | 4.375 | 4 | # Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must have a corresponding left parenthesis '('.
# Left parenthesis '(' must go before the corresponding right parenthesis ')'.
# '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
# An empty string is also valid.
# Example 1:
# Input: "()"
# Output: True
# Example 2:
# Input: "(*)"
# Output: True
# Example 3:
# Input: "(*))"
# Output: True
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
left = []
star = []
if not s:
return True
for index, value in enumerate(s):
if value == '(':
left.append(index)
elif value == '*':
star.append(index)
else:
if left:
left.pop()
elif star:
star.pop()
else:
return False
if not left:
return True
elif len(left) > len(star):
return False
else:
index = -1
for i in left:
index +=1
if index == len(star):
return False
while(star[index] < i) :
index += 1
if index == len(star):
return False
return True
if __name__ == "__main__":
print(Solution().checkValidString("()*()**()(())(()()(())*)()((()**))()()()(((*(((*)))(**(())))*()*))()(()()(()))()((())(*()())())()(*")) | true |
327adc7432d621c66865248250a20d233671e2b9 | MuhammadAzizShobari/praxis-academy | /novice/02-01/latihan/kekekalan.py | 552 | 4.1875 | 4 | mutable_collection = ['Tim', 10, [4, 5]]
immutable_collection = ('Tim', 10, [4, 5])
# Reading from data types are essentially the same:
print(mutable_collection[2]) # [4, 5]
print(immutable_collection[2]) # [4, 5]
# Let's change the 2nd value from 10 to 15
mutable_collection[1] = 15
# This fails with the tuple
immutable_collection[1] = 15
immutable_collection[2].append(6)
print(immutable_collection[2]) # [4, 5, 6]
immutable_collection[2] = [4, 5]
# This throws a familiar error:
# TypeError: 'tuple' object does not support item assignment | true |
3c40edcb6143bd3a72febcac7c4e0f891e571e51 | roopi7760/WebServer | /Client.py | 2,797 | 4.125 | 4 | '''
Author: Roopesh Kumar Krishna Kumar
UTA ID: 1001231753
This is the Client program which sends the request to the server and displays the response
*This code is compilable only with python 3.x
Naming convention: camel case
Ref: https://docs.python.org/3/library/socket.html and https://docs.python.org/3/tutorial/index.html '''
import sys
import socket
import time
import datetime
#Method to print socket details
def PrintServerDetails(ServerAddress, ServerPort):
ServerDetails = socket.getaddrinfo(ServerAddress, ServerPort, proto=0) #This function returns a list of 5-tuples(family, type, proto, canonname, sockaddr)
print("Server socket family:", ServerDetails[0][0])
print("Server socket type:", ServerDetails[0][1])
print("Server name: " , socket.gethostbyaddr(ServerAddress)[0])
#End of method PrintServerDetails
#Main program starts here
try:
print("Client Started. . .\n")
ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket to connect to server
if(len(sys.argv) < 3): #Check whether the command line argument is less than 3. [argv[0]:File Name]
print("No or insufficient parameters recieved! \n")
ServerAddress = input("Enter the Server address: ") #Take the input from the user if the arguments are not sufficient.
ServerPort = int(input("Enter the port: "))
FileName = input("Enter the file you want request: ")
else: #if the command line argument is sufficient, then assign them to respective variables.
ServerAddress = (sys.argv[1])
ServerPort = int(sys.argv[2])
FileName = (sys.argv[3])
SendMsg = 'GET /'+FileName+ ' HTTP/1.1' #Prepare the header for the request
StartTime = datetime.datetime.now() #Mark the start time of the connection to calculate RTT
ClientSocket.connect((ServerAddress, ServerPort)) #Connect to the server
ClientSocket.sendall(SendMsg.encode()) #send the request to the server
ReplyFromServer = ClientSocket.recv(1024) #Recieve the request from the server
EndTime=datetime.datetime.now() #Mark the end time of the connection to calculate RTT
PrintServerDetails(ServerAddress,ServerPort)
print("Peer name: " , ClientSocket.getpeername() , "\n")
print("\nReply from the server: \n============\n")
print(ReplyFromServer.decode())
RTT = (EndTime - StartTime) #calculate the RTT
print("\nThe RTT is ", (RTT.total_seconds()) , " seconds or %.2f" %((RTT.total_seconds())*1000) , " milliseconds.") #print the RTT in seconds and milliseconds format
ClientSocket.close() #close the client socket
k = input("\nPress any key to exit") #close the program
except Exception as e:
print("Client encountered an error! Client is closing!\n",e)
'''End of the program'''
| true |
87a51c978d8891d80b1f1eafadbd0e7654e04237 | viseth89/nbapython | /trial.py | 1,042 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 19:06:19 2016
@author: visethsen
"""
import matplotlib.pyplot as plt
# Importing matplotlib general way that it is used
x1 = [1,2,3]
y1 = [4,7,5]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x1, y1, label = "first line")
plt.plot(x2, y2, label = 'second line')
plt.xlabel('this is the x label')
plt.ylabel('this is the y label')
plt.title('this is how we put the title')
plt.legend()
plt.show()
a1 = [1,2,3]
b1 = [4,7,5]
a2 = [1,2,3]
b2 = [10,14,12]
plt.plot(a1, b1, label = "third line")
plt.plot(a2, b2, label = 'fourth line')
plt.xlabel('this is the x label')
plt.ylabel('this is the y label')
plt.title('this is how we put the title')
plt.legend()
plt.show()
'''
plt.bar([1,3,5,7,9], [5,2,7,8,2], label='example numero 1')
plt.bar([2,4,6,8,10], [4,6,8,4,10], label='part 2', color='g')
plt.legend
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('bar graph title\nAnother Line Whoa')
plt.show()
# Plotting x and y which would be the data
'''
| true |
4b93a00e1ca8e27e19d5c723af42b9b2604d61f4 | NUbivek/PythonBootcamp | /Module6/ex1.py | 1,175 | 4.28125 | 4 | # Exercise 1.
# Write your Binary Search function.
# Start at the middle of your dataset. If the number you are searching for is lower,
#stop searching the greater half of the dataset. Find the middle of the lower half
#and repeat.
# Similarly if it is greater, stop searching the smaller half and repeat
# the process on that half. By continuing to cut the dataset in half,
#eventually you get your index number.
# Number to search for - 3 alist = [1,2,3,4,5,6,7]
def binary_search (user_input,x):
# user_input_lefthalf = 0
# user_input_righthalf = 0
mid = round(len(user_input)//2)
#print (mid)
#print (user_input[mid-1])
while len(user_input) > 1:
if x == user_input[mid-1]:
value = x
print("The value is {}", x)
return x
elif x < user_input[mid-1]:
start_point = user_input[0]
end_point = user_input[mid-1]
value = len(range(user_input[start_point:end_point]))//2
print (value)
return value
elif x > user_input[mid-1]:
start_point = user_input[mid-1]
end_point = user_input[:]
value = len(range(user_input[start_point:end_point]))//2
print (value)
return value
binary_search([1,2,3,4,5,6,7],6)
| true |
09fdf09fb3393d7081c02d4fb9fbf3efb81e14b0 | NUbivek/PythonBootcamp | /Module1/ex6.py | 748 | 4.28125 | 4 | ##Exercise 6: Write Python program to construct the following pattern, using a nested for loop.
def triangle():
temp_var = ""
for num in range(5):
temp_var += "*"
print(temp_var)
for num in range(5,0,-1):
temp_var = "*"
print(num * "*")
triangle()
##(optimized code below)
def triangle(number):
for num in range (1, number+1):
print (num*"*")
for num in range (number-1,0,-1):
print (num*"*")
triangle(6)
####
def triangle(number,character):
character_str = str(character)
for num in range (1, number+1):
print (num*character_str)
for num in range (number-1,0,-1):
print (num*character_str)
triangle(6,"$")
| true |
075507eb146a94e556b9fe135191c904a4e479ed | 4320-Team-2/endDateValidator | /endDateValidator.py | 1,352 | 4.34375 | 4 | import datetime
class dateValidator:
#passing in the start date provided by user
def __init__(self, startDate):
self.startDate = startDate
def endDate(self):
#loop until user provides valid input
while True:
#try block to catch value errors
try:
endDate = input("Enter the end Date (YYYY-MM-DD): ")
#splitting input to use with datetime module
d1 = self.startDate.split(('-'))
d2 = endDate.split('-')
#creating datetime objects
start = datetime.datetime(int(d1[0]),int(d1[1]),int(d1[2]))
end = datetime.datetime(int(d2[0]),int(d2[1]),int(d2[2]))
#error handling for end date before start date
if start == end:
print("[ERROR] Start date cannot be the same as end date\n")
elif start > end:
print("[ERROR] Start date cannot be after end date\n")
else:
print("Valid date input")
return end.date()
break
except ValueError:
print("[ERROR] Invalid date provided.\n")
#Error checking and example use
#date = dateValidator("1999-06-29")
#endDate = date.endDate() | true |
c72f07976c3d40c88fbef5a39d3bdab8f0a5f202 | divyashree-dal/PythonExercises | /Exercise22.py | 673 | 4.625 | 5 | '''Question 54
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with the same name in the super class.'''
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self,length):
Shape.__init__(self)
self.length = length
def area(self):
return self.length * self.length
asquare = Square(int(raw_input()))
print asquare.area() | true |
8fd1d34b6a98d4f171c8b7bd138f892a3861800e | deepakmethalayil/PythonCrash | /list_study.py | 785 | 4.125 | 4 | members = ['uthay', 'prsanna', 'karthick']
members_master = members
print(members) # print the entire list
print(members[0]) # print list items one by one
print(members[1])
print(members[2])
msg = "Hello!"
print(f"{msg},{members[0].title()}")
print(f"{msg},{members[1].title()}")
print(f"{msg},{members[2].title()}")
# Adding an element to the list
members.append('ratheesh')
print(members)
# Define an empty list
Grade = []
# removing items using del statement
del members[0]
print(members)
# Removing an Item Using the pop() Method
members.pop()
print(members)
members1 = members.pop(0)
print(members1)
# we can remove the items by value by remove command
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
| true |
0c885c721e116d2ed482bf53bae8590df0db711e | gauvansantiago/Practicals | /Prac_02/exceptions_demo.py | 1,020 | 4.46875 | 4 | # Gauvan Santiago Prac_02 Task_04 exceptions_demo
try:
# asks to input numerator and denominator
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
# while loop will prevent ZeroDivisionError and ask for a valid denominator
while denominator == 0:
print(print("Cannot divide by zero!"))
denominator = int(input("Enter the denominator: "))
# calculates the fraction and changes it to a number
fraction = numerator / denominator
print(fraction)
# Valid numbers meaning whole numbers without decimal points
except ValueError:
print("Numerator and denominator must be valid numbers!")
print("Finished.")
# When will a ValueError occur?
# A ValueError will occur if you put in a number with a decimal as an input
# When will a ZeroDivisionError occur?
# ZeroDivisionError occurs when you input 0 in either denominator and numerator as well as on both
# Could you change the code to avoid the possibility of a ZeroDivisionError?
# Yes
| true |
a26da98cd7f927a76810f2b9f97a60e896cbd5ee | Anjalibhardwaj1/GuessingGame | /GuessingGame.py | 2,370 | 4.28125 | 4 | #December 30 2020
#Guessing Game
#This program will pick a random number from 1 to 100, and
#it will ask the user to guess the number.
from random import randint
#Welcome Message and Rules
print("\n---------------------- Guessing Game ------------------------------")
print("Welcome!")
print("In this game I will think of a number, and you will try to guess it!\n")
#Start Game
ready = input("Are you ready to play? (Y/N)")
#If 'y' then start game otherwise, prompt and exit.
if ready.lower() == 'y':
print("\nGenerating a random number...")
#Randomly chose a number from 1 to 100
random_num = randint(1, 100)
#Initialize user Guess List
guess_list = [0]
#While True this code will loop and prompt the user for guesses
while True:
#Prompt user for their guess and convert to integer
user_guess = int(input('Enter Your Guess! \n'))
#If the user's guess is out of bounds, ask the user again.
if user_guess < 1 or user_guess > 100:
print('Please Enter a Number Between 1 and 100. \n')
continue
#If the user's guess is correct then prompt user, tell them their amount of tries and break out of loop
if user_guess == random_num:
print('Correct! It took you {} tries!'.format(len(guess_list)))
print("Play again next time!")
exit()
break
#Add user's guesses to guess_list
guess_list.append(user_guess)
#If there exists 3 values in the list compare the current value to the previous value
if guess_list[-2]:
#if the current value is closer to the random number prompt "WAMER!"
if abs(random_num-user_guess) < abs(random_num-guess_list[-2]):
print('WARMER!\n')
#Otherwise, print "COLDER!"
else:
print('COLDER!\n')
#otherwise check if user's guess is within 10 digits of the random number
else:
if abs(random_num - user_guess) <= 10:
print("WARM!\n")
else:
print("COLD!\n")
else:
print("...Come back next time")
exit()
| true |
ed294c0d77434c644a4805c6f7a04b1789e1019d | nbrown273/du-python-fundamentals | /modules/module11_list_comprehensions/exercise11.py | 1,384 | 4.34375 | 4 | # List Comprehension Example
def getListPowN(x, n):
"""
Parmaeters: x -> int: x > 0
n -> int: n >= 0
Generate a list of integers, 1 to x, raised to a power n
Returns: list(int)
"""
return [i**n for i in range(1, x) if i % 2 == 0]
# Dictionary Comprehension Example
def getDictComprehension(keys, vals):
"""
Parameters: keys -> list(str)
vals -> tuple(int)
Generate a dictionary comprehension based on a list and tuple
Returns: dict
"""
return {key: val for key, val in zip(keys, vals)}
################################################################################
"""
TODO: Write a function that follows the criteria listed below
The purpose of this function is to generate a dictionary object whose
keys and values follow the criteria below:
* Function should take in a parameter "letters", where "letters" is a
list of strings of length 1
* Function should take in a parameter "lengths", where "lengths" is a
list of ints >= 0
* The length of "letters" and "lengths" have to be equal
* If the lengths of "letters" and "lengths" are not equal, return the
an error message
Example:
letters=["a", "b", "c", "d"]
lengths=[0, 1, 2, 3]
returns {"a0": "", "b1": "b", "c2": "cc", "d3": "ddd"}
""" | true |
2cad47a5a9905de6a6dfc562e71db4f8a6e66ac9 | manmodesanket/hackerrank | /problem_solving/string.py | 683 | 4.34375 | 4 | # You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
#
# For Example:
#
# Www.HackerRank.com → wWW.hACKERrANK.COM
# Pythonist 2 → pYTHONIST 2
# Input Format
#
# A single line containing a string .
#
# Constraints
#0<=len(s)<=1000
#
# Output Format
#
# Print the modified string .
#
# Sample Input 0
#
# HackerRank.com presents "Pythonist 2".
# Sample Output 0
#
# hACKERrANK.COM PRESENTS "pYTHONIST 2".
def swap_case(s):
a=""
for i in s:
if i.islower()==True:
a+=(i.upper())
else :
a+=(i.lower())
return a
s=input()
a=swap_case(s)
print(a) | true |
4d97da83215734d677dd6b7bc15c527b9e6ee262 | srs0447/Basics | /8-calculator.py | 817 | 4.15625 | 4 | # Basic calculator that do the basic calculations like addition, subtraction, multification etc
# declaring the global variables
print("This is the basic calculator")
print("\n********************************************\n")
print("$$$$$$^^^^^^********^^^^^^^$$$$$$$$$$")
number1 = float(input('Please Enter the first number \n'))
operator = str(input("Please select the operator \n"))
number2 = float(input("Please enter the second number \n"))
def add():
print(number1 + number2)
def sub():
print(number1 - number2)
def mult():
print(number1 * number2)
def devide():
print(number1 / number2)
if(operator == "+"):
add()
elif(operator == "-"):
sub()
elif(operator == "*"):
mult()
elif(operator == "/"):
devide()
else:
print("Wrong operator !. Please select the currect operator..") | true |
ffb5acfef7395967bfc3a8d62fb981768ef6bae4 | anish-lakkapragada/libmaths | /libmaths/trig.py | 2,884 | 4.28125 | 4 | #Developer : Vinay Venkatesh
#Date : 2/20/2021
import matplotlib.pyplot as plt
import numpy as np
def trigsin(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.sin(b * x)
yint = z * np.sin(b * 0)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}sin({b}x)')
plt.title('Sine Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
def trigcos(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.cos(b * x)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}cos({b}x)')
plt.title('Cosine Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
def trigtan(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine-cosine-tangent.html
'''
x = np.linspace(-np.pi,np.pi,100)
# the function, which is y = sin(x) here
y = z * np.tan(b * x)
# setting the axes at the centre
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
if z < 0:
plt.ylim((z*1.5,-z*1.5))
else:
plt.ylim((-z*1.5,z*1.5))
# plot the functions
plt.plot(x,y, 'b', label=f'y={z}tan({b}x)')
plt.title('Tangent Graph')
plt.legend(loc='upper left')
# show the plot
plt.show()
| true |
9d59edf273a76e409ca5ba7a6898c50d130d43c7 | khanmaster/python_modules | /exception_handling.py | 1,246 | 4.1875 | 4 | # We will have a look at the practical use cases and implementation of try, except, raise and finally
we will create a variable to store a file data using open()
Iteration 1
try: # let's use try block for a 1 line of code where we know this will throw an error
file = open("orders.text")
except:
print(" Panic Alert!!!! ")
# Iteration 2
try:
file = open("orders.text")
except FileNotFoundError as errmsg: # creating an alais for FileNotFound Error in except block
print("Alert something sent wrong" + str(errmsg))
# if we still wanted them to see the actual exception together with our customised message
raise # raise will send back the actual exception
finally: # finally will execute regardless of the above conditions
print(" Hope you had a good Customer experience, please visit again")
# import json
#
# car_data = {"name": "tesla", "engine": "electric"} # dic
#
# print(type(car_data))
#
#
# car_data_json_string = json.dumps(car_data) #
# print(type(car_data_json_string))
#
# with open("new_json_file.json", "w") as jsonfile:
# json.dump(car_data, jsonfile)
#
# with open("new_json_file.json") as jsonfile:
# car = json.load(jsonfile)
# print(car['name'])
# print(car['engine'])
| true |
60e0fa3af1eca5fbd52590f7622545097db1a8be | jxhangithub/lintcode | /Tree/480.Binary Tree Paths/Solution.py | 1,853 | 4.15625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
self.result = []
if not root:
return self.result
self.dfs(root, "")
return self.result
def dfs(self, root, path):
# dfs has reached the leaf node, add path to result
if root.left is None and root.right is None:
path = path + str(root.val)
self.result.append(path)
return
# turn left
if root.left:
self.dfs(root.left, path + str(root.val) + "->")
# turn right
if root.right:
self.dfs(root.right, path + str(root.val) + "->")
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
# Traverse
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
result = []
if not root:
return result
self._traverse(root, result, [str(root.val)])
return result
def _traverse(self, root, result, path):
if root.left is None and root.right is None:
result.append("->".join(path))
return
if root.left:
path.append(str(root.left.val))
self._traverse(root.left, result, path)
path.pop()
if root.right:
path.append(str(root.right.val))
self._traverse(root.right, result, path)
path.pop()
| true |
1708d66404362fb9a0e18008e6e500453235a49e | chandnipatel881/201 | /chap3.py | 407 | 4.25 | 4 | print "This program illustrates average of numbers"
# total_num = input ("How many numbers you want to average : ")
# sum = 0.0
#
# for i in xrange(total_num):
# sum = sum + input("Enter: " )
# average = sum/total_num
# print average
avg = 0.0
count = 0
while True:
total = avg * count
num = input("Enter : ")
count = count + 1
total = total + num
avg = total/count
print avg
| true |
d4b2cdb089e531181f30b6130d915878bd5744ef | Aiswarya333/Python_programs | /const5.py | 1,595 | 4.1875 | 4 | '''CELL PHONE BILL - A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs
$0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the entire bill
(including the 911 charge) is subject to 5 percent sales tax.
Write a program that reads the number of minutes and text messages used in a month from the user. Display
the base charge, additional minutes charge (if any), additional text message charge (if any), the 911 fee, tax and total bill amount. Only display the additional
minute and text message charges if the user incurred costs in these categories. Ensure that all of the charges are displayed using 2 decimal places.'''
min=int(input('ENTER THE NUMBER OF MINUTES :'))
msg=int(input('ENTER THE NUMBER OF MESSAGES :'))
BASE_COST=15.00
MSG_COST=0.15
CALL_COST=0.25
accost=0.0
amcost=0.0
if min>50:
accost=(min-50)*CALL_COST
if msg>50:
amcost=(msg-50)*MSG_COST
center=amcost+accost+BASE_COST+0.44
tax=(BASE_COST+amcost+accost+center)*5/100
total=tax+BASE_COST+amcost+accost+center
print('''
BASE CHARGE : %.2f
ADDITIONAL MINUTES CHARGE : %.2f
ADDITIONAL TEXT CHARGE : %.2f
911 FEE : %.2f
TAX : %.2f
------------------------------------------
TOTAL BILL AMOUNT : %.2f
''' %(BASE_COST,accost,amcost,center,tax,total))
| true |
38f3243733f0a36e5c2ca109f986f9fdc94cd9f0 | ed4m4s/learn_python_the_hard_way | /Exercise18.py | 569 | 4.1875 | 4 | #!/usr/bin/python
# Exercise on Names, Variables, Code, Functions
# this one is like the scripts we did with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Take out the *args as you do not need it
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Takes one argument only
def print_one(arg1):
print "arg1: %r" % arg1
# No arguments at all.
def print_none():
print "I got no arguments"
print_two("Zed", "Shaw")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none()
| true |
1f024b3de44ee95d07ab6b44a2c3fcf22079ba09 | pioziela/programming-learning | /Hacker_Rank_Exceptions.py | 965 | 4.25 | 4 | import sys
def divide_exceptions():
"""
divide_exceptions function trying to divide two values.
The user provides data in the following format:
- in the first line the number of divisions to be carried out,
- in the following lines, the user provides two values to divide, the values should be separated by a space.
The function returns a division result or a corresponding error.
"""
line_number = 0
number_of_lines = int(sys.stdin.readline())
while line_number < number_of_lines:
numbers_to_divide = list(map(str, sys.stdin.readline().rstrip().split()))
try:
print(int(numbers_to_divide[0]) / int(numbers_to_divide[1]))
except ZeroDivisionError:
print("Error Code: integer division or modulo by zero")
except ValueError as invalid_literal:
error = f"Error Code: {invalid_literal}"
print(error)
line_number += 1
divide_exceptions()
| true |
a1b191446e960f38e7e6621275d85ac7629d0368 | geetha10/GeeksForGeeks | /basic/factorial.py | 317 | 4.25 | 4 | def factorial(num):
result = 1
for x in range(1, num+1):
result = result*x
return result
num = input("Enter a number for finding factorial")
if num.isdigit():
num = int(num)
fact = factorial(num)
print(f"Factorial of {num} is {fact}")
else:
print("Please enter a valid Integer")
| true |
721b2651ffb8c02d09a2130810f3baf3294c48ec | jayantpranjal0/ITW1-Lab | /python-assignments/3/4.py | 219 | 4.375 | 4 | '''
Python program to read last n lines of a file.
'''
with open("test.txt", "r") as f:
n = int(input("Enter number of lines from last to read: "))
for i in f.readlines()[-n:]:
print(i, end = "") | true |
4bc1c71828f44dda49523303fa15adc3ba9ed9d3 | jayantpranjal0/ITW1-Lab | /python-assignments/1/14.py | 213 | 4.21875 | 4 | '''
Python program to get the number of occurrences of a specified element in an array.
'''
l = input("Enter the array: ").split()
e = input("Enter the element: ")
print("No of occurence: "+str(l.count(e))) | true |
01fe18819e29ae6806c6392f384ce6cbc39c81b7 | KarnolPL/python-unittest | /06_functions/04_tax/tax.py | 511 | 4.25 | 4 | def calc_tax(amount, tax_rate):
"""The function returns the amount of income tax"""
if not isinstance(amount, (int, float)):
raise TypeError('The amount value must be int or float type')
if not amount >= 0:
raise ValueError('The amount value must be positive.')
if not isinstance(tax_rate, float):
raise TypeError('The tax_rate must be float')
if not 0 < tax_rate < 1:
raise ValueError('The tax_rate must be between 0 and 1')
return amount * tax_rate
| true |
5588dad39ce8b2d00d77f4497371df468016e4fe | Parzha/Assingment3 | /assi3project6.py | 583 | 4.125 | 4 |
flag=True
number_list = []
while flag:
user_input=int(input("Please enter the numbers you want? "))
number_list.append(user_input)
user_input_2=input("If you wanna continue type yes or 1 if you want to stop type anything= ").lower()
if user_input_2=="1" or user_input_2=="yes":
flag=True
else:
print("created list is ",number_list)
flag=False
sorted_list = sorted(number_list)
if sorted_list == number_list:
print("This list array is sorted ",number_list)
else:
print("This array is not sorted ",number_list) | true |
e42748ed030e92c694657695e48fdc29a3dafed8 | ConnorHoughton97/selections | /Water_Temp.py | 337 | 4.34375 | 4 | #Connor Houghton
#30/09/14
#telling the user whether ater is frozen, boiling or neither
water_temp = int(input("please enter the temperature of the water: "))
if water_temp >= 100:
print ("The water is boiling.")
elif water_temp <= 0:
print("The water is frozen.")
else:
print("The water is neither boiling or frozen.")
| true |
fbf00374688203f1feacec0636e2f1d385439be0 | zhanshi06/DataStructure | /Project_1/Problem_2.py | 1,375 | 4.375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
if len(suffix) == 0:
return []
files_list = list()
if os.path.exists(path):
dir_to_walk = [path]
while dir_to_walk:
cur_folder = dir_to_walk.pop() + '/' # get the first folder
sub_items = os.listdir(cur_folder)
for item in sub_items:
item = cur_folder + item
if os.path.isdir(item):
dir_to_walk.append(item)
elif str(item).endswith(suffix):
files_list.append(item)
return files_list
# tets
### Test Case one ###
print(find_files('.h', 'testdir'))
'''
output: ['testdir/t1.h', 'testdir/subdir1/a.h', 'testdir/subdir5/a.h', 'testdir/subdir3/subsubdir1/b.h']
'''
### Test Case two ###
print(find_files('.c', ''))
'''
output: []
'''
### Test Case three ###
print(find_files('.c', 'testdir/subdir1'))
'''
output: ['testdir/subdir1/a.c']
'''
| true |
32e95aacf766b380faaa2b8dc64d13b7bb062f24 | fffelix-jan/Python-Tips | /3a-map-those-ints.py | 239 | 4.15625 | 4 | print("Enter space-separated integers:")
my_ints = list(map(int, input().split())) # collect the input, split it into a list of strings, and then turn all the strings into ints
print("I turned it into a list of integers!")
print(my_ints) | true |
0ff46aa541476ec73d8dbe2de099a11048d0f560 | SS1908/30_days_of_python | /Day 16/properties_of_match.py | 342 | 4.21875 | 4 | """"
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function.
.group() returns the part of the string where there was a match.
"""
import re
str = "The train in Spain"
x = re.search("train",str)
print(x.span())
print(x.string)
print(x.group()) | true |
d62363750fa06239f769f4490b7c8dea0eeb06eb | SS1908/30_days_of_python | /Day 12/LIst_comprehension.py | 466 | 4.34375 | 4 | """
List Comprehension is defined as an elegant way to define, create a list in Python.
It consists of brackets that contains an expression followed by for clause.
SIGNATURE:
[ expression 'for' item 'in' list 'if' condition]
"""
letters = []
for letter in 'Python':
letters.append(letter)
print(letters)
print()
#You can also do using list comprehension.
letters = [letter for letter in 'Python']
print(letters)
| true |
c07614f370a9f5b625593569cf89f2e98f15e01a | SS1908/30_days_of_python | /Day 17/type_of_variable_in_class.py | 940 | 4.34375 | 4 | """
we have a two type of variable in class :- 1) instance variable
2)class variable
instance variable is changes object to object.
class variable is same for all the instance/object of the class.
"""
class car:
#this is a class variable
#class variable define outside the __init__ method.
wheels = 4
#this is a instance variable
def __init__(self):
self.comp = "BMW"
self.mile = 10
c1 = car()
c2 = car()
# you can access class variable using object_name or class_name.
print(c1.comp,c1.mile,c1.wheels)
print(c2.comp,c2.mile,car.wheels)
print()
#you can change the value of an instance variable.
c1.mile = 8
#we can also change the value of class variable.
car.wheels = 5
print("After changing value of instance and class variable")
print(c1.comp,c1.mile,car.wheels)
print(c2.comp,c2.mile,c2.wheels) | true |
9d6e28084ff70545db5ed473b6ca361806566481 | SS1908/30_days_of_python | /Day 6/Comparisons_of_set.py | 406 | 4.25 | 4 | # <, >, <=, >= , == operators
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
# Days1 is the superset of Days2 hence it will print true.
print(Days1 > Days2)
# prints false since Days1 is not the subset of Days2
print(Days1 < Days2)
# prints false since Days2 and Days3 are not equivalent
print(Days2 == Days3) | true |
6a1f01bccda41e9216fc389162eaa758f241ac7d | SS1908/30_days_of_python | /Week 1/Day 1/Logical_operator.py | 761 | 4.5625 | 5 | #Logical operators are use to combine conditional statements.
# Operator Description
# and Returns True if both statements are true
# or Returns True if one of the statements is true
# not Reverse the result, returns False if the result is true
print("and operator")
x=6
print(x)
if x>0 and x<10:
print("number is between 0 to 10")
else:
print("numer is not is between 0 to 10")
print()
print(" or opreator")
x=11
if x>0 or x<10:
print("one or both conditons are true")
else:
print("both the conditions are false")
print()
print("not operator")
x = True
print("before use of not operator x is",x)
print("after using not operator x is become",not x)
| true |
34133a627a028c0b89086bd79ab2928cdd85aa36 | leoweller7139/111-Lab-1 | /calc.py | 1,299 | 4.15625 | 4 | # Method on the top
def seperator():
print(30 * '-')
def menu():
print('\n') #\n is like pressing enter
seperator()
print(" Welcome to PyCalc")
seperator()
print('[1] - Add')
print('[2] - Subtract')
print('[3] - Multiply')
print('[4] - Divide')
print('[x] - Exit')
# instructions on the bottom
opc = ''
while(opc != 'x'):
menu() # Display Menu
# Select an option
opc = input('Select an option: ')
if(opc == 'x'):
break # Finish with the loop
num1 = float(input('First Number: '))
num2 = float(input('Second Number: '))
if(opc == '1'):
res = num1 + num2
print('Result: ' + str(res))
if(opc == '2'):
res = num1 - num2
print('Result: ' + str(res))
if(opc == '3'):
res = num1 * num2
print('Result: ' + str(res))
elif(opc == '4'):
if(num1 == 0) or (num2 == 0): # After the if is the condition of the loop
print("Can not put zero when dividing")
# elif also requires a condition COMMENTS EFFECT IF LOOPS
else: #Else do not have a condition
res = num1 / num2
print('Result: ' + str(res))
input('Press Enter to continue...')
print('Thank you!!') | true |
c3b4e2f580b13b04739c2b47b7dd47def850947e | gabe01feng/trinket | /Python Quiz/poolVolume.py | 1,108 | 4.1875 | 4 | import math
name = input("What is your name? ")
pool = input("What shape is your pool, " + name + "? (Use RP for rectangular prism, C for cube, or CY for a cylindrical pool) ")
if pool == "RP":
length = float(input("What is the length of the pool in feet? "))
width = float(input("What is the width of the pool in feet? "))
depth = float(input("What is the depth of the pool in feet? "))
volume = length * depth * width * 7.5
print("The volume of your pool, " + name + ", is " + str(volume) + " gallons.")
elif pool == "C":
length = float(input("What is the side length of the pool? "))
volume = (length ** 3) * 7.5
print("The volume of your pool, " + name + ", is " + str(volume) + " gallons.")
elif pool == "CY":
radius = float(input("What is the radius of the pool? "))
depth = float(input("What is the depth of the pool in feet? "))
volume = (((((math.pi * (radius ** 2)) * depth * 7.5) * 100) // 1) / 100)
print("The volume of your pool, " + name + ", is ~" + str(volume) + " gallons.")
else:
print(name + ", you didn't give me a valid pool shape.") | true |
d68f4b523b209f3a42cea58cafd8b153eeba6ba2 | Mukosame/learn_python_the_hard_way | /ex25.py | 1,380 | 4.4375 | 4 | def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
stuff = "A quick brown fox jumps over a lazy dog"
words = break_words(stuff)
print (words)
sorted_words = sort_words(words)
print (sorted_words)
print_first_word(words)
print (words)
print_last_word(words)
print (words)
sentence = "Ich habe eine kleine Katze."
sorted_sentence = sort_sentence(sentence)
print (sorted_sentence)
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
| true |
2aa078dc068d59306dd016ccd5f61591fc6c1214 | aselvais/PythonOOPexample | /libs/animals/AnimalArmy.py | 1,246 | 4.1875 | 4 | """
Class for creating an army of animal
"""
from libs.animals.Dog import Dog
from libs.animals.Duck import Duck
class AnimalArmy:
"""Generates an army of animals
Args:
animal_type (str, optional): duck or dog. Defaults to 'duck'.
army_size (int, optional): Number of animal in the army. Defaults to 10.
"""
animals = []
def __init__(self, animal_type='Duck', army_size=10):
"""Generates an army of animals
Args:
animal_type (str, optional): duck or dog. Defaults to 'Duck'.
army_size (int, optional): Number of animal in the army. Defaults to 10.
"""
for i in range(army_size):
if animal_type == 'Duck':
_a = Duck()
if animal_type == 'Dog':
_a = Dog()
_a.set_name(animal_type + str(i))
self.animals.append(_a)
print('Army of ' + str(army_size) + ' ' + animal_type + 's created!')
def attack(self, enemy):
"""Attacking the enemy animal with the army, each animal at a time
Args:
enemy (Animal): Enemy animal
"""
print('Army attack on ' + enemy._name)
for i in self.animals:
i.attack(enemy)
| true |
3807e45d09f23244239ad8db2bdd786c0badc56e | Kota-N/python-exercises | /ex6StringLists.py | 350 | 4.125 | 4 | # An exercise from http://www.practicepython.org/
#6 String Lists
import math
word = input("Enter a word: ")
middleIndex = math.floor(len(word)/2)
firstHalf = word[0:middleIndex]
lastHalf = word[middleIndex+1:]
if firstHalf[::-1] == lastHalf:
print(word, ": Your word is palindrome!")
else:
print(word, ": Your word isn't palindrome...") | true |
906289d11e5d2e0cb23ed09ed268916674ae689f | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/Hacker Chapter--Files/ex.04.py | 2,959 | 4.25 | 4 | '''Here is a file called labdata.txt that contains some sample data from a lab experiment.
44 71
79 37
78 24
41 76
19 12
19 32
28 36
22 58
89 92
91 6
53 7
27 80
14 34
8 81
80 19
46 72
83 96
88 18
96 48
77 67
Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair.
Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:
y=y¯+m(x−x¯)
m=∑xiyi−nx¯y¯∑x2i−nx¯2
where x¯
is the mean of the x-values, y¯ is the mean of the y- values and n is the number of points.
If you are not familiar with the mathematical ∑ it is the sum operation. For example
∑xi means to add up all the x values.
Your program should analyze the points and correctly scale the window using setworldcoordinates so that that each point can be plotted.
Then you should draw the best fit line, in a different color, through the points.
'''
'''
def plot(data):
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed(1)
# Set up our variables for the formula.
x_lst, y_lst = [i[0] for i in data], [i[1] for i in data]
x_sum, y_sum = float(sum(x_lst)), float(sum(y_lst))
x_mean, y_mean = x_sum / len(x_lst), y_sum / len(y_lst)
# Not sure about the formula where x and E are concerned ...
m = ((x_sum * y_sum) - (20 * x_mean * y_mean)) / (x_sum ** 2 - (20 * x_mean ** 2))
y = y_mean + m * (x_sum - x_mean) # This gives 966=x_sum so it can't be right.
# Get min and max values for coordinate system.
x_min, x_max, y_min, y_max = min(x_lst), max(x_lst), min(y_lst), max(y_lst)
# Add 10 points on each line to be safe.
wn.setworldcoordinates(x_min - 10, y_min - 10, x_max + 10, y_max + 10)
for i in data:
t.setpos(i[0], i[1])
wn.exitonclick()
with open("lib/labdata.txt") as f:
coords = [map(int, line.split()) for line in f]
plot(coords)
'''
def plot(data):
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed(1)
# Set up our variables for the formula.
x_lst, y_lst = [i[0] for i in data], [i[1] for i in data]
x_sum, y_sum = float(sum(x_lst)), float(sum(y_lst))
x_mean, y_mean = x_sum / len(x_lst), y_sum / len(y_lst)
# Not sure about the formula where x and E are concerned ...
m = ((x_sum * y_sum) - (20 * x_mean * y_mean)) / (x_sum ** 2 - (20 * x_mean ** 2))
y = y_mean + m * (x_sum - x_mean) # This gives 966=x_sum so it can't be right.
# Get min and max values for coordinate system.
x_min, x_max, y_min, y_max = min(x_lst), max(x_lst), min(y_lst), max(y_lst)
# Add 10 points on each line to be safe.
wn.setworldcoordinates(x_min - 10, y_min - 10, x_max + 10, y_max + 10)
for i in data:
t.setpos(i[0], i[1])
wn.exitonclick()
f = open("studentdata.txt", "r")
coords = [map(int, line.split()) for line in f]
plot(coords)
| true |
eaedab6cec968ff2daf1313210d0713a8a397653 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 3/ex.04.py | 1,137 | 4.375 | 4 | '''Football Scores Suppose you’ve written the program below.
The given program asks the user to input the number of touchdowns and field goals scored by a (American) football team,
and prints out the team’s score. (We assume that for each touchdown, the team always makes the extra point.)
The European Union has decided that they want to start an American football league,
and they want to use your killer program to calculate scores,
but they like things that are multiples of 10 (e.g. the Metric System),
and have decided that touchdowns will be worth 10 points and field goals are worth 5 points.
Modify the program below to work on both continents, and beyond.
It should ask the user how many points a touchdown is worth and how many points a field goal is worth.
Then it should ask for the number of each touchdowns / field goals scored, and print the team’s total score.
'''
num_touchdowns = input("How many touchdowns were scored? ")
num_field_goals = input("How many field goals were scored? ")
total_score = 7 * int(num_touchdowns) + 3 * int(num_field_goals)
print("The team has", total_score, "points")
| true |
8751ce643df7e321eaf0f354e4e2d03641f56778 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 2/ex.08.py | 326 | 4.28125 | 4 | '''Write a program that will compute the area of a rectangle.
Prompt the user to enter the width and height of the rectangle.
Print a nice message with the answer.
'''
## question 9 solution
width = int(input("Width? "))
height = int(input("Height? "))
area = width * height
print("The area of the rectangle is", area)
| true |
cd9e9cf99f39ffab5a59d013375ebe2016503dae | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/commandline.py | 1,150 | 4.53125 | 5 | '''
commandline.py
Jeff Ondich, 21 April 2009
This program gives a brief illustration of the use of
command-line arguments in Python. The program accepts
a file name from the command line, opens the file, and
counts the lines in the file.
'''
import sys
# If the user types too few or too many command-line arguments,
# this code prints a usage statement and exits the program.
# Note that sys.argv[0] is the name of the program, so if
# I type "python commandline.py something", then sys.argv[0]
# is "commandline.py" and sys.argv[1] is "something".
if len(sys.argv) != 2:
print ('Usage:', sys.argv[0], 'filename')
exit()
# You don't normally need to tell the users what they just
# typed, but the print statement here just verifies that
# we have grabbed the right string for the file name.
fileName = sys.argv[1]
print ('The requested file is', fileName)
theFile = open(fileName)
# Count the lines in the file.
lineCounter = 0
for line in theFile:
lineCounter = lineCounter + 1
# Report the results.
print ('The file', fileName, 'contains', lineCounter, 'lines.')
# Clean up after yourself.
theFile.close()
| true |
f81af3b3ee07daecb713502882d235f0b62e0fca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/List Comprehensions.py | 628 | 4.5 | 4 | '''The previous example creates a list from a sequence of values based on some selection criteria.
An easy way to do this type of processing in Python is to use a list comprehension.
List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
where the if clause is optional. For example,
'''
mylist = [1,2,3,4,5]
yourlist = [item ** 2 for item in mylist]
print(yourlist)
alist = [4,2,8,6,5]
blist = [num*2 for num in alist if num%2==1]
print(blist)
'''Correct! Yes, 5 is the only odd number in alist. It is doubled before being placed in blist.'''
| true |
b1b9abda174eecee080e0bc8b1fa8b424104ea3e | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/strings2.py | 442 | 4.15625 | 4 | '''strings2.py
Jeff Ondich, 2 April 2009
This sample program will introduce you to "iteration" or
"looping" over the characters in a string.
'''
s = 'two kudus and a newt'
# What happens here?
print('The first loop')
for ch in s:
print (ch)
print()
# And here?
print( 'The second loop')
k = 0
while k < len(s):
print (s[k])
k = k + 1
print()
# Can you make sense of these structures? Let's talk about
# them on Monday. | true |
6b49356fb32eee0f79ad56e806a41b549b7fc847 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 6/ex.08.py | 337 | 4.28125 | 4 | '''Now write the function is_odd(n) that returns True when n is odd and False otherwise.
'''
from test import testEqual
def is_odd(n):
# your code here
if n % 2 == 0:
return False
else:
return True
testEqual(is_odd(10), False)
testEqual(is_odd(5), True)
testEqual(is_odd(1), True)
testEqual(is_odd(0), False) | true |
1122da139c723e93234aba0ae35e3ec62f7504b6 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Nested Lists.py | 776 | 4.53125 | 5 | '''A nested list is a list that appears as an element in another list.
In this list, the element with index 3 is a nested list.
If we print(nested[3]), we get [10, 20]. To extract an element from the nested list, we can proceed in two steps.
First, extract the nested list, then extract the item of interest.
It is also possible to combine those steps using bracket operators that evaluate from left to right.
'''
'''
nested = ["hello", 2.0, 5, [10, 20]]
innerlist = nested[3]
print(innerlist)
item = innerlist[1]
print(item)
print(nested[3][1])
'''
alist = [ [4, [True, False], 6, 8], [888, 999] ]
if alist[0][1][0]:
print(alist[1][0])
else:
print(alist[1][1])
'''Correct! Yes, alist[0][1][0] is True and alist[1] is the second list, the first item is 888.'''
| true |
cbb24873533a63b0842920b265efe25987dca3f3 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 14/ex.06.py | 1,691 | 4.125 | 4 | ''')
(GRADED) Write a new method in the Rectangle class to test if a Point falls within the rectangle.
For this exercise, assume that a rectangle at (0,0) with width 10 and height 5 has open upper bounds on the width and height, i.e.
it stretches in the x direction from [0 to 10), where 0 is included but 10 is excluded, and from [0 to 5) in the y direction.
So it does not contain the point (10, 2). These tests should pass:
r = Rectangle(Point(0, 0), 10, 5)
test(r.contains(Point(0, 0)), True)
test(r.contains(Point(3, 3)), True)
test(r.contains(Point(3, 7)), False)
test(r.contains(Point(3, 5)), False)
test(r.contains(Point(3, 4.99999)), True)
test(r.contains(Point(-3, -3)), False)
'''
from test import test
class Point:
"""Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def __str__(self):
return "x=" + str(self.x) + ", y=" + str(self.y)
class Rectangle:
"""Rectangle class using Point, width and height"""
def __init__(self, initP, initW, initH):
self.location = initP
self.width = initW
self.height = initH
def contains(self, point):
# Your code here!
x, y = point.get_x(), point.get_y()
return 0 <= x < self.width and 0 <= y < self.height
r = Rectangle(Point(0, 0), 10, 5)
test(r.contains(Point(0, 0)), True)
test(r.contains(Point(3, 3)), True)
test(r.contains(Point(3, 7)), False)
test(r.contains(Point(3, 5)), False)
test(r.contains(Point(3, 4.99999)), True)
test(r.contains(Point(-3, -3)), False)
| true |
bd7d3da5c3917644520e2fd9528bee66e85ade32 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 4/ex.02.py | 884 | 4.4375 | 4 | '''Turtle objects have methods and attributes. For example, a turtle has a position and when you move the turtle forward, the position changes.
Think about the other methods shown in the summary above. Which attibutes, if any, does each method relate to? Does the method change the attribute?
'''
'''Write a program that prints out the lyrics to the song “99 Bottles of Beer on the Wall”
'''
for i in range(99, -1, -1):
if i==1:
print (i,"bottle of beer on the wall,",i,"bottle of beer.")
print ("Take one down and pass it around,")
print (i-1,"bottles of beer on the wall.")
elif i==0:
print( "No more bottles of beer on the wall. How about some soju?")
else:
print (i,"bottles of beer on the wall,",i,"bottles of beer.")
print ("Take one down and pass it around,")
print (i-1,"bottles of beer on the wall.") | true |
d15fa577adbdc9cf9ac0c3ad0652ad2430eb8bca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 12/Crypto/Caesar Cipher/caesar01/caesar 02.py | 1,272 | 4.375 | 4 | def caesarCipher(t, s):
"""
caesarCipher(t, s)
Returns the cipher text in a given plain text or vice versa.
Variables:
t - text (input), nt - new text (output)
lc - lowercase, uc - uppercase
pt[c] - nth character of the plain text (also used to get the
plaintext in a given cipher text.
Description:
In Cryptography, caesar cipher is the most simplest and most widely
known encryption/decryption techniques. It substitutes your input
with a given shift (s). e.g, if s is 1, A will be B
or a will be b.
Examples:
#>>> #caesarCipher("Be sure to drink your ovaltine", 13)
'Or fher gb qevax lbhe binygvar'
#>>> caesarCipher("Or fher gb qevax lbhe binygvar", -13)
'Be sure to drink your ovaltine'
"""
nt = ""
t = t.replace("\n", "")
uc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lc = "abcdefghijklmnopqrstuvwxyz"
for c in range(len(t)):
if (t[c].isalpha()):
if (t[c].isupper()):
nt += uc[(uc.index(t[c]) + s) % 26]
else:
nt += lc[(lc.index(t[c]) + s) % 26]
else:
nt += t[c]
return nt | true |
7f7f4cd5a877fb9a457cd662ec1cbe4f47cba6cb | CriticalD20/String-Jumble | /stringjumble.py | 1,567 | 4.3125 | 4 | """
stringjumble.py
Author: James Napier
Credit: http://stackoverflow.com/questions/12794141/reverse-input-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python
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
"""
JumbleString = input('Please enter a string of text (the bigger the better): ')
print('You entered "'+JumbleString+'". Now jumble it:')
#This is the code for the first input line
print(JumbleString[::-1])
#This is the code for the second output line
print(' '.join(reversed(JumbleString.split(' '))))
#This is the code for the third output line
print(' '.join(w[::-1] for w in JumbleString.split())) | true |
03478dde7f02433ae2c351c181cefc942e0c75be | parthpanchal0794/pythontraining | /NumericType.py | 1,634 | 4.25 | 4 | """
Numeric types classes
1. Integer e.g 10
2. Float e.g 10.0
3. Complex e.g 3 + 5j
4. Binary type (Class Int)
5. Hexadecimal (Class Int)
6. Octa decimal (Class Int)
"""
# Integer Values
a = 13
b = 100
c = -66
print(a, b, c)
print(type(a))
# Floating values
x = 33.44
y = -8.78
z = 56.0 # with .0 at end it will consider as integer but with .0 it will consider as float
print(x, y, z)
print(type(z))
# Complex type
d = 3 + 5j
print(d)
print(type(d))
# Binary type
# To define binary type start with literal 0b or 0B
e = 0b1010
g = 0B1010
print(e)
print(g)
print(type(e))
# Hexadecimal type
# To define hexadecimal start with literal 0x or 0X
f = 0XFF
h = 0xFF
print(f)
print(h)
print(type(f))
# Octa decimal type
# To define octa decimal start with literal 0o or 0O
i = 0o12
j = 0O12
print(i)
print(j)
print(type(i))
#################################################################
# Boolean value type have 2 value: True and False
# it mainly use to define condition in loop or if statement
k = True
print(type(k))
print(9 > 8) # Condition returns True value of class bool
###################################################################
# int, float, bin, hex and oct functions used to convert the numeric data type class
A = int(55.60) # float or int no are allowed
print(type(A))
C = float(66)
print(type(C))
D = float("66") # only no are allowed not string like "python"
print(type(D))
E = bin(10) # only integers are allowed
print(type(E))
print(E)
F = hex(10) # only integers are allowed
print(type(F))
print(F)
G = oct(10) # only integers are allowed
print(type(G))
print(G)
| true |
a862febaed4059785ab37c810b54b6a1034c6901 | Mohibtech/Mohib-Python | /UrduPythonCourse/List Comprehension.py | 2,248 | 4.75 | 5 | '''
List comprehensions provide a concise way to create lists.
It consists of brackets containing an expression followed by a for clause, then
optional if clauses.
The expressions can be anything, meaning you can put in all kinds of objects in lists.
The list comprehension always returns a result list.
'''
# List comprehensions in Python are constructed as follows:
list_variable = [x for x in sequence]
# In maths, common ways to describe lists (or sets, or tuples, or vectors) are:
'''
S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}
'''
'''
sequence S contains values between 0 and 9 included that are raised to the power of two.
Sequence V contains the value 2 that is raised to a certain power.
For the first element in the sequence, this is 0, for the second this is 1, and so on, until you reach 12.
sequence M contains elements from the sequence S, but only the even ones.
'''
# Above mathematical expressions will produce following lists.
S = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
V = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
M = {0, 4, 16, 36, 64}
# Creating List S using List comprehension
S = [x**2 for x in range(10)]
# Creating List S using for Loop
S = []
for x in range(10):
S.append(x**2)
# Creating List V using List comprehension
V = [2**i for i in range(13)]
# Creating List V using for Loop
V = []
for i in range(13):
V.append(2**i)
# Creating List M using List comprehension
M = [x for x in S if x % 2 == 0]
# Creating List M using for Loop
M = []
for x in S:
if x % 2 ==0:
M.append(x)
# Celsius to Fahrenheit conversion
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = [((9/5)*x + 32) for x in Celsius ]
print(Fahrenheit)
# Celsius to Fahrenheit using for loop
Fahrenheit = []
for x in Celsius:
item = (9/5)*x + 32
Fahrenheit.append(item)
# Transpose matrix
matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print (transpose)
matrix = [[1, 2], [3,4], [5,6], [7,8]]
# Transpose matrix using for Loop
transposed = []
for i in range(2):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed) | true |
3cf56345025b2e3d5581c689813defd14a38feb7 | malhar-pr/side-projects | /pythagorean.py | 2,783 | 4.375 | 4 | import time
pyth_list=[] #Creates an empty list that will hold the tuples containing Pythagorean/Fermat triplets
power_list=[] #Creates an empty list that will cache the value of each index raised to the specified exponent in the given range
print("---------------------------------------------------------------------\nMALHAR'S PYTHAGOREAN TRIPLET GENERATOR / FERMAT'S LAST THEOREM SOLVER\n---------------------------------------------------------------------")
UserInput1 = input("What power will be selecting? \n")
UserInput2=input("And till what range would you like to go to? \n")
UserInput3=input("Would you like to be 100% accurate? [1/0] \n")
if UserInput3 == '0':
UserInput4 = input("Order of accuracy (put 0 if 100% accurate): ")
order=int(UserInput4) #typecasts the user-input value to int
start=time.process_time() #stores current process time in variable to calculate time elapsed to run the code
power=int(UserInput1) #typecasts the user-input value to int
crange=int(UserInput2) #typecasts the user-input value to int
def append_check(accornot):
"""
Inputs: Takes in variable "accornot" which determines if the user requires an accurate answer or not
Appends a tuple containing the triplet that satisfies the condition to the list, "pyth_list"
Returns: nothing
"""
if accornot == '1':
if (power_list[a] + power_list[b] == power_list[c]): #Compares exact condition
pyth_list.append((a,b,c))
elif accornot == '0':
if (power_list[a] + power_list[b] < (1+(pow(10,-order)))*power_list[c]) and (power_list[a] + power_list[b] > (1-(pow(10,-order)))*power_list[c]):
#compares approximate condition within required order parameter
pyth_list.append((a,b,c))
else:
print("Invalid Input")
for var in range(crange):
power_list.append(pow(var,power)) #creates cache of the value of each index raised to the specified exponent in the given range, to reduce time complexity
for c in range(crange):
for b in range(c):
for a in range(b):
append_check(UserInput3) #calls the function that checks for the condition and appends to list if condition is True
if crange>=10000:
if not (c%(crange/1000)):
print(str(c/(crange/100)) + "% complete\r",)
elif crange<10000:
if not (c%(crange/100)):
print(str(int(c/(crange/100))) + "% complete\r",) #Gives loading indicator to show how much has completed
del power_list #Deletes cache of value of indices raised to the specified exponent
if (pyth_list)==[]: #If no results are found
print ("Search Complete. No results found.")
else:
print ("The list of triplets are: ")
print(pyth_list)
del pyth_list
a1 = input("Runtime of the program is {} seconds. Press any key to exit".format(time.process_time()-start))
| true |
e884acf79724ce595323ca07bf8e9783a2698f2e | shubham-bhoite164/DSA-with-Python- | /Reversing the Integer.py | 685 | 4.21875 | 4 | # Our task is to design an efficient algorithm to reverse the integer
# ex :- i/p =1234 , o/p =4321
# we are after the last digit in every iteration
# we can get it with modulo operator: the last digit is the remainder when dividing by 10
# we have to make sure that we remove that digit from the original number
# so we just have to divide the original number by 10 !!!
def reverse_integer(n):
reversed_integer = 0
remainder = 0
while n>0:
remainder = n % 10
reversed_integer = reversed_integer*10 + remainder
n = n//10 # we don't want decimal point
return reversed_integer
if __name__ == '__main__':
print(reverse_integer(1234))
| true |
1c7a92b66d1999fc6158a0422558668498f5aa0f | hdjsjyl/LeetcodeFB | /23.py | 2,577 | 4.21875 | 4 | """
23. Merge k Sorted Lists
Share
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
## solution1: similar to merge sort algorithm, the time complexity is O(nklogn)
# n is the length of lists; k is the length of each list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def helper(self, lists, left, right):
if left < right:
mid = left + (right - left) // 2
return self.merge(self.helper(lists, left, mid), self.helper(lists, mid + 1, right))
return lists[left]
def merge(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
dummy = ListNode(-1)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
cur = cur.next
cur.next = None
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = None
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
left = 0
right = len(lists) - 1
return self.helper(lists, left, right)
# solution2: maintain a heap with length of n, n is the length of lists, k is the length of each list
# time complexity is O(nklogn), the time of updating heap is logn
# python heapq, if the item is a tuple, it includes three elements, the first is the priority and compared item, we use it to compare;
# the second is count item, each count item is different from all of others; the third is task object
import heapq
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
stack = []
heapq.heapify(stack)
order = 0
for l in lists:
if l:
heapq.heappush(stack, (l.val, order, l))
order += 1
res = ListNode(-1)
dummy = res
while stack:
cur = heapq.heappop(stack)[2]
res.next = cur
res = res.next
if cur.next:
heapq.heappush(stack, (cur.next.val, order, cur.next))
res.next = None
order += 1
return dummy.next | true |
aa866eb07967f983e83b81db0dd63ca2237c8935 | marwane8/algorithms-data-structures | /Sorting.py | 2,174 | 4.25 | 4 | import heapq
'''
SORTING ALGORITHMS
-Sorting Algorithms are a common class of problems with many implementation
-This class highlights some of the foundational implmentations of sorting
-SORT FUNCTIONS-
selectionSort: finds the minimum number and pops it into the result array
mergeSort: uses divide and conqure to to sort elements in n log(n) time
heapSort: uses heap data structure and heap pop to sort array
'''
class Sort:
def selectionSort(self, array):
result = []
size = len(array)
for n in range(size):
#Take minimum of the subarray and pop it into the result array
result.append(array.pop(array.index(min(array))))
return result
def mergeSort(self, array):
if not array:
return None
#base case
if len(array) == 1: return array
#divide array in two
middle = len(array)//2
LeftArray = array[:middle]
RightArray = array[middle:]
# call merge sort on both halfs
Left = self.mergeSort(LeftArray)
Right = self.mergeSort(RightArray)
# bring sorted halfs together
result = self.mergeArray(Left, Right)
return list(result)
def mergeArray(self, LeftArray, RightArray):
resultArray = []
#append smallest value to the result array
while LeftArray and RightArray:
if LeftArray[0] <= RightArray[0]:
resultArray.append(LeftArray.pop(0))
elif LeftArray[0] > RightArray[0]:
resultArray.append(RightArray.pop(0))
if not RightArray: resultArray += LeftArray
else: resultArray += RightArray
return resultArray
#Heap Sorting
def heapSort(self, array):
heapq.heapify(array)
result = []
while array:
result.append(heapq.heappop(array))
print(result)
return result
testArray = [2,6,9,8,4,7]
sort = Sort()
# Merge Sort
test1 = sort.mergeSort(testArray)
# Heap Sort
test2 = sort.heapSort(testArray)
#Selection Sort
test3 = sort.selectionSort(testArray) | true |
87784d6b0b95fb4c9b84b0a25d1b9c3423a7a52c | linhdvu14/leetcode-solutions | /code/874_walking-robot-simulation.py | 2,149 | 4.5 | 4 | # A robot on an infinite grid starts at point (0, 0) and faces north. The robot can
# receive one of three possible types of commands:
# -2: turn left 90 degrees
# -1: turn right 90 degrees
# 1 <= x <= 9: move forward x units
# Some of the grid squares are obstacles.
# The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
# If the robot would try to move onto them, the robot stays on the previous
# grid square instead (but still continues following the rest of the route.)
# Return the square of the maximum Euclidean distance that the robot will be
# from the origin.
# Example 1:
# Input: commands = [4,-1,3], obstacles = []
# Output: 25
# Explanation: robot will go to (3, 4)
# Example 2:
# Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
# Output: 65
# Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)
# Note:
# 0 <= commands.length <= 10000
# 0 <= obstacles.length <= 10000
# -30000 <= obstacle[i][0] <= 30000
# -30000 <= obstacle[i][1] <= 30000
# The answer is guaranteed to be less than 2 ^ 31.
# ----------------------------------------------
# Ideas:
# Considerations:
# Complexity: O(m) time, O(n) space where m = len(commands), n = len(obstacles)
# ----------------------------------------------
class Solution:
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
obstacles = set(map(tuple, obstacles))
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # turn left = step left on dir array
result = x = y = i = 0 # i = dirs index; x, y = coords
for c in commands:
if c == -2:
i = (i - 1) % 4
elif c == -1:
i = (i + 1) % 4
else:
for _ in range(c):
dx, dy = dirs[i]
if (x + dx, y + dy) not in obstacles:
x += dx
y += dy
result = max(result, x * x + y * y)
return result | true |
7908915172b367d592be102e890a18001709d6e2 | linhdvu14/leetcode-solutions | /code/231_power-of-two.py | 639 | 4.375 | 4 | # Given an integer, write a function to determine if it is a power of two.
# Example 1:
# Input: 1
# Output: true
# Explanation: 20 = 1
# Example 2:
# Input: 16
# Output: true
# Explanation: 24 = 16
# Example 3:
# Input: 218
# Output: false
# ----------------------------------------------
# Ideas: power of two iff 1 bit set iff n&(n-1) == 0
# Considerations:
# - edge cases: n = 1, n < 0
# Complexity: O(1) time, O(1) space
# ----------------------------------------------
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and n & (n - 1) == 0 | true |
ded0c70db2cdd448b7041f41266219fe933f1aa7 | linhdvu14/leetcode-solutions | /code/589_n-ary-tree-preorder-traversal.py | 918 | 4.125 | 4 | # Given an n-ary tree, return the preorder traversal of its nodes' values.
# For example, given a 3-ary tree:
# 1
# / | \
# 3 2 4
# / \
# 5 6
# Return its preorder traversal as: [1,3,5,6,2,4].
# Note: Recursive solution is trivial, could you do it iteratively?
# ----------------------------------------------
# Ideas:
# Considerations:
# Complexity: time, space
# ----------------------------------------------
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class Solution:
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = []
stack = [root]
while stack:
node = stack.pop()
if node:
result.append(node.val)
stack.extend(node.children[::-1])
return result
| true |
41be3c636e2d3cda64f2b4db81121a7b47ead5f5 | alexresiga/courses | /first semester/fp/assignment1/SetBP10.py | 660 | 4.375 | 4 | # Consider a given natural number n. Determine the product p of all the proper factors of n.
def productOfProperFactors(n):
"""
This function returns the product of all proper factor of a given natural number n.
input: n natural number.
output: a string with the proper factors and the reuslt of their product.
"""
result=""
p=1
d=2
while d<=n//2:
if n%d==0:
p*=d
result+=str(d)+'*'
d+=1
result=result[:-1]
result+='='+ str(p)
return result
n=int(input("Give natural number n: "))
print("The product of all proper factors of",n,"is",productOfProperFactors(n))
| true |
a4e6c461cea4d86d34094af65ca4ee743b7be922 | oneandzeroteam/python | /dev.garam.seo/factorial.py | 227 | 4.25 | 4 | #factorial.py
factorial = 1
number = int (input ("input the number wanted to factorial: "))
print (number)
if (number == 1):
factorial = 1
else :
for i in range (1, number+1):
factorial = factorial * i
print (factorial) | true |
98b8353fedd8c1efa32ef163d62ba63c9cf169c2 | WhySongtao/Leetcode-Explained | /python/240_Search_a_2D_Matrix_II.py | 1,350 | 4.125 | 4 | '''
Thought: When I saw something like sorted, I will always check if binary search
can be used to shrink the range. Here is the same.
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Take this as an example. First let's go to the middle of the first row: 7. If
the target is bigger, then clearly, it could be at the right of 7. It can also be
at the down of 7. The only impossible place is the element on the left of 7 in the
same row. Hmm, this doesn't look like a way to shrink range.
So what about going from right top corner. Corner seems to be a good starting point.
If the target is bigger than current element, we can get rid of this whole row!
If the target is smaller than the current element, we can get rid of this whole
column!
I think going from left bottom corner works as well.
'''
def searchMatrix(matrix, target):
if len(matrix) == 0:
return False
# Starting from top right corner.
row = 0
column = len(matrix[0])-1
while(row <= len(matrix)-1 and (column >= 0)):
if matrix[row][column] == target:
return True
elif target < matrix[row][column]:
column -= 1
elif target > matrix[row][column]:
row += 1
return False
| true |
b928b09a4b3e417316274d2bd19ddccf31198aff | LeftySolara/Projects | /Classic Algorithms/Collatz_Conjecture/collatz.py | 606 | 4.1875 | 4 | """
Collatz Conjecture:
Start with a number n > 1. Find the number of steps it takes to
reach one using the following process:
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1
"""
try:
n = int(input("Enter a number greater than one: "))
if n <= 1:
print("Invalid input")
exit(0)
except ValueError:
print("Invalid input")
exit(0)
count = 0
while n != 1:
print(n)
if n % 2 == 0:
n //= 2
count += 1
elif n % 2 > 0:
n *= 3
n += 1
count += 1
print(n)
print("\nSteps taken: {}".format(count)) | true |
80f8377d734ff1a9f51ea52956ddbdb172456b78 | lachlankerr/AdventOfCode2020 | /AdventOfCode2020/day09.py | 1,883 | 4.15625 | 4 | '''
Day 09: https://adventofcode.com/2020/day/9
'''
def read_input():
'''
Reads the input file and returns a list of all the lines
'''
lines = []
with open('day09input.txt') as f:
lines = f.read().splitlines()
lines = list(map(int, lines)) # convert list to ints
return lines
def part_one(lines):
'''
Finds the number in the list that cannot be made from the previous `preamble_size` numbers.
'''
preamble = []
preamble_size = 25
for line in lines:
if len(preamble) < preamble_size:
preamble.append(line)
else:
if not check_preamble(preamble, line):
part_one_result = line
return line
else:
preamble.pop(0)
preamble.append(line)
pass
def check_preamble(preamble, num):
'''
Checks if the given num is a product of two numbers in the preamble.
'''
for a in preamble:
for b in preamble:
if a + b == num:
return True
return False
def part_two(lines):
'''
Finds a contiguous set of at least two numbers that sum to the result of part_one, then returns the sum of the smallest and largest number in this contiguous set.
'''
part_one_result = part_one(lines)
preamble = []
preamble_size = 2
i = 0
while i < len(lines):
if len(preamble) < preamble_size:
preamble.append(lines[i])
else:
if sum(preamble) == part_one_result:
return min(preamble) + max(preamble)
else:
preamble.pop(0)
preamble.append(lines[i])
if i == len(lines) -1 and preamble_size < i:
preamble_size += 1
preamble = []
i = 0
continue
i += 1
pass
| true |
90251aa6711f4db8af28ce75d89e4de26552f4a6 | danielmaddern/DailyProgrammer | /easy_challenge_1/challange.py | 611 | 4.25 | 4 | """
create a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format:
your name is (blank), you are (blank) years old, and your username is (blank)
for extra credit, have the program log this information in a file to be accessed later.
"""
name = raw_input('Enter your name:')
age = raw_input('Enter your age:')
username = raw_input('Enter your Reddit username:')
output = "your name is %s, you are %s years old, and your username is %s" % (name, age, username)
print output
# Extra Credit
with open('output.file', 'w') as f:
f.write(output)
| true |
5368c1c72141f2c65dc28018a9007b8465b308a4 | neha52/Algorithms-and-Data-Structure | /Project1/algo2.py | 2,928 | 4.21875 | 4 | # -*- coding: utf-8 -*-
array = [] #create an array.
x = float (input ("Enter the value of X: "))
n = int(input("Enter the number of elements you want:"))
if(n<2): #check if array more than two elements.
print ("Enter valid number of elements!")
else:
print ('Enter numbers in array: ') #take input from user.
for i in range(int(n)):
no = input()
array.append(int(no))
def heap(array, n, i):
largest = i # Initialize largest as root.
l = 2 * i + 1
r = 2 * i + 2
# See if left child of root exists and is greater than root.
if l < n and array[i] < array[l]:
largest = l
# See if right child of root exists and is greater than root.
if r < n and array[largest] < array[r]:
largest = r
if largest != i: # If required, change root.
array[i],array[largest] = array[largest],array[i]
# swap root with element greater than root.
heap(array, n, largest) # Heapify the root.
# The main function to sort an array
def hSort(array):
# Build a maxheap.
for i in range(n, -1, -1):
heap(array, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
array[i], array[0] = array[0], array[i] # swap
heap(array, i, 0)
try:
hSort(array) #sort the array using heapsort.
def median(array): #compute median of array.
mid = len(array)//2 #if length=odd, compute middle element.
if len(array) % 2: # To check if the length of array is odd or even.
return array[mid]
else:
med = (array[mid] + array[mid-1]) / 2 #if length=even, compute mean of middle elements.
return med
with open('algo2.txt', 'w') as filehandle: # open file algo1.txt to print
for items in array: # sorted array with write privilege.
filehandle.write( '%d ' % items)
filehandle.close()
med = median(array)
#function to compute longest sub-array with median greater than equal to X.
def LongSubArray(array, med):
if x > med:
for i in range (int(n)):
if i>=n or x <= med: #conditions based on desired output.
break
array.remove(array[0])
med = median(array) #median of longest subarray.
return ("Longest Subarray is :" ,array ,"of length" ,len(array))
f = open('algo2.txt', 'a') #open same file to append output.
f.write(" : is the Sorted Array \n \n")
f.write(str(LongSubArray(array, med))) #called function to print longest subarray.
f.close()
except ValueError as err: #errors
print("Something went Wrong",err)
except:
print("Something went Wrong")
| true |
679425af21b2ce17248f38b842ab6717df10d1a9 | Langutang/Spark_Basics | /spark_basics_.py | 2,906 | 4.1875 | 4 | '''
Spark is a platform for cluster computing. Spark lets you spread data and computations over clusters with multiple nodes (think of each node as a separate computer).
Splitting up your data makes it easier to work with very large datasets because each node only works with a small amount of data.
As each node works on its own subset of the total data, it also carries out a part of the total calculations required,
so that both data processing and computation are performed in parallel over the nodes in the cluster. It is a fact that parallel computation
can make certain types of programming tasks much faster.
'''
'''
Spark's core data structure is the Resilient Distributed Dataset (RDD). This is a low level object that lets Spark work its magic by splitting data across multiple nodes
in the cluster. However, RDDs are hard to work with directly, so in this course you'll be using the Spark DataFrame abstraction built on top of RDDs.
'''
# Step 1 - create instance of SparkContext
# Import SparkSession from pyspark.sql
from pyspark.sql import SparkSession
# Create my_spark
my_spark = SparkSession.builder.getOrCreate()
# Print my_spark
print(my_spark)
# View Tables
print(spark.catalog.listTables())
# Don't change this query
query = "FROM flights SELECT * LIMIT 10"
# Get the first 10 rows of flights
flights10 = spark.sql(query)
# Show the results
flights10.show()
##############################
# QUERY AND CONVERT TO PD DF #
##############################
# Don't change this query
query = "SELECT origin, dest, COUNT(*) as N FROM flights GROUP BY origin, dest"
# Run the query
flight_counts = spark.sql(query)
pd_counts = flight_counts.toPandas()
print(pd_counts.head())
# Create pd_temp
pd_temp = pd.DataFrame(np.random.random(10))
# Create spark_temp from pd_temp
spark_temp = spark.createDataFrame(pd_temp)
# Examine the tables in the catalog
print(spark.catalog.listTables())
# Add spark_temp to the catalog
spark_temp.createOrReplaceTempView("temp")
# Examine the tables in the catalog again
print(spark.catalog.listTables())
####################
# LOADING FROM FILE#
####################
# Don't change this file path
file_path = "/usr/local/share/datasets/airports.csv"
# Read in the airports data
airports = spark.read.csv(file_path, header=True)
# Show the data
airports.show()
####################
# CREATING COLUMNS #
####################
# Create the DataFrame flights
flights = spark.table("flights")
# Show the head
flights.show()
# Add duration_hrs
flights = flights.withColumn("duration_hrs", flights.air_time/60)
#############
# FILTERING #
#############
# Filter flights by passing a string
long_flights1 = flights.filter("distance > 1000")
# Filter flights by passing a column of boolean values
long_flights2 = flights.filter(flights.distance > 1000)
# Print the data to check they're equal
long_flights1.show()
long_flights2.show()
| true |
d07674970d95b0ab207982ccf70f771840a8486d | Liam1809/Classes | /Polymorphism.py | 798 | 4.28125 | 4 |
a_list = [1, 18, 32, 12]
a_dict = {'value': True}
a_string = "Polymorphism is cool!"
print(len(a_list))
print(len(a_dict))
print(len(a_string))
# The len() function will attempt to call a method named __len__() on your class.
# This is one of the special methods known as a “dunder method” (for double underscore) which Python will look for to perform special operations.
# Implementing that method will allow the len() call to work on the class.
# If it is not implemented, the call to len() will fail with an AttributeError.
# The following code example shows a class implementing __len__().
class Bag:
def __init__(self, item_count):
self.item_count = item_count
def __len__(self):
return self.item_count
mybag = Bag(10)
print(len(mybag))
# OUTPUTS: 10 | true |
2ab337712c44f9dd7fffb98548c8e3a7d0cea93f | tillyoswellwheeler/python-learning | /multi-question_app/app.py | 929 | 4.15625 | 4 | #--------------------------------------------
# Python Learning -- Multi-Question Class App
#--------------------------------------------
from Question import Question
#-------------------------------------
# Creating Question Object and App
question_prompts = [
"What colour are apples?\n(a) Red/Green\n(b) Purple/Red\n(c) Grey\n\n",
"What colour are Bananas?\n(a) Teal/Green\n(b) Magenta/Red\n(c) Yellow\n\n",
"What colour are Cherries?\n(a) Red/Green\n(b) Purple/Red\n(c) Blue\n\n"
]
questions = [
Question(question_prompts[0], "a"),
Question(question_prompts[1], "c"),
Question(question_prompts[2], "b"),
]
def ask_questions(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer is question.answer:
score += 1
else:
"Invalid choice"
print("You got {} Correct".format(score))
ask_questions(questions) | true |
0443bd0c80489e9a063851c62583a9fb7956bc4a | tillyoswellwheeler/python-learning | /2d-lists_&_nested-loops.py | 625 | 4.40625 | 4 | #-----------------------------------------
# Python Learning -- 2D & Nested Loops
#-----------------------------------------
#-----------------------------------------
# Creating a 2D array
number_grid = [
[1, 3, 4],
[3, 4, 5],
[3, 6, 7],
[2]
]
#-----------------------------------------
# Accessing rows and cols
print(number_grid[0][1])
#-----------------------------------------
# Accessing rows using a For Loop
for row in number_grid:
print(row)
#-----------------------------------------
# Accessing cols using a NESTED For Loop
for row in number_grid:
for col in row:
print(col) | true |
69e4a76a2265aa14a5efaaef542c8335fdd2a3e1 | tillyoswellwheeler/python-learning | /inheritance.py | 607 | 4.4375 | 4 | #-------------------------------------
# Python Learning -- Inheritance
#-------------------------------------
#-------------------------------------
#
class Chef:
def make_chicken(self):
print("Chef makes chicken")
def make_ham(self):
print("Chef makes ham")
def make_special_dish(self):
print("Chef makes a special dish")
class ChineseChef(Chef):
def make_chicken_feet(self):
print("Hmm crunchy chicken feet!")
dinner1 = Chef.make_chicken(Chef)
dinner2 = ChineseChef.make_chicken(ChineseChef)
dinner3 = ChineseChef.make_chicken_feet(ChineseChef)
| true |
d16589bfe23eaa72097e6fd6ea740bc4008a9415 | tillyoswellwheeler/python-learning | /LPTHW/Ex15.py | 1,123 | 4.40625 | 4 | # ------------------------------------
# LPTHW -- Ex15. Reading Files
# ------------------------------------
from sys import argv
# this means when you run the python, you need to run it with the name of the python command
# and the file you want to read in
script, filename = argv
# This opens the file and assigns it to a variable to use later
txt = open(filename)
# A string that passes through the filename given when you run the command
# This can happen because of the sys argv module
print(f"Here's your file {filename}:")
# This reads the saved txt from the txt variable above
print(txt.read())
# This print outputs a string and then asks the user for input
# If the user types in a valid txt file it saves to the variable file_again
# If you had another txt file in the same directory you could pass it through here by using its name
print("Type the filename again:")
file_again = input("> ")
# This opens the file and saves the output to the variable txt_again
txt_again = open(file_again)
# This uses the read() module to read what is in txt_again.
print(txt_again.read())
txt_again.close()
txt.close()
| true |
0bc1e75b9b72d3dc658993e020e7067a3ad5e468 | sriram161/Data-structures | /PriorityQueue/priorityqueue.py | 1,580 | 4.21875 | 4 | """ Priotity Queue is an abstract data structure.
Logic:
-------
Priority queue expects some sort of order in the data that is feed to it.
"""
import random
class PriorityQueue(object):
def __init__(self, capacity):
self.capacity = capacity
self.pq = []
def push(self, value):
if len(self.pq) < self.capacity:
self.pq.append(value)
else:
print("Priority queue is full!!!")
def delMax(self):
self.popMax()
def popMax(self):
max_index = self._findMaxIndex()
self.pq[-1], self.pq[max_index] = self.pq[max_index], self.pq[-1]
return self.pq.pop()
def popMin(self):
min_index = self._findMinIndex()
self.pq[-1], self.pq[min_index] = self.pq[min_index], self.pq[-1]
return self.pq.pop()
def isEmpty(self):
return False if len(self.pq) else True
def insert(self, pos, value):
self.pq.insert(-pos,value)
def _findMaxIndex(self):
max_index = 0
for i in range(len(self.pq)):
if self.pq[i] > self.pq[max_index]:
max_index = i
return max_index
def _findMinIndex(self):
min_index = 0
for i in range(len(self.pq)):
if self.pq[i] < self.pq[min_index]:
min_index = i
return min_index
if __name__ == "__main__":
pq = PriorityQueue(10)
for i in range(11):
pq.push(random.randint(1, 100))
print(pq.pq)
print(pq.popMax())
print(pq.pq)
print(pq.popMin()) | true |
98082b9e10c1250be6b115aa7278315a0a4b9cdc | griffs37/CA_318 | /python/8311.sol.py | 1,013 | 4.15625 | 4 | def make_sum(total, coins):
# Total is the sum that you have to make and the coins list contains the values of the coins.
# The coins will be sorted in descending order.
# Place your code here
greedy_coin_list = [0] * len(coins) # We create a list of zeros the same length as the coins list we read in
i = 0
while total > 0: # While the total is less than 0
while i < len(coins): # and while i is within the bounds of the coins list
if coins[i] <= total: # if the number at position i is less than or equal to our total
greedy_coin_list[i] += 1 # We add 1 to that position in our greedy coin list as it means we will use that coin once
total -= coins[i] # We then subtract that value from the total
else: # else the number at position i is greater than the total
i += 1 # We increment i to check the next coin in the list
return(greedy_coin_list)
# Test cases used for local testing
#print(make_sum(12, [5,2,1]))
#print(make_sum(157, [7,3,2,1])) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.