blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
42716bcb27499c2079a9eda6925d9ae969217adf | tme5/PythonCodes | /CoriolisAssignments/pyScripts/33_file_semordnilap.py | 1,780 | 4.53125 | 5 | #!/usr/bin/python
'''
Date: 19-06-2019
Created By: TusharM
33) According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen. For example, if "stressed" and "desserts" is part of the word list, the the output should include the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome!
'''
def in_file_semordnilap(file):
'''prints the semordnilap pairs present in the file
Time complexity of the function is O(n)'''
with open(file,'r') as f:
f_rd=f.readlines()
f_cl=[x.strip() for x in f_rd]
ref_set=[]
list(map(lambda x: ref_set.extend(x.split(' ')), f_cl))
for inp in ref_set:
rev_inp=inp[::-1]
if rev_inp in ref_set:
print(inp,rev_inp)
if __name__=='__main__':
in_file_semordnilap('palindrome_input_1.txt')
# SWAP PAWS
# STEEL LEETS
# LEETS STEEL
# PEELS SLEEP
# SERIF FIRES
# FIRES SERIF
# SLEEP PEELS
# STRESSED DESSERTS
# DEVIL LIVED
# LIVED DEVIL
# DESSERTS STRESSED
# DELIVER REVILED
# PAWS SWAP
# REDIPS SPIDER
# DEBUT TUBED
# DEEPS SPEED
# SPEED DEEPS
# TUBED DEBUT
# SPIDER REDIPS
# REVILED DELIVER
# DIAPER REPAID
# DRAWER REWARD
# LOOTER RETOOL
# RETOOL LOOTER
# MURDER REDRUM
# REDRUM MURDER
# REWARD DRAWER
# REPAID DIAPER
# ANIMAL LAMINA
# DEPOTS STOPED
# STOPED DEPOTS
# LAMINA ANIMAL
| true |
9801097af0d4a761dc1f96039b2cf86cac257c26 | tme5/PythonCodes | /CoriolisAssignments/pyScripts/21_char_freq.py | 1,200 | 4.40625 | 4 | #!/usr/bin/python
'''
Date: 18-06-2019
Created By: TusharM
21) Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").
'''
def char_freq(inp):
'''Returns a dictionary of frequency of occurence of characters in the input string, considers only characters
Time complexity of this function in worst condition is O(n)'''
if type(inp)==str:
unq=set(x for x in inp if x.isalpha())
unq=sorted(unq,reverse=False)
ret_dict={x:0 for x in unq}
#print(temp)
lst=[x for x in inp if x.isalpha()]
for char in lst:
ret_dict[char]=ret_dict.get(char)+1
else:
raise Exception('Input expected string')
return ret_dict
if __name__=='__main__':
print(char_freq("abbabcbdbabdbdbabababcbcbab"))
#{'a': 7, 'b': 14, 'c': 3, 'd': 3}
print(char_freq('merry christmas and happy new year'))
#{'a': 4, 'c': 1, 'd': 1, 'e': 3, 'h': 2, 'i': 1, 'm': 2, 'n': 2, 'p': 2, 'r': 4, 's': 2, 't': 1, 'w': 1, 'y': 3}
| true |
f869321ad3d5a053c4e10c8c0e84c83d25b33974 | tme5/PythonCodes | /CoriolisAssignments/pyScripts/30_translate_to_swedish.py | 1,031 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
'''
Date: 19-06-2019
Created By: TusharM
30) Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"r"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words.
'''
def translate_to_swedish(inp):
'''Converts the English Christmas card message to Swedish using small biligual lexicon Python dictionary
Time complexity of this function in worst condition is O(1)'''
trans_dict={'merry':'god', 'christmas':'jul', 'and':'och', 'happy':'gott', 'new':'nytt', 'year':'r'}
return ' '.join(list(map(lambda word: (trans_dict.get(word)) if word in trans_dict.keys() else word,inp.split(' '))))
if __name__=='__main__':
print(translate_to_swedish('merry christmas and happy new year'))
| true |
46bcbbe3a779b19a3c021be114ebb33846785e49 | thien-truong/learn-python-the-hard-way | /ex15.py | 617 | 4.21875 | 4 | from sys import argv
script, filename = argv
# A file must be opened before it can be read/print
txt = open(filename)
print "Here's your file {}:".format(filename)
# You can give a file a command (or a function/method) by using the . (dot or period),
# the name of the command, and parameteres.
print txt.read() # call a function on txt. "Hey txt! Do your read command with no parameters!"
# it is important to close files when you are done with them
txt.close()
print "I'll also ask you to type it again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
| true |
8a745e216a89e5a3f6c9d4111ea2bc38d37e4eb7 | thien-truong/learn-python-the-hard-way | /ex18.py | 1,209 | 4.59375 | 5 | # Fuctions: name the pieces of code the way ravirables name strings and numbers.
# They take arguments the way your scripts take argv
# They let you make "tiny commands"
# this one is like your scripts with argv
# this function is called "print_two", inside the () are arguments/parameters
# This is like your script with argv
# The keyword def introduces a function definition. It must be followed by the
# function name and the parenthesized list of formal parameters. The statements that
# form the body of the function start at the next line, and must be indented.
def print_two(*args):
"""print 2 arguments.""" # This is a docstring or documentation string. It should concisely sumarize the object's purpose
arg1, arg2 = args
print "arg1: {}, arg2: {}".format(arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: {}, arg2: {}".format(arg1, arg2)
# This just takes one argument
def print_one(arg1):
print "arg1: {}".format(arg1)
# This one takes no arguments:
def print_none():
print "I got nothing'."
print_two("zed","shaw")
print_two_again("zed","shaw")
print_one("First!")
print_none()
| true |
4a98b19419c953a3b12a1df262c3674a6b3a8967 | kahuroA/Python_Practice | /holiday.py | 1,167 | 4.53125 | 5 | """#Assuming you have a list containing holidays
holidays=['february 14', 'may 1', 'june 1', 'october 20']
#initialized a list with holiday names that match the holidays list
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check if the entered string is in our list of holidays
if month_date in holidays:
#get the index of the month date in holiday list
idx=holidays.index(month_date)
#use that index to get the holiday name from holiday_name list
print(holiday_name[idx])
else:
print('entered month and date do not correspond to a holiday')"""
holidays=['02-14','05-1','10-20']
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check if the entered string is in our list of holidays
if month_date in holidays:
#get the index of the month date in holiday list
idx=holidays.index(month_date)
#use that index to get the holiday name from holiday_name list
print(holiday_name[idx])
else:
print('entered month and date do not correspond to a holiday')
| true |
ec3010b56ca544f4910d38d6bf5c5dc8e61ff30e | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/filter.py | 883 | 4.15625 | 4 | # filter(function, iterable)
# returns a filter object of the original collection
# can be turned into a iterator
num_list = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, num_list))
print(evens)
users = [
{"username": "Samuel", "tweets": ["IO love cake", "IO love cookies"]},
{"username": "Katie", "tweets": ["IO love my cat"]},
{"username": "Jeff", "tweets": []},
{"username": "Bob123", "tweets": []},
{"username": "doggo_luvr", "tweets": ["dogs are the best"]},
{"username": "guitar_gal", "tweets": []}
]
# FILTER AND MAP TOGETHER
filtered_mapped = list(map(lambda user: user["username"].upper(),
filter(lambda u: not u["tweets"], users)))
print(filtered_mapped)
# Same as above
filtered_mapped_list_comp = [user["username"].upper() for user in users if not user["tweets"]]
print(filtered_mapped_list_comp)
| true |
c59e167d00e927e6ca41268b9490b3eb6722ad3d | l-ejs-l/Python-Bootcamp-Udemy | /Iterators-Generators/generator.py | 410 | 4.1875 | 4 | # A generator is returned by a generator function
# Instead of return it yields (return | yield)
# Can be return multiple times, not just 1 like in a normal function
def count_up_to(max_val):
count = 1
while count <= max_val:
yield count
count += 1
# counter now is a generator and i can call the method next(counter)
counter = count_up_to(5)
for i in count_up_to(5):
print(i)
| true |
d3b10c9fdd390fdf8068c1e343da8c334c034437 | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/zip.py | 437 | 4.4375 | 4 | # zip(iterable, iterable)
# Make an iterator that agregate elements from each of the iterables.
# Returns an iterator of tuples, where the i'th tuple contains the i'th element from each of the of the argument
# sequences or iterables.
# The iterator stops when the shortest input iterable is exhausted
first_zip = zip([1, 2, 3], [4, 5, 6])
print(list(first_zip)) # [(1, 4), (2, 5), (3, 6)]
print(dict(first_zip)) # {1: 4, 2: 5, 3: 6}
| true |
fae187d17f928d0791df8d0f4f7d5f678d09c5cd | AnanyaRao/Python | /tryp10.py | 224 | 4.28125 | 4 | def factorial(num):
fact=1;
i=1;
for i in range(i,num+1):
fact=fact*i;
return fact;
num=int(input('Enter the number:'))
fact=factorial(num);
print('The factorial of the number is:',fact) | true |
bf5ca4a2000a7d1ffa895ec758308b80ef1cb93a | calwoo/ppl-notes | /wengert/basic.py | 1,831 | 4.25 | 4 | """
Really basic implementation of a Wengert list
"""
# Wengert lists are lists of tuples (z, g, (y1,...)) where
# z = output argument
# g = operation
# (y1,...) = input arguments
test = [
("z1", "add", ["x1", "x1"]),
("z2", "add", ["z1", "x2"]),
("f", "square", ["z2"])]
# Hash table to store function representations of operator names
G = {
"add" : lambda a, b: a + b,
"square": lambda a: a*a}
# Hash table to store initialization values
val = {
"x1": 3,
"x2": 7}
print("x1 -> {}, x2 -> {}".format(val["x1"], val["x2"]))
# Evaluation function
def eval(f, val):
for z, g, inputs in f:
# Fetch operation
op = G[g]
# Apply to values
args = list(map(lambda v: val[v], inputs))
val[z] = op(*args)
return val[z]
print("eval(test) -> {}".format(eval(test, val)))
# To do backpropagation of the Wengert list, we need the derivatives
# of each of the primitive operators.
DG = {
"add" : [(lambda a, b: 1), (lambda a, b: 1)],
"square": [lambda a: 2*a]}
# We then go through the Wengert list in reverse, accumulating gradients
# when we pass through an operation.
def backpropagation(f, vals):
# Initialize gradient tape
delta = {"f": 1} # df/df = 1
# Go through Wengert list in reverse order
for z, g, inputs in reversed(f):
args = list(map(lambda v: vals[v], inputs))
for i in range(len(inputs)):
# Get gradient
dop = DG[g][i]
yi = inputs[i]
if yi not in delta:
delta[yi] = 0
# Apply chain rule
delta[yi] += delta[z] * dop(*args)
return delta
delta = backpropagation(test, val)
print("df/dx1 -> {}, df/dx2 -> {}".format(delta["x1"], delta["x2"]))
| true |
936ce5e1d8181e03d394ba350ef26c10ee575bb6 | sonias747/Python-Exercises | /Pizza-Combinations.py | 1,614 | 4.15625 | 4 | '''
On any given day, a pizza company offers the choice of a certain
number of toppings for its pizzas. Depending on the day, it provides
a fixed number of toppings with its standard pizzas.
Write a program that prompts the user (the manager) for the number of
possible toppings and the number of toppings offered on the standard
pizza and calculates the total number of different combinations of toppings.
Recall that the number of combinations of k items from n possibilities
is given by the formula nCk = n!/k!(n−k)!.
'''
'''
prompt user for number of possible toppings x
prompt user for number of toppings on standard pizza y
get factorial of x
get factorial of y
if y = x
print possible combinations 1
if y is greater than x
print possible combinations 0
if y is 1
print possible combinations y
else use binomial coefficient to get possible combinations
print possible combinations
'''
x = int(input('Enter number of possible toppings: '))
y = int(input('Enter number of toppings on standard pizza: '))
if x == 0:
xfact = 1
elif x == 1:
xfact = 1
else:
xfact = 1
for i in range(1, x + 1):
xfact *= i
continue
if y == 0:
yfact = 1
elif x == 1:
yfact = 1
else:
yfact = 1
for i in range(1, y + 1):
yfact *= i
continue
import sys
if y == x :
print('Possible Combinations: 1')
sys.exit()
if y > x:
print('Possible Combinations: 0')
sys.exit()
if y == 1:
print('Possible Combinations: ', x)
else:
posscomb = xfact // (yfact*(x-y))
print('Possible Combinations:', posscomb)
| true |
62021b456a4f6fbaeed24422fa09429698a7459d | ethanschreur/python-syntax | /words.py | 346 | 4.34375 | 4 | def print_upper_words(my_list, must_start_with):
'''for every string in my_list, print that string in all uppercase letters'''
for word in my_list:
word = word.upper()
if word[0] in must_start_with or word[0].lower() in must_start_with:
print(word)
print_upper_words(['ello', 'hey', 'yo', 'yes'], {"h", "y"})
| true |
b5887edb1d489421105fe45ca7032fb136c479df | KenMatsumoto-Spark/100-days-python | /day-19-start/main.py | 1,614 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
#
# def move_forwards():
# tim.forward(10)
#
#
# def move_backwards():
# tim.backward(10)
#
#
# def rotate_clockwise():
# tim.right(10)
#
#
# def rotate_c_clockwise():
# tim.left(10)
#
#
# def clear():
# tim.penup()
# tim.clear()
# tim.home()
# tim.pendown()
#
#
# screen.listen()
# screen.onkey(key="w", fun=move_forwards)
# screen.onkey(key="s", fun=move_backwards)
# screen.onkey(key="d", fun=rotate_clockwise)
# screen.onkey(key="a", fun=rotate_c_clockwise)
# screen.onkey(key="c", fun=clear)
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race?")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-75, -45, -15, 15, 45, 75]
all_turtles = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-230, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
is_race_on = False
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
if turtle.xcor() > 230:
is_race_on = False
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You've Won! The {winning_color} turtle is the winner!")
else:
print(f"You Lost! The {winning_color} turtle is the winner!")
rand_dist = random.randint(0, 10)
turtle.forward(rand_dist)
screen.exitonclick()
| true |
c56d992234d558fd0b0b49aa6029d6d287e90f2a | ARSimmons/IntroToPython | /Students/Dave Fugelso/Session 2/ack.py | 2,766 | 4.25 | 4 | '''
Dave Fugelso Python Course homework Session 2 Oct. 9
The Ackermann function, A(m, n), is defined:
A(m, n) =
n+1 if m = 0
A(m-1, 1) if m > 0 and n = 0
A(m-1, A(m, n-1)) if m > 0 and n > 0.
See http://en.wikipedia.org/wiki/Ackermann_funciton
Create a new module called ack.py in a session02 folder in your student folder.
In that module, write a function named ack that performs Ackermann's function.
Write a good docstring for your function according to PEP 257.
Ackermanns function is not defined for input values less than 0. Validate inputs to your function and return None if they are negative.
The wikipedia page provides a table of output values for inputs between 0 and 4. Using this table, add a if __name__ == "__main__": block to test your function.
Test each pair of inputs between 0 and 4 and assert that the result produced by your function is the result expected by the wikipedia table.
When your module is run from the command line, these tests should be executed. If they all pass,
print All Tests Pass as the result.
Add your new module to your git clone and commit frequently while working on your implementation. Include good commit messages that explain concisely both what you are doing and why.
When you are finished, push your changes to your fork of the class repository in GitHub. Then make a pull request and submit your assignment in Canvas.
'''
#Ackermann function
def ack(m, n):
'''
Calculate the value for Ackermann's function for m, n.
'''
if m < 0 or n < 0: return None
if m == 0: return n+1
if n == 0: return ack(m-1, 1)
return ack (m-1, ack (m, n-1))
class someClass (object):
def __init__(self):
self.setBody('there')
def afunc (self, a):
print a, self.getBody()
def getBody(self):
return self.__body
def setBody(self, value):
self.__body = value
body = property(getBody, setBody, None, "Body property.")
if __name__ == "__main__":
'''
Unit test for Ackermann function. Print table m = 0,4 and n = 0,4.
'''
#Print nicely
print 'm/n\t\t',
for n in range(0,5):
print n, '\t',
print '\n'
for m in range (0,4):
print m,'\t',
for n in range(0,5):
print '\t',
print ack(m, n),
print
# for the m = 4 row, just print the first one (n = 0) otherwise we hit a stack overflow (maximum resursion)
m = 4
print m,'\t',
for n in range(0,1):
print '\t',
print ack(m, n),
print '\t-\t-\t-\t-'
print 'All Tests Pass'
s = someClass ()
s.afunc('hello')
s.body = 'fuck ya!'
s.afunc('hello')
s.body = 'why not?' | true |
688ede91119829d5ec4b75452ef18a5a29d6bd29 | akidescent/GWC2019 | /numberWhile.py | 1,018 | 4.25 | 4 | #imports the ability to get a random number (we will learn more about this later!)
from random import *
#Generates a random integer.
aRandomNumber = randint(1, 20) #set variable aRandomNumber to random integer (1-20)
#can initialize any variable
# For Testing: print(aRandomNumber)
numGuesses = 0
while True: #set a forever loop
guess = input("You have 20 tries. Guess a number between 1 and 20 (inclusive): ") #getting user input, a string
if not guess.isnumeric(): # checks if a string is only digits 0 to 20
print("That's not a positive whole number, try again!")
continue
else:
guess = int(guess)
numGuesses += 1
if aRandomNumber == guess:
print("Congradulations, you guessed the right number!")
print(aRandomNumber)
break
elif (aRandomNumber < guess):
print("Sorry your guess is too high, that's not it.")
elif (aRandomNumber > guess):
print("Sorry your guess is too low, that's not it.")
if numGuesses >= 20: #number of tries >=2
print("Sorry, you ran out of tries.")
break
| true |
42f6e8a1a8cbd172c92d6ba4ad7a115ac3982bb7 | EugeneStill/PythonCodeChallenges | /open_the_lock.py | 2,132 | 4.125 | 4 | import unittest
import collections
# https://www.geeksforgeeks.org/deque-in-python/
class OpenTheLock(unittest.TestCase):
"""
You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0' through '9'.
The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'.
Each move consists of turning one wheel one slot.
The lock initially starts at '0000', a string representing the state of the 4 wheels.
You are given a list of deadends dead ends, meaning if the lock displays any of these codes,
the wheels of the lock will stop turning and you will be unable to open it.
Given a target representing the value of the wheels that will unlock the lock,
return the minimum total number of turns required to open the lock, or -1 if it is impossible.
"""
def open_the_lock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
dead_set = set(deadends)
queue = collections.deque([('0000', 0)])
visited = set('0000')
while queue:
(wheel_state, turns) = queue.popleft()
if wheel_state == target:
return turns
elif wheel_state in dead_set:
continue
for i in range(4):
# for each slot in wheel, move down 1, up 1 to get new combos
digit = int(wheel_state[i])
for move in [-1, 1]:
new_digit = (digit + move) % 10
new_combo = wheel_state[:i]+str(new_digit)+wheel_state[i+1:]
if new_combo not in visited:
visited.add(new_combo)
queue.append((new_combo, turns+1))
return -1
def test_open_lock(self):
self.assertEqual(self.open_the_lock(["0201","0101","0102","1212","2002"], "0202"), 6)
self.assertEqual(self.open_the_lock(["8888"], "0009"), 1)
self.assertEqual(self.open_the_lock(["8887","8889","8878","8898","8788","8988","7888","9888"], "8888"), -1)
| true |
3ea411d749f483c8fd5c63ad0ac7fd8a5c8c0a01 | EugeneStill/PythonCodeChallenges | /rotting_oranges.py | 2,767 | 4.125 | 4 | import unittest
from collections import deque
class OrangesRotting(unittest.TestCase):
"""
You are given an m x n grid where each cell can have one of three values:
0 representing an empty cell,
1 representing a fresh orange, or
2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
Return minimum number of minutes that must pass until no cell has a fresh orange. If this is impossible, return -1.
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: Bottom left corner (row 2, column 0) is never rotten, bc rotting only happens 4-directionally.
"""
def oranges_rotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
# Time complexity: O(rows * cols) -> each cell is visited at least once
# Space complexity: O(rows * cols) -> in the worst case if all the oranges are rotten they will be added to the queue
rows = len(grid)
if rows == 0: # check if grid is empty
return -1
EMPTY, FRESH, ROTTEN = 0, 1, 2
cols, fresh_cnt, minutes_passed, rotten = len(grid[0]), 0, 0, deque()
# visit each cell in the grid & update fresh count & rotten queue
for r in range(rows):
for c in range(cols):
if grid[r][c] == ROTTEN:
rotten.append((r, c))
elif grid[r][c] == FRESH:
fresh_cnt += 1
# If there are rotten oranges in the queue and there are still fresh oranges in the grid keep looping
while rotten and fresh_cnt > 0:
# update the number of minutes for each level pass
minutes_passed += 1
# process rotten oranges on the current level
for _ in range(len(rotten)):
row, col = rotten.popleft()
# visit all the valid adjacent cells
for new_row, new_col in [(row-1,col), (row+1,col), (row,col-1), (row,col+1)]:
if not 0 <= new_row < rows or not 0 <= new_col < cols or grid[new_row][new_col] != FRESH:
continue
# update the fresh count, mark cell rotten and add to queue
fresh_cnt -= 1
grid[new_row][new_col] = ROTTEN
rotten.append((new_row, new_col))
return minutes_passed if fresh_cnt == 0 else -1
def test_ro(self):
grid1 = [[2,1,1],[1,1,0],[0,1,1]]
grid2 = [[2,1,1],[0,1,1],[1,0,1]]
self.assertEqual(self.oranges_rotting(grid1), 4)
self.assertEqual(self.oranges_rotting(grid2), -1) | true |
59a8864a5f317ead31eb8d93246776eed2342fec | EugeneStill/PythonCodeChallenges | /word_break_dp.py | 1,621 | 4.125 | 4 | import unittest
class WordBreak(unittest.TestCase):
"""
Given a string s and a dictionary of strings wordDict, return true if s can be segmented
into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
"""
def word_break(self, s, words):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False] * len(s)
for i in range(len(s)):
for w in words:
# does current word end at i
# (AND dp[idx_before_word] is True (meaning a valid word ended right before this word)
# OR idx_before_word == -1 (meaning its ok that there was no valid word before it))
idx_before_word = i - len(w)
if w == s[idx_before_word + 1:i + 1] and (dp[idx_before_word] or idx_before_word == -1):
dp[i] = True
return dp[-1]
def test_word_break(self):
words = ["cats","dog","sand","and","cat", "pen", "apple"]
good_string = "applepenapple"
bad_string = "catsandog"
self.assertTrue(self.word_break(good_string, words))
self.assertFalse(self.word_break(bad_string, words))
| true |
26d1d171bfa5feab074dd6dafef2335befbc4ca7 | EugeneStill/PythonCodeChallenges | /unique_paths.py | 2,367 | 4.28125 | 4 | import unittest
import math
class UniquePaths(unittest.TestCase):
"""
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]).
The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]).
The robot can only move either down or right at any point in time.
Given 2 integers m and n, return the number of unique paths that the robot can take to reach the bottom-right corner
The test cases are generated so that the answer will be less than or equal to 2 * 109.
"""
# 2. Math solution
# Note, that we need to make overall n + m - 2 steps, and exactly m - 1 of them need to be right moves and n - 1 down steps. By definition this is numbef of combinations to choose n - 1 elements from n + m - 2.
# Complexity: time complexity is O(m+n), space complexity is O(1).
def unique_paths(self, rows, cols):
dp = [1] * cols
print("\n" + str(dp))
for row in range(1, rows):
print("CHECKING ROW {}".format(row))
for col in range(1, cols):
dp[col] = dp[col - 1] + dp[col]
print(str(dp))
return dp[-1] if rows and cols else 0
# 2. Math solution
# Note, that we need to make overall n + m - 2 steps, and exactly m - 1 of them need to be right moves
# and n - 1 down steps. By definition this is number of combinations to choose n - 1 elements from n + m - 2.
# Complexity: time complexity is O(m+n), space complexity is O(1).
def unique_paths_math(self, m, n):
print("FACT MN {}".format(math.factorial(m+n-2)))
print("FACT M {}".format(math.factorial(m -1)))
print("FACT N {}".format(math.factorial(n - 1)))
return math.factorial(m+n-2)//math.factorial(m-1)//math.factorial(n-1)
def test_unique_paths(self):
print(self.unique_paths(3, 7))
# LOGGING
# [1, 1, 1, 1, 1, 1, 1] # INIT ARRAY FOR ROW 0 with 1's
# CHECKING ROW 1 # FROM HERE OUT, ADD COL[COL-1] TO COL TO UPDATE EACH COL VALUE
# [1, 2, 1, 1, 1, 1, 1]
# [1, 2, 3, 1, 1, 1, 1]
# [1, 2, 3, 4, 1, 1, 1]
# [1, 2, 3, 4, 5, 1, 1]
# [1, 2, 3, 4, 5, 6, 1]
# [1, 2, 3, 4, 5, 6, 7]
# CHECKING ROW 2
# [1, 3, 3, 4, 5, 6, 7]
# [1, 3, 6, 4, 5, 6, 7]
# [1, 3, 6, 10, 5, 6, 7]
# [1, 3, 6, 10, 15, 6, 7]
# [1, 3, 6, 10, 15, 21, 7]
# [1, 3, 6, 10, 15, 21, 28] | true |
fdd5987f684a90e78ba5622fd37919c43951bd20 | EugeneStill/PythonCodeChallenges | /course_prerequisites.py | 2,711 | 4.34375 | 4 | import unittest
import collections
class CoursePrereqs(unittest.TestCase):
"""
There are a total of num_courses courses you have to take, labeled from 0 to num_courses - 1.
You are given an array prerequisites where prerequisites[i] = [ai, bi]
meaning that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses.
If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Input: num_courses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
"""
def get_order(self, num_courses, prerequisites):
"""
:type num_courses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
# map courses to preqs and preqs to courses
course_preq_dic = {course: set() for course in range(num_courses)}
preq_course_dic = collections.defaultdict(set)
for course, preq in prerequisites:
course_preq_dic[course].add(preq)
preq_course_dic[preq].add(course)
# add any courses without preqs to new taken_q
taken_q = collections.deque([])
for course, preq in course_preq_dic.items():
if len(preq) == 0:
taken_q.append(course)
# go through q to see if we can take expected num of courses
taken = []
while taken_q:
course = taken_q.popleft()
taken.append(course)
if len(taken) == num_courses:
return taken
# use preq_course_dic to check every dependent course that had the course we just took as a preq
for dependent in preq_course_dic[course]:
# remove the taken course from the course_preq_dic for any dependent courses
course_preq_dic[dependent].remove(course)
# if dependent course no longer has any preqs then we can add it as course to take
if not course_preq_dic[dependent]:
taken_q.append(dependent)
return False
def test_prereqs(self):
prereqs = [[1,0],[2,0],[3,1],[3,2]]
acceptable_results = [[0,1,2,3], [0,2,1,3]]
self.assertIn(self.get_order(len(prereqs), prereqs), acceptable_results) | true |
57d16b965de6e4f82979f42656042af956145410 | EugeneStill/PythonCodeChallenges | /reverse_polish_notation.py | 2,516 | 4.21875 | 4 | import unittest
import operator
class ReversePolishNotation(unittest.TestCase):
"""
AKA Polish postfix notation or simply postfix notation
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.
"""
def reverse_polish_notation(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': 'custom'
}
stack = []
for t in tokens:
if t not in ops:
stack.append(int(t))
continue
r, l = stack.pop(), stack.pop()
if t == '/':
stack.append(int(l/r))
else:
stack.append(ops[t](l, r))
return stack.pop()
#
#
# stack = []
# print("\n" + str(tokens))
# for t in tokens:
# if t not in "+-*/":
# stack.append(int(t))
# else:
# r, l = stack.pop(), stack.pop()
# if t == "+":
# stack.append(l+r)
# elif t == "-":
# stack.append(l-r)
# elif t == "*":
# stack.append(l*r)
# else:
# stack.append(int(float(l)/r))
# print(str(stack))
# return stack.pop()
def test_rpn(self):
input1 = ["2","1","+","3","*"]
input2 = ["4","13","5","/","+"]
input3 = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
self.assertEqual(self.reverse_polish_notation(input1), 9)
self.assertEqual(self.reverse_polish_notation(input2), 6)
self.assertEqual(self.reverse_polish_notation(input3), 22)
# LOGGING
# ['2', '1', '+', '3', '*']
# [2]
# [2, 1]
# [3]
# [3, 3]
# [9]
#
# ['4', '13', '5', '/', '+']
# [4]
# [4, 13]
# [4, 13, 5]
# [4, 2]
# [6]
#
# ['10', '6', '9', '3', '+', '-11', '*', '/', '*', '17', '+', '5', '+']
# [10]
# [10, 6]
# [10, 6, 9]
# [10, 6, 9, 3]
# [10, 6, 12]
# [10, 6, 12, -11]
# [10, 6, -132]
# [10, 0]
# [0]
# [0, 17]
# [17]
# [17, 5]
# [22] | true |
47656bdd5d6b6f46cb957f38ecc32184198f9829 | MariamBilal/python | /List.py | 1,008 | 4.65625 | 5 | # Making and Printing list
my_list = ['fish','dog','cat','horse','frog','fox','parrot','goat']
print(my_list)
#Using Individual Values from a List
for i in my_list:
print(i)
#Accessing elements in a List
print(my_list[0])
#To title the the items in list.
print(my_list[2].title())
#To print last character from the list.
print(my_list[-1])
#Modifying Elements in a List
my_list[0] = 'jelly fish'
print(my_list)
#Adding Elements to the end of a List
my_list.append('sparrow')
print(my_list)
#Inserting Elements into a List
my_list.insert(0,'kingfisher')
print(my_list)
#removing an Item Using the del Statement
del my_list[0]
print(my_list)
#removing an Item Using the pop() Method
pop_item = my_list.pop(3)
print(my_list)
print(pop_item)
#removing an Item by Value.
my_list.remove('frog')
print(my_list)
#Sorting List:
my_list.sort()
print(my_list)
#Printing a List in Reverse Order
my_list.reverse()
print(my_list)
#Finding the Length of a List
len_of_list = len(my_list)
print(len_of_list) | true |
4bc82f2bdf496610241ad272ee9f76b69713c51d | codilty-in/math-series | /codewars/src/highest_bi_prime.py | 1,100 | 4.1875 | 4 | """Module to solve https://www.codewars.com/kata/highest-number-with-two-prime-factors."""
def highest_biPrimefac(p1, p2, end):
"""Return a list with the highest number with prime factors p1 and p2, the
exponent for the smaller prime and the exponent for the larger prime."""
given_primes = set([p1, p2])
k1 = 0
k2 = 0
highest = 0
for n in range(end, 0, -1):
pf = prime_factors(n, given_primes)
if given_primes == set(pf):
if pf.count(p1) > k1 and pf.count(p2) > k2:
k1 = pf.count(p1)
k2 = pf.count(p2)
highest = n
if (p1 ** k1) * (p2 ** k2) > n:
return [highest, k1, k2]
return None
def prime_factors(n, given_primes):
"""Return a list with all prime factors of n."""
factors = []
if n < 2:
return factors
p = 2
while n >= (p * p):
if n % p:
p += 1
else:
if p not in given_primes:
return []
n = n // p
factors.append(p)
factors.append(n)
return factors
| true |
d20b15088e93c670f2ddd84ec8d2b78ad0d63199 | codilty-in/math-series | /codewars/src/surrounding_prime.py | 1,328 | 4.25 | 4 | def eratosthenes_step2(n):
"""Return all primes up to and including n if n is a prime
Since we know primes can't be even, we iterate in steps of 2."""
if n >= 2:
yield 2
multiples = set()
for i in range(3, n+1, 2):
if i not in multiples:
yield i
multiples.update(range(i*i, n+1, i))
def prime(n, primes):
"""Return True if a given n is a prime number, else False."""
if n > 5 and n % 10 == 5:
return False
for p in primes:
if n % p == 0:
return False
return True
def get_next_prime(n, primes, direction=1):
"""Return the next prime of n in given direction."""
if direction > 0:
start = n + 1 if n % 2 == 0 else n + 2
step = 2
stop = n * n
else:
start = n -1 if n % 2 == 0 else n - 2
step = -2
stop = 0
prime_generator = (x for x in xrange(start, stop, step) if prime(x, primes))
return prime_generator.next()
def prime_bef_aft(n):
"""Return the first pair of primes between m and n with step g."""
#n needs to start out as an odd number so we can step over known composites
primes = [p for p in eratosthenes_step2(int(n // 2))]
before = get_next_prime(n, primes, -1)
after = get_next_prime(n, primes, 1)
return [before, after]
| true |
7a291a64dea198b5050b83dc70f5e30bcf8876f5 | codilty-in/math-series | /codewars/src/nthfib.py | 524 | 4.1875 | 4 | """This module solves kata https://www.codewars.com/kata/n-th-fibonacci."""
def original_solution(n):
"""Return the nth fibonacci number."""
if n == 1:
return 0
a, b = 0, 1
for i in range(1, n - 1):
a, b = b, (a + b)
return b
#better solution
def nth_fib(n):
"""Return the nth fibonacci number. Per the kata, f(1) is supposed to be
0 so the fibonacci sequence for this kata was not indexed at 0."""
a, b = 0, 1
for __ in range(n-1):
a, b = b, a + b
return a
| true |
9b4a1f7ef0879176a70ee0324c49914d24c76c80 | achiengcindy/Lists | /append.py | 347 | 4.375 | 4 | # define a list of programming languages
languages = ['java', 'python', 'perl', 'ruby', 'c#']
# append c
languages.append('c')
print(languages)
# Output : ['java', 'python' ,'perl', 'ruby', 'c#', 'c']
# try something cool to find the last item,
# use **negative index** to find the value of the last item
print(languages[-1])
# should give you c
| true |
d7a0d968a0b1155703ec27009f4c673bab32416f | johnmcneil/w3schools-python-tutorials | /2021-02-09.py | 2,405 | 4.40625 | 4 | # casting to specify the data type
x = str(3)
y = int(3)
z = float(3)
# use type() to get the data type of a variable
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))
# you can use single or double quotes
# variables
# variable names are case-sensitive.
# must start with a letter or the underscore character
# cannot start with a number
# can containe alpha-numeric characters and underscores
# camel case
myVariableName = "camel case"
# Pascal Case
MyVariableName = "Pascal case"
# snake case
my_variable_name = "snake case"
# assigning multiple variables in a line
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
# assigning the same value to multiple variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
# unpacking
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
# output variables with print: variable plus text
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
# for numbers, + inside print works as addition
x = 5
y = 10
print(x + y)
# variable with global scope
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
# variable with local scope
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
# global keyword
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
# data types
# assignment of a value, constructor function
# text
str
x = str("Hello World")
x = "Hello World"
# numeric
int
x = int(20)
x = 20
float
x = float(20.5)
x = 20.5
complex
x = complex(1j)
x = 1j
# sequence
list
x = list(("apple", "banana", "cherry"))
x = ["apple", "banana", "cherry"]
tuple
x = tuple(("apple", "banana", "cherry"))
x = ("apple", "banana", "cherry")
range
x = range(6)
x = range(6)
# mapping
dict
x = dict(name="John", age=36)
x = {"name": "John", "age": 36}
# set
set
x = set(("apple", "banana", "cherry"))
x = {"apple", "banana", "cherry"}
frozenset
x = frozenset(("apple", "banana", "cherry"))
x = frozenset({"apple", "banana", "cherry"})
# boolean
bool
x = bool(5)
x = True
# binary
bytes
x = bytes(5)
x = b"Hello"
bytearray
x = bytearray(5)
x = bytearray(5)
memoryview
x = memoryview(bytes(5))
x = memoryview(bytes(5))
# Numbers
# Float can be scientifice with an e to indicate the power of 10
z = -87.7e100
| true |
df2a11b4b05eb2a086825a7a996347f0f56a75ee | johnmcneil/w3schools-python-tutorials | /2021-03-05.py | 1,466 | 4.65625 | 5 | # regexp
# for regular expressions, python has the built-in package re
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
print(x)
# regex functions
# findall() - returns a list of all matches
x = re.findall("ai", txt)
print(x)
x = re.findall("sdkj", txt)
print(x)
# search() - returns a match object if there is a match anywhere in the string
x = re.search("ai", txt)
print(x)
x = re.search("Portugal", txt)
print(x)
# split() - returns a list where the string has been split at each match
x = re.split("i", txt)
print(x)
x = re.split("\s", txt)
print(x)
x = re.split("q", txt)
print(x)
# maxsplit parameter
# e.g. split string only at first occurence
x = re.split("\s", txt, 1)
print(x)
# sub() - replaces one or many matches with a string
x = re.sub("\s", "9", txt)
print(x)
# count parameter controls the number of replacements
x = re.sub("\s", "9", txt, 2)
print(x)
# Match Object
# contains information about the search and its result
# if there is no match, None will be returned
txt = "The rain in Spain"
x = re.search("ai", txt)
print(x)
# Match object properties and methods
# span() - returns a tuple containing the start and end positions of the match
print(x.span())
# string - print the string passed into the function
print(x.string)
# print the part of the string where there was a match
print(x.group())
# pip
import camelcase
c = camelcase.CamelCase()
txt = "hello world!"
print(c.hump(txt))
| true |
c31786c6ad2645c08348c68592c2e95c1b924be9 | krishnakesari/Python-Fund | /Operators.py | 1,296 | 4.15625 | 4 |
# Division (/), Integer Division (//), Remainder (%), Exponent (**), Unary Negative (-), Unary Positive (+)
y = 5
x = 3
z = x % y
z = -z
print(f'result is {z}')
# Bitwise operator (& | ^ << >>)
x = 0x0a
y = 0x02
z = x << y
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}')
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
# Comparision Operators
x = 42
y = 73
if x < y:
print('comparision is true')
else:
print('comparision is false')
if x > y:
print('comparision is true')
else:
print('comparision is false')
if x != y:
print('comparision is true')
else:
print('comparision is false')
if x == y:
print('comparision is true')
else:
print('comparision is false')
# Boolean Operators
a = True
b = False
x = ('bear', 'bunny', 'tree')
y = 'tree'
if a and b:
print('expression is true')
else:
print('expression is false')
if a or b:
print('expression is true')
else:
print('expression is false')
if not b:
print('expression is true')
else:
print('expression is false')
if y and x:
print('expression is true')
else:
print('expression is false')
if y is x[2]:
print('expression is true')
else:
print('expression is false')
print(id(y))
print(id(x[2]))
# Operator Precedence
print( 2 + 4 * 5)
| true |
4e0088bb25588855455f58537abbabb1769b2459 | ETDelaney/automate-the-boring-stuff | /05-01-guess-the-number.py | 1,343 | 4.21875 | 4 | # a game for guessing a number
import random
num_of_chances = 5
secret_number = random.randint(1,20)
#print(secret_number)
print('Hello, what is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 0 and 20.')
print('Can you guess the number? I will give you ' + str(num_of_chances) + ' chances.')
for guessesTaken in range(num_of_chances+1):
if guessesTaken == num_of_chances:
print('You have run out of chances... I was thinking of the number: ' + str(secret_number))
break
try:
if guessesTaken == num_of_chances-1:
print('You have 1 guess remaining, uh oh ;-) \n')
else:
print('You have ' + str(num_of_chances-guessesTaken) + ' guesses remaining.\n')
guess = int(input('Guess: '))
if int(guess) < secret_number:
print('Sorry, too low.')
elif int(guess) > secret_number:
print('Sorry, too high.')
else:
print('Congrats,' + name + '! That is the correct guess.')
if guessesTaken+1 == 1:
print('You got it in a single try!')
else:
print('You got it in ' + str(guessesTaken + 1) + ' tries.')
break
except:
print('You need to enter an integer ... try again.')
| true |
8d37af2dc7cf5fba984f7c35f343c6741a30653e | rustybailey/Project-Euler | /pe20.py | 425 | 4.15625 | 4 | """
n! means n * (n - 1) * ... * 3 * 2 * 1
For example, 10! = 10 * 9 * ... 3 * 2 * 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
import math
def sumFactorial(n):
num = math.factorial(n)
total = 0
while (num > 0):
total += num % 10
num = math.trunc(num / 10)
return total
print sumFactorial(100) | true |
b495c945cfed8db9787f8d9fab4e3c02a5232dfb | shagunsingh92/PythonExercises | /FaultyCalculator.py | 1,122 | 4.53125 | 5 | import operator
'''Exercise: My_faulty_computer
this calculator will give correct computational result for all the numbers except [45*3 = 555, 56+9=77
56/6=4]
'''
def my_faulty():
allowed_operator = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}
# ask the user for an input
a = int(input('give me a number:'))
b = int(input('give me another number:'))
opp = input('What operation do you want to perform: ')
if a == 45 and b == 3 and opp == '*':
print(555)
elif a == 56 and b == 9 and opp == '+':
print(77)
elif a == 56 and b == 6 and opp == '/':
print(4)
# https://docs.python.org/3/library/operator.html check the documentation on operators
# operator.add(a,b) is the basic representation
elif opp in ['+', '-', '*', '/']:
result = allowed_operator[opp](a, b)
print(result)
else:
print('I am not capable of performing that computation.')
while True:
my_faulty()
command = input('Do you want to calculate more? ')
if command == 'Yes':
continue
else:
break
| true |
3302de8bad34c27c4ed7216b5d4b9fb786979c6c | allenc8046/CTI110 | /P4HW4_Chris Allen.py | 356 | 4.21875 | 4 | import turtle
redCross = turtle.Screen()
x = turtle.Turtle()
x.color("red") # set x turtle color
x.pensize(3) # set x turtle width
print("It's a red cross!")
print ()
# use a for loop
for redCross in range (4):
x.forward(150)
x.left(90)
x.forward(150)
x.left(90)
x.forward(150)
x.right(90)
| true |
00129adf4cbb2fda2215c499ba7392ca17e90b10 | rafaelalmeida2909/Python-Data-Structures | /Linked Queue.py | 2,268 | 4.28125 | 4 | class Node:
"""Class to represent a node in Python3"""
def __init__(self, data):
self.data = data # Node value
self.next = None # Next node
class LinkedQueue:
"""Class to represent a Linked Queue(without priority) in Python3"""
def __init__(self):
self._front = None # The first element of queue
self._back = None # The last element of queue
self._size = 0 # The size of queue
def enqueue(self, elem):
"""Inserts an element at the end of the queue"""
if self._size == 0:
aux = Node(elem)
self._front = aux
self._back = aux
else:
pointer = self._back
aux = Node(elem)
pointer.next = aux
self._back = aux
self._size += 1
def dequeue(self):
"""Removes and returns the first element from the queue"""
if self._size == 0:
raise Exception("Empty queue")
elem = self._front.data
self._front = self._front.next
self._size -= 1
return elem
def length(self):
"""Returns the size of queue"""
return self._size
def first(self):
"""Returns the first element from queue"""
if self._size == 0:
raise Exception("Empty queue")
return self._front.data
def last(self):
"""Returns the last element from queue"""
if self._size == 0:
raise Exception("Empty queue")
return self._back.data
def empty(self):
"""Returns true if the queue is empty, otherwise, it returns false"""
if self._size == 0:
return True
return False
def __del__(self):
"""Destructor method"""
def __str__(self):
"""Method for representing the linked queue (user)"""
rep = "\033[1;31m" + "first" + "\033[0;0m" + " -> "
pointer = self._front
while pointer != None:
rep += f"{pointer.data} -> "
if pointer.next is None:
break
pointer = pointer.next
rep += "\033[1;34mNone\033[0;0m"
return rep
def __repr__(self):
"""Method for representing the linked queue (developer)"""
return str(self)
| true |
b314cc818cdf04d37dbc36fae60f5f0ca354182e | divineunited/casear_cipher | /casear_cipher.py | 2,649 | 4.125 | 4 | def casear(message, n, encrypt=True):
'''This casear encryption allows for undercase and capital letters. Pass a message to encrypt or decrypt, n number of positions (must be less than 26) where n will add to the alphabet for encryption and subtract for decryption, and optional encrypt=False to allow for decryption of a message. The message must not include any non alphabetic characters besides a space'''
# creating our dictionary with number key and letter value
num_let = {i:let for i, let in enumerate('abcdefghijklmnopqrstuvwxyz')}
# creating our dictionary with corresponding letter key and number value
let_num = {let:i for i, let in enumerate('abcdefghijklmnopqrstuvwxyz')}
# creating versions for the capital letters
NUM_LET = {i:let for i, let in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ')}
LET_NUM = {let:i for i, let in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ')}
final = ''
# encryption
if encrypt:
# going through our message and replacing each letter with a coded number by adding n to each letter and using the dictionary.
for letter in message:
# if this letter is a space, leave it
if letter in ' ':
final += letter
# if letter is non capital
elif letter in let_num.keys():
# if this is one of the later numbers at the end of the dictionary, loop around to the beginning
if let_num[letter] + n > 25:
final += num_let[let_num[letter]+n-26]
else:
final += num_let[let_num[letter]+n]
# if letter is capitalized
else:
if LET_NUM[letter] + n > 25:
final += NUM_LET[LET_NUM[letter]+n-26]
else:
final += NUM_LET[LET_NUM[letter]+n]
return final
# decryption
else:
for letter in message:
if letter == ' ':
final += letter
elif letter in let_num.keys():
if let_num[letter] - n < 0:
final += num_let[let_num[letter]-n+26]
else:
final += num_let[let_num[letter]-n]
else:
if LET_NUM[letter] - n < 0:
final += NUM_LET[LET_NUM[letter]-n+26]
else:
final += NUM_LET[LET_NUM[letter]-n]
return final
# main testing:
message = 'This is a test of the excellent Casear Cipher'
print(casear(message, 3))
cipher = 'Wklv lv d whvw ri wkh hafhoohqw Fdvhdu Flskhu'
print(casear(cipher,3,encrypt=False)) | true |
7c4f5a725fb49a86333809956941866f45d0effb | MeghaSajeev26/Luminar-Python | /Advance Python/Test/pgm5.py | 448 | 4.4375 | 4 | #5. What is method overriding give an example using Books class?
#Same method and same arguments --- child class's method overrides parent class's method
class Books:
def details(self):
print("Book name is Alchemist")
def read(self):
print("Book is with Megha")
class Read_by(Books):
def read(self):
print("Book is with Akhil")
b=Read_by()
b.read()
#method overloading---consider no of arguments while callling | true |
9f9a506baa32ca4d7f7c69ed5d66eac431d0c37f | MeghaSajeev26/Luminar-Python | /Looping/for loop/demo6.py | 212 | 4.21875 | 4 | #check whether a number is prime or not
num=int(input("enter a number"))
flag=0
for i in range(2,num):
if(num%i==0):
flag=1
if(flag>0):
print(num,"is not a prime")
else:
print(num,"is prime") | true |
05984d56459fb9738b27f9bc1fe070ede6d948ea | uttam-kr/PYTHON | /Basic_oops.py | 1,042 | 4.1875 | 4 | #!/usr/bin/python
#method - function inside classes
class Employee():
#How to initialize attribute
#init method
def __init__(self, employee_name, employee_age, employee_weight, employee_height):
print('constructor called')
#('init method or constructor called') ---->This __init__ method called constructor
self.name = employee_name
self.age = employee_age
self.weight = employee_weight
self.height = employee_height
def Developer(self):
print("Developer {}".format(self.name))
def is_eligible(self):
print(self.age)
#Variable define under __init__ method called instance variable
#An object employee1 is created using the constructor of the class Employee
employee1 = Employee("Uttam", "age 25", "65 kg", "175 cm")
#self = employee1
#Whenever we create object __init__ gets called, it create space in memory so that we can work with objects.
print(employee1.name)
print(employee1.age)
print(employee1.weight)
print(employee1.height)
print('method call')
employee1.Developer() #Method call
employee1.is_eligible()
| true |
49f4d48bc9ccc29332f76af833fefa0383defea3 | fadhilahm/edx | /NYUxFCSPRG1/codes/week7-functions/lectures/palindrome_checker.py | 631 | 4.15625 | 4 | def main():
# ask for user input
user_input = input("Please enter a sentence:\n")
# sterilize sentence
user_input = sterilize(user_input)
# check if normal equals reversed
verdict = "is a palindrome" if user_input == user_input[::-1] else "is not a palindrome"
# render result
print("Your sentence {}".format(verdict))
def sterilize(string):
# define value to be removed
forbidden = "!@#$%^&*()_-+={[}]|\\:;'<,>.?/ "
for char in string:
if char in forbidden:
string = string.replace(char, "")
# return lowercased string
return string.lower()
main() | true |
cd1f058045cc9414ca8d8f2d5ed0e7f0d4ef231d | suiody/Algorithms-and-Data-Structures | /Data Structures/Circular Linked List.py | 1,248 | 4.125 | 4 | """
* Author: Mohamed Marzouk
* --------------------------------------
* Circular Linked List [Singly Circular]
* --------------------------------------
* Time Complixty:
* Search: O(N)
* Insert at Head/Tail: O(1)
* Insert at Pos: O(N)
* Deletion Head/Tail: O(1)
* Deletion [middle / pos]: O(N)
* Space Complixty: O(N)
* Used Language: Python
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = self.tail = Node(None)
self.tail.next = self.head
self.head.next = self.tail
def add(self, data):
newNode = Node(data)
if self.head.data is not None:
self.tail.next = newNode
self.tail = newNode
newNode.next = self.head
else:
self.head = self.tail = newNode
newNode.next = self.head
def display(self):
current = self.head
if self.head is None:
print("List is empty")
return;
else:
print("Nodes of the circular linked list: ");
print(current.data)
while(current.next != self.head):
current = current.next;
print(current.data)
cllist = CircularLinkedList()
cllist.add(5)
cllist.add(2)
cllist.add(1)
cllist.add(3)
cllist.display()
| true |
16c3c7b2302a7fd892b67a00b09d41e058a3cff5 | sula678/python-note | /basic/if-elif-else.py | 233 | 4.125 | 4 | if 3 > 5:
print "Oh! 3 is bigger than 5!"
elif 4 > 5:
print "Oh! 4 is bigger than 5!"
elif 5 > 5:
print "Oh! 5 is bigger than 5!"
elif 6 > 5:
print "Of course, 6 is bigger than 5!"
else:
print "There is no case!"
| true |
e707b084c1932e484b5023eae4052fc606332c3c | mreboland/pythonListsLooped | /firstNumbers.py | 878 | 4.78125 | 5 | # Python's range() function makes it easy to generate a series of numbers
for value in range(1, 5):
# The below prints 1 to 4 because python starts at the first value you give it, and stops at the second value and does not include it.
print(value)
# To count to 5
for value in range(1, 6):
print(value)
# You can also pass 1 argument
for value in range(6):
print(value) # prints values 0-5
# Using range to make a list of numbers
# If you want to make a list of numbers, you can covert the results of range() directly into a list using the list() function.
numbers = list(range(1, 6))
print(numbers) # outputs [1, 2, 3, 4, 5]
# You can also use the range() function to tell python to skip numbers in a given range
# The third argument tells python to skip by 2
even_numbers = list(range(2, 11, 2))
print(even_numbers) # outputs [2, 4, 6, 8, 10]
| true |
8a9b9a790d09aa9e7710b48b67575553224a497b | EvheniiTkachuk/Lessons | /Lesson24/task1.py | 949 | 4.15625 | 4 | # Write a program that reads in a sequence of characters and prints
# them in reverse order, using your implementation of Stack.
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return self.array.pop()
def peek(self):
return self.__current()
def __current(self):
return self.array[self.count() - 1]
def count(self):
return len(self.array)
def __iter__(self):
self.index = self.count() - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration()
result = self.array[self.index]
self.index -= 1
return result
if __name__ == "__main__":
string = '123456789'
stack = MyStack()
for i in string:
stack.push(i)
for i in stack:
print(i, end=' ')
| true |
d69a710becdd434773d15def23dbe71e3c426b75 | EvheniiTkachuk/Lessons | /Lesson24/task3_2.py | 1,856 | 4.125 | 4 | # Extend the Queue to include a method called get_from_stack that
# searches and returns an element e from a queue. Any other element must
# remain in the queue respecting their order. Consider the case in which the element
# is not found - raise ValueError with proper info Message
class Queue:
def __init__(self):
self._items = []
def is_empty(self):
return bool(self._items)
def enqueue(self, item):
self._items.insert(0, item)
def dequeue(self):
return self._items.pop()
def size(self):
return len(self._items)
def get_from_queue(self, item):
try:
return self._items.pop(self._items.index(item))
except (ValueError, TypeError):
print(f'\nItem "{item}" don\'t found')
def __iter__(self):
self.index = len(self._items) - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration
self.index -= 1
return self._items[self.index + 1]
def __repr__(self):
representation = "<Queue>\n"
for ind, item in enumerate(reversed(self._items), 1):
representation += f"{ind}: {str(item)}\n"
return representation
def __str__(self):
return self.__repr__()
if __name__ == "__main__":
string = '123456789'
queue = Queue()
for i in string:
queue.enqueue(i)
for i in queue: # __iter__, __next__
print(i, end=' ')
print()
print(queue)
queue.get_from_queue('9')
queue.get_from_queue('8')
queue.get_from_queue('7')
print(queue)
queue.get_from_queue('5')
queue.get_from_queue('4')
queue.get_from_queue('3')
queue.get_from_queue('2')
print(queue)
queue.get_from_queue('test')
| true |
02ffe7089ad2b5c05246949bf9731c73130e3ebd | EvheniiTkachuk/Lessons | /Lesson24/task2.py | 1,596 | 4.15625 | 4 | # Write a program that reads in a sequence of characters,
# and determines whether it's parentheses, braces, and curly brackets are "balanced."
class MyStack:
def __init__(self):
self.array = []
def push(self, item):
self.array.append(item)
def pop(self):
return self.array.pop(self.count() - 1)
def peek(self):
return self.__current()
def __current(self):
return self.array[self.count() - 1]
def count(self):
return len(self.array)
def __iter__(self):
self.index = self.count() - 1
return self
def __next__(self):
if self.index < 0:
raise StopIteration()
result = self.array[self.index]
self.index -= 1
return result
def check(string: str, stack: MyStack) -> bool:
for i in string:
if i == '(' or i == '{' or i == '[':
stack.push(i)
elif i == ')' and stack.peek() == '(':
stack.pop()
elif i == ']' and stack.peek() == '[':
stack.pop()
elif i == '}' and stack.peek() == '{':
stack.pop()
return True if stack.count() == 0 else False
if __name__ == "__main__":
my_string = '{[()]}'
my_string1 = '((((((('
my_string2 = '{{{[]}}}'
my_stack = MyStack()
my_stack1 = MyStack()
my_stack2 = MyStack()
print(f'{my_string} = {check(my_string, my_stack)}')
print(f'{my_string1} = {check(my_string1, my_stack1)}')
print(f'{my_string2} = {check(my_string2, my_stack2)}')
| true |
7191a0743560cc83b9522c6fae2f5bdffb721bc0 | EvheniiTkachuk/Lessons | /Lesson5/task1.py | 460 | 4.125 | 4 | # #The greatest number
# Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
from random import randint as rand
s = []
i = 1
while i <= 10:
s.append(rand((10**9), (10**10) - 1))
print(f'{i}. {s[i-1]}')
i += 1
maxElem = max(s)
print(f'Max list item at position {s.index(maxElem) + 1} and has matters {max(s)}')
| true |
9a9f02d7d36150749820c11ad1815e1939c21fad | kookoowaa/Repository | /SNU/Python/코딩의 기술/zip 활용 (병렬).py | 774 | 4.34375 | 4 | ### 병렬에서 루프문 보다는 zip 활용
names = ['Cecilia', 'Lise', 'Marie']
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
# 루프문 활용
for i in range(len(names)):
count = letters[i]
if count > max_letters:
longest_name = names[i]
max_letters = count
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7
# 루프 enumerate 활용
for order, name in enumerate(names):
if len(name)>max_letters:
max_letters, longest_name = letters[order], name
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7
# zip 활용
for name, length in zip(names, letters):
if length > max_letters:
max_letters, longest_name = length, name
print(longest_name)
print(max_letters)
# >> Cecilia
# >> 7 | true |
fb57296132ee3c28d5940f746bbc1496e566c946 | nidhi988/THE-SPARK-FOUNDATION | /task3.py | 2,329 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Task 3: Predicting optimum number of clusters and representing it visually.
# ## Author: Nidhi Lohani
# We are using Kmeans clustering algorithm to get clusters. This is unsupervised algorithm. K defines the number of pre defined clusters that need to be created in the process. This is done by elbow method, which is based on concept of wcss (within cluster sum of squares).
# In[1]:
# Importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
#To display maximum columns of dataframe
pd.pandas.set_option('display.max_columns',None)
# ## Loading dataset
# In[3]:
data=pd.read_csv('C:\\Users\\LOHANI\\Desktop\\Iris2.csv')
print("Data imported")
# In[4]:
print(data.shape)
# In[5]:
data.head()
# ## Extracting Independent variables
# In[6]:
X=data.iloc[:,[0,1,2,3]].values
# ## finding optimum value of k
# In[10]:
from sklearn.cluster import KMeans
wcss=[]
for i in range(1,11):
Kmeans=KMeans(n_clusters=i,init='k-means++',max_iter=300,n_init=10,random_state=0)
Kmeans.fit(X)
wcss.append(Kmeans.inertia_)
#plotting the results into line graph
plt.plot(range(1,11),wcss)
plt.title("Elbow method")
plt.xlabel("No of clusters")
plt.ylabel("WCSS")
plt.show()
# ## Using dendogram to find optimal no of clusters.
# ## Hierarchical clustering
# In[12]:
import scipy.cluster.hierarchy as sch
dendrogram=sch.dendrogram(sch.linkage(X,method='ward'))
plt.title("Dendrogram")
plt.xlabel("Species")
plt.ylabel("Euclidean Distance")
plt.show()
# optimum clusters will be cluster after which wcss remains almost constant. From above two graphs, optimum no of clusters is 3.
# ## creating kmeans classifier
# In[13]:
kmeans=KMeans(n_clusters=3,init='k-means++',max_iter=300,n_init=10,random_state=0)
y_kmeans=kmeans.fit_predict(X)
# ## Visualizing the clusters
# In[15]:
plt.scatter(X[y_kmeans==0,0],X[y_kmeans==0,1],s=100,c='red',label='setosa')
plt.scatter(X[y_kmeans==1,0],X[y_kmeans==1,1],s=100,c='blue',label='versicolor')
plt.scatter(X[y_kmeans==2,0],X[y_kmeans==2,1],s=100,c='green',label='virginica')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=100,c='yellow',label='centroids')
plt.legend()
# In[ ]:
| true |
65d2ba3d984567002d83f04bbf0fa42ded16a5bb | dineshneela/class-98 | /file.py | 678 | 4.125 | 4 | # program to read and open a file.
#>>> f= open("test.txt")
#>>> f.read()
#'test filllles'
#>>> f= open("test.txt")
#>>> filelines=f.readlines()
#>>> for line in filelines:
#... print(line)
#...
#test filllles. somettttthing else
# program to split the words in a string.
#>>> introstring="my name is Dinesh,I am 13 years old"
#>>> words=introstring.split()
#>>> print(words)
#['my', 'name', 'is', 'Dinesh,I', 'am', '13', 'years', 'old']
#>>> words=introstring.split(",")
#>>> print(words)
#['my name is Dinesh', 'I am 13 years old']
# how to write a function in python
#def Greet(name):
# print("Hello "+ name+"How are you")
#Greet("Dinesh")
| true |
1a7c48054418adef604c72fa24c62904e6a41525 | Oli-4ction/pythonprojects | /dectobinconv.py | 556 | 4.15625 | 4 | """*************************
Decimal to binary converter
*************************"""
#function
def function():
#intialize variables
number = 0
intermediateResult = 0
remainder = []
number = int(input("Enter your decimal number: "))
base = int(input("Choose the number format: "))
#loops
while number != 0:
remainder.append(number % base)
number = number // base
remainder.reverse()
for result in remainder:
print(result, end = "")
#output
function()
| true |
cd0e31fec220f4c3e9a04262de709ed86c91e37f | posguy99/comp644-fall2020 | /L3-12.py | 270 | 4.125 | 4 | # Create a while loop that will repetitively ask for a number.
# If the number entered is 9999 stop the loop.
while True:
answer = int(input('Enter a number, 9999 to end: '))
if answer == 9999:
break
else:
print('Your number was: ', answer)
| true |
266855d66e3b769f19350e5fa22af81c7b367811 | stfuanu/Python | /basic/facto.py | 268 | 4.125 | 4 |
num = input("Enter a number: ")
num = int(num)
x = 1
if num < 0:
print("Factorial doesn't exist for -ve numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1,num + 1):
x = x*i
print("Factorial of",num,"is",x) | true |
3ab084579276659c14fca1a6421903dc47227b27 | jrngpar/PracticePython | /15 reverse word order.py | 1,273 | 4.28125 | 4 | #reverse word order
#ask for a long string with multiple words
#print it back with the words in backwards order
#remove spaces? Maybe print back with words in reverse
#2 functions, one to reverse order of words, one to reverse letters in words?
#Can call both functions to reverse order and letters if wanted
def reverse_words(sentence_in):
swapped = sentence_in.split(" ")
swapped = " ".join(reversed(swapped))
return swapped
def get_sentence():
user_sentence = input("What would you like reversed:\n")
return user_sentence
#print(reverse_words(get_sentence()))
def reverse_sentence(s):
backwards = s[::-1]
return backwards
#print(reverse_sentence(get_sentence()))
def other_reverse(s):
backwards = "".join(reversed(s))
return backwards
def sentence_editor():
user_sentence = input("Would you like to edit a sentence or quit(type 'quit')?")
while user_sentence != "quit":
my_sentence = input("Enter your sentence:")
which_mod = input("Reverse words(1)\nReverse letters in words(2)\nReverse entire sentence(3)\n")
if which_mod == "1":
print(reverse_words(my_sentence))
break
elif which_mod =="2":
print(reverse_words(other_reverse(my_sentence)))
break
else:
print(reverse_sentence(my_sentence))
break
sentence_editor()
| true |
1341c50fd7e58931c55c79478479d0b29deb0787 | MrazTevin/100-days-of-Python-Challenges | /SolveQuiz1.py | 695 | 4.15625 | 4 | # function to determine leap year in the gregorian calendar
# if a year is leap year, return Boolean true, otherwise return false
# if the year can be evenly divided by 4, it's a leap year, unless: The year can be evenly divided by 100 it is# not a leap year,unless the year is also divisible by 400, then its a leap year
# In the Gregorian Calendar, years 2000 and 2400 are leap years, while 1800,1900,2100,2200,2300 and 2500 are not leap years
def leap_year(year):
if (year%4==0 and year%100!=0):
return True
elif (year%100==0 and year%400==0):
return True
else:
return False
yearInput = int(input("Enter any year i.e 2001 :"))
print(leap_year(yearInput))
| true |
82573c7abbdd044e489e75c4b53f7840c10873ae | rdstroede-matc/pythonprogrammingscripts | /week5-files.py | 978 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Name: Ryan Stroede
Email: rdstroede@madisoncollege.edu
Description: Week 5 Files Assignment
"""
#1
with open("/etc/passwd", "r") as hFile:
strFile = hFile.read()
print(strFile)
print("Type:",type(strFile))
print("Length:",len(strFile))
print("The len() function counts the number of characters in a file.")
print("You would use this technique if you want to print certain characters in a file.")
#2
with open("/etc/passwd", "r") as hFile:
fileList = hFile.readlines()
print(fileList)
print("Type:",type(fileList))
print("Length:",len(fileList))
print("The len() function counts each object in the list.")
print("You can use this to get a number of how many objects are in the list.")
#3
with open("/etc/passwd", "r") as hFile:
fileLine = hFile.readline()
print(fileLine)
print("Type:",type(fileLine))
print("Length:",len(fileLine))
print("You would use this technique when you want to count one line at a time.")
| true |
1bdfad55963a5ca778fc06d402edc95abcf8fb16 | stak21/DailyCoding | /codewarsCodeChallenge/5-anagram.py | 1,300 | 4.28125 | 4 | # Anagram
# Requirements:
# Write a function that returns a list of all the possible anagrams
# given a word and a list of words to create the anagram with
# Input:
# 'abba', ['baab', 'abcd', 'baba', 'asaa'] => ['baab, 'baba']
# Process:
# Thoughts - I would need to create every permutation of the given word and check the list for each one
# example: 'a' in ['a', 'ab', 'c'] -> true, but would 'a' in 'ab' be true too? The answer is no
# Naive approach: a possible naive approach is to sort each word and put each one in a dictionary with a list of the matching letters.
# Approach 1: change each character in different arrangements and check if that character is in the list
# Naive approach
def is_anagram(word, words):
matchings = {}
for w in words:
sorted_word = ''.join(sorted(w))
if sorted_word in matchings:
matchings[sorted_word].append(w)
else:
matchings[sorted_word] = [w]
sorted_word = ''.join(sorted(word))
return matchings.get(sorted_word, [])
tests = [('a', ['a', 'b', 'ab']), ('aba', ['aab', 'baa', 'abb']), ('ab', ['a'])]
answers = [['a'], ['aab', 'baa'], []]
for test, answer in zip(tests, answers):
res = is_anagram(test[0], test[1])
print(res, 'Success: ', res == answer) | true |
aaad26766dbaf3819cebe370c7f5117283fd1630 | HarithaPS21/Luminar_Python | /python_fundamentals/flow_of_controls/iterating_statements/while_loop.py | 339 | 4.15625 | 4 | # loop - to run a block of statements repeatedly
# while loop -run a set of statements repeatedly until the condition becomes false
#Syntax
# while condition:
# code
# inc/dec operator
a=0
while a<=10:
print("hello") # prints "hello" 11 times
a+=1
print("\nwhile decrement example")
i=10
while i>0:
print(i)
i-=1 | true |
85b7319bc24340a96ce0e3a97791d6eee2643c32 | Syconia/Harrow-CS13 | /Stacks.py | 1,611 | 4.125 | 4 |
# Stack class
class Stack():
# Put in a list and set a limit. If limit is less than 0, it's basically infinitely large
def __init__(self, List, INTlimit):
self.Values = List
if INTlimit < 0:
INTlimit = 99999
self.Limit = INTlimit
# Set up pointer. It's set by list index so start from 0. If empty, it's false
if self.Values == []:
self.Pointer = False
else:
self.Pointer = len(List)-1
# If pointer exists, then check if it's over the limit
if self.Pointer != False:
if self.Limit < self.Pointer + 1:
raise IndexError
# Add item to top of stack
def push(self, item):
# Check to see if it's over the limit
if self.Pointer + 2 > self.Limit:
raise IndexError
# Check to see if it's at top of list
try:
# If not, then change next value to item
self.Values[self.Pointer + 1] = item
except IndexError:
# else, add new value
self.Values.append(item)
# Pointer update
if self.Pointer == False:
self.Pointer = 0
else:
self.Pointer += 1
# Return top item, do not delete
def pop(self):
returnValue = self.Values[self.Pointer]
# Update pointer
self.Pointer -= 1
return returnValue
# Empty the stack, reset the pointer
def emptyStack(self):
self.Values = []
self.Pointer = False
# For convenient printing
def __str__(self):
return str(self.Values)
| true |
c353be9014cb341a5a04e1f55ef53661f88175ef | JoshTheBlack/Project-Euler-Solutions | /075.py | 1,584 | 4.125 | 4 | # coding=utf-8
'''It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed?'''
from comm import timed
DEBUG = False
@timed
def p075(max):
def driver():
from typing import DefaultDict
from math import gcd
limit = int((max/2)**0.5)
triangles = DefaultDict(int)
result = 0
for m in range(2,limit):
for n in range(1,m):
if ((n+m) % 2) == 1 and gcd(n, m) == 1:
a = m**2 + n**2
b = m**2 - n**2
c = 2*m*n
p = a + b + c
while p < max:
triangles[p] += 1
if triangles[p] == 1: result += 1
if triangles[p] == 2: result -= 1
p += a+b+c
return result
return driver()
if __name__ == "__main__":
print(p075(1_500_000)) | true |
c8509d347b9d8dce353f1e40f9ba2a1c4d3df4f2 | RaviC19/Dictionaries_Python | /more_methods.py | 625 | 4.375 | 4 | # pop - removes the key-value pair from the dictionary that matches the key you enter
d = dict(a=1, b=2, c=3)
d.pop("a")
print(d) # {'b': 2, 'c': 3}
# popitem - removes and returns the last element (key, value) pair in a dictionary
e = dict(a=1, b=2, c=3, d=4, e=5)
e.popitem()
print(e) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# update - updates keys and values in a dictionary with another set of key value pairs
user = {
"name": "Ravi",
"location": "UK",
"age": 30
}
person = {"language": "Python"}
person.update(user)
print(person)
# returns {'language': 'Python', 'name': 'Ravi', 'location': 'UK', 'age': 30}
| true |
44291c2c7fe818202a9d424139eba73e90dfd5ce | Jwbeiisk/daily-coding-problem | /mar-2021/Mar15.py | 1,643 | 4.4375 | 4 | #!/usr/bin/env python3
"""
15th Mar 2021. #558: Medium
This problem was asked by Google.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.
Hint: The basic equation of a circle is x^2 + y^2 = r^2.
"""
"""
Solution: We sample random points that would appear in the first quadrant of the coordinate axes. The points lie
between 0 and 1 and may lie inside a circle of radius 1 with its origin at (0, 0) if it satisfies the condition x^2 +
y^2 <= 1^2 (or r^2). If we have sampled enough of the quarter of the circle uniformly, the ratio of points inside the
circle and total samples is pi/4. We multiply this by 4 to get an approximate pi.
https://en.wikipedia.org/wiki/Monte_Carlo_method
"""
from random import random, seed
SAMPLES = 999
def monte_carlo_pi():
prev = 0
pi = 3
total_valid_points = 0
total_points = 0
# The approximation of pi stays the same for over a couple estimations
while abs(prev - pi) > 1e-6:
# Get SAMPLES number of random points with x, y in range(0, 1)
for _ in range(SAMPLES):
# Check if random point lies inside a circle of radius 1 with its centre at origin
if random() ** 2 + random() ** 2 <= 1:
total_valid_points += 1
total_points += 1
prev = pi
# New estimation is 4 * (pi/4)
pi = float(4 * total_valid_points) / float(total_points)
# Return result to 3 decimal places
return '{0:.3f}'.format(pi)
def main():
print(monte_carlo_pi()) # Prints 3.142
return
if __name__ == "__main__":
main() | true |
f2c376ba14e0c328cc64f9985d080d4968a57431 | Jwbeiisk/daily-coding-problem | /mar-2021/Mar10.py | 1,667 | 4.5 | 4 | #!/usr/bin/env python3
"""
10th Mar 2021. #553: Medium
This problem was asked by Google.
You are given an N by M 2D matrix of lowercase letters. Determine the minimum number of columns that can be removed to
ensure that each row is ordered from top to bottom lexicographically. That is, the letter at each column is
lexicographically later as you go down each row. It does not matter whether each row itself is ordered
lexicographically.
For example, given the following table:
cba
daf
ghi
This is not ordered because of the a in the center. We can remove the second column to make it ordered:
ca
df
gi
So your function should return 1, since we only needed to remove 1 column.
As another example, given the following table:
abcdef
Your function should return 0, since the rows are already ordered (there's only one row).
As another example, given the following table:
zyx
wvu
tsr
Your function should return 3, since we would need to remove all the columns to order it.
"""
"""
Solution: Self-explanatory.
"""
def col_del(arr):
count = 0
for i in range(len(arr[0])):
char = 'a'
for row in arr:
if ord(row[i]) < ord(char):
count += 1
break
char = row[i]
return count
def main():
arr1 = [
'cba',
'daf',
'ghi'
]
arr2 = ['abcdef']
arr3 = [
'zyx',
'wvu',
'tsr'
]
print(col_del(arr1)) # Prints 1
print(col_del(arr2)) # Prints 0
print(col_del(arr3)) # Prints 3
return
if __name__ == "__main__":
main() | true |
14b70002c95cdd503190e523f840b543a272f481 | Jwbeiisk/daily-coding-problem | /feb-2021/Feb17.py | 1,784 | 4.40625 | 4 | #!/usr/bin/env python3
"""
17th Feb 2021. #532: Medium
This problem was asked by Google.
On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops that
have another bishop located between them, i.e. bishops can attack through pieces.
You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the
number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered the
same as (2, 1).
For example, given M = 5 and the list of bishops:
(0, 0)
(1, 2)
(2, 2)
(4, 0)
The board would look like this:
[b 0 0 0 0]
[0 0 b 0 0]
[0 0 b 0 0]
[0 0 0 0 0]
[b 0 0 0 0]
You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4.
"""
"""
Solution: The diagonals on a chessboard would have coordinates along a line that has the characteristic of always
being the same number of steps down as it is across. For example, from (2, 2) to (4, 0) we have to go 2 steps left and
2 steps down. Thus we simply calculate the number of coordinate pairs where the difference in x or y coordinate values
is the same (regardless of sign).
"""
def bishop_kills(bishops):
kills = 0
for i in range(len(bishops)):
# Look for every bishop after the selected one
for j in range(min(i + 1, len(bishops)), len(bishops)):
if abs(bishops[i][0] - bishops[j][0]) == abs(bishops[i][1] - bishops[j][1]):
kills += 1
return kills
def main():
bishops = [(0, 0),
(1, 2),
(2, 2),
(4, 0)]
print(bishop_kills(bishops)) # Prints 2
return
if __name__ == "__main__":
main() | true |
f98b5090fbc532098ebbcd8026efae383bfcc507 | Jwbeiisk/daily-coding-problem | /jan-2021/Jan30.py | 1,092 | 4.34375 | 4 | #!/usr/bin/env python3
"""
30th Jan 2021. #514: Medium
This problem was asked by Microsoft.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its
length: 4.
Your algorithm should run in O(n) complexity.
"""
"""
Solution: Nothing too fancy. We use hashing to convert a solution that would usually run in O(nlogn) time and O(1)
space to O(n) time and space. We use a set here, and search for consecutive elements, which is faster than first
ordering a list and then looping through for sequences.
"""
def longest_sequence(arr):
count = 0
s = set(arr)
for i in range(len(arr)):
if arr[i] - 1 not in s:
j = arr[i]
while j in s:
j += 1
count = max(count, j - arr[i])
return count
def main():
arr = [100, 4, 200, 1, 3, 2]
print(longest_sequence(arr)) # Returns 4 (for [1, 2, 3, 4])
return
if __name__ == "__main__":
main()
| true |
e08c9f11aab1e0131d5f37feeb01f6475ae6ec23 | Jwbeiisk/daily-coding-problem | /feb-2021/Feb22.py | 1,107 | 4.3125 | 4 | #!/usr/bin/env python3
"""
22th Feb 2021. #537: Easy
This problem was asked by Apple.
A Collatz sequence in mathematics can be defined as follows. Starting with any positive integer:
if n is even, the next number in the sequence is n / 2
if n is odd, the next number in the sequence is 3n + 1
It is conjectured that every such sequence eventually reaches the number 1. Test this conjecture.
Bonus: What input n <= 1000000 gives the longest sequence?
"""
"""
Solution: Spoiler alert: the conjecture is true.
To my understanding, the bonus question is quite hard and I can not imagine it to be anything more than a discussion
if even asked at an interview. Here is a link though:
https://lucidmanager.org/data-science/project-euler-14/
"""
def is_collatz(n):
if n == 1:
return True
if n % 2 == 0:
return is_collatz(int(n / 2))
else:
return is_collatz(3 * n + 1)
return False
def main():
print(is_collatz(49)) # Prints True
print(is_collatz(82)) # Prints True
return
if __name__ == "__main__":
main() | true |
e72f31942b3077b838ec289bffcf5a22526eea40 | priyakrisv/priya-m | /set17.py | 400 | 4.1875 | 4 | print("Enter 'x' for exit.");
string1=input("enter first string to swap:");
if(string1=='x'):
exit()
string2=input("enter second string to swap:");
print("\nBoth string before swap:");
print("first string=",string1);
print("second string=",string2);
temp=string1;
string1=string2;
string2=temp;
print("\nBoth string after swap:");
print("first string=",string1);
print("second string=",string2);
| true |
39959d08343f4ca027e3150e4a29186675a8ab2d | ramshaarshad/Algorithms | /number_swap.py | 305 | 4.21875 | 4 | '''
Swap the value of two int variables without using a third variable
'''
def number_swap(x,y):
print x,y
x = x+y
y = x-y
x = x-y
print x,y
number_swap(5.1,6.3)
def number_swap_bit(x,y):
print x,y
x = x^y
y = x^y
x = x^y
print x,y
print '\n'
number_swap_bit(5,6)
| true |
50ea487c9c3dd452fc4ed94cd86b223554b7afc2 | rajivpaulsingh/python-codingbat | /List-2.py | 2,799 | 4.5 | 4 |
# count_evens
"""
Return the number of even ints in the given array.
Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0
"""
def count_evens(nums):
count = 0
for element in nums:
if element % 2 == 0:
count += 1
return count
# big_diff
"""
Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array.
Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values.
big_diff([10, 3, 5, 6]) → 7
big_diff([7, 2, 10, 9]) → 8
big_diff([2, 10, 7, 2]) → 8
"""
def big_diff(nums):
return max(nums) - min(nums)
# centered_average
"""
Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
except ignoring the largest and smallest values in the array.
If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.
Use int division to produce the final average. You may assume that the array is length 3 or more.
centered_average([1, 2, 3, 4, 100]) → 3
centered_average([1, 1, 5, 5, 10, 8, 7]) → 5
centered_average([-10, -4, -2, -4, -2, 0]) → -3
"""
def centered_average(nums):
sum = 0
for element in nums:
sum += element
return (sum - min(nums) - max(nums)) / (len(nums)-2)
# sum13
"""
Return the sum of the numbers in the array, returning 0 for an empty array.
Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
sum13([1, 2, 2, 1]) → 6
sum13([1, 1]) → 2
sum13([1, 2, 2, 1, 13]) → 6
"""
def sum13(nums):
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
if i+1 < len(nums):
nums[i+1] = 0
return sum(nums)
# sum67
"""
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6
and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers.
sum67([1, 2, 2]) → 5
sum67([1, 2, 2, 6, 99, 99, 7]) → 5
sum67([1, 1, 6, 7, 2]) → 4
"""
def sum67(nums):
for i in range(0, len(nums)):
if nums[i] == 6:
nums[i] = 0
for j in range(i+1, len(nums)):
temp = nums[j]
nums[j] = 0
if temp == 7:
i = j + 1
break
return sum(nums)
# has22
"""
Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
has22([1, 2, 2]) → True
has22([1, 2, 1, 2]) → False
has22([2, 1, 2]) → False
"""
def has22(nums):
for i in range(0, len(nums)-1):
#if nums[i] == 2 and nums[i+1] == 2:
if nums[i:i+2] == [2,2]:
return True
return False | true |
4404e39852e74e7ca1ad170550b02fd3b09f76dd | wilsonbow/CP1404 | /Prac03/gopher_population_simulator.py | 1,190 | 4.5 | 4 | """
This program will simulate the population of gophers over a ten year period.
"""
import random
BIRTH_RATE_MIN = 10 # 10%
BIRTH_RATE_MAX = 20 # 20%
DEATH_RATE_MIN = 5 # 5%
DEATH_RATE_MAX = 25 # 25%
YEARS = 10
print("Welcome to the Gopher Population Simulator!")
# Calculate births and deaths
def gopher_births(population):
"""Calculates yearly gopher births."""
birth_rate = random.randint(BIRTH_RATE_MIN, BIRTH_RATE_MAX) # Birth rate between min and max
return int(population * birth_rate / 100) # Calculate and return births
def gopher_deaths(population):
"""Calculate yearly gopher deaths"""
death_rate = random.randint(DEATH_RATE_MIN, DEATH_RATE_MAX) # Death rate between min and max
return int(population * death_rate / 100) # Calculate and return deaths
population = 1000
print("Initial population is 1000")
# Simulate for YEARS years
for year in range(1, YEARS + 1):
births = gopher_births(population)
deaths = gopher_deaths(population)
population = int(population + births - deaths)
print("In year {:>2}, there were {:>3} births and {:>3} deaths. \
The new population is: {:>4}.\n".format(year, births, deaths, population)) | true |
c1c268aa78f389abc625b582e37ba9316f36a849 | AlfredPianist/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 2,885 | 4.3125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""100-singly_linked_list
A Node class storing integers, and a Singly Linked List class implementing a
sorted insertion.
"""
class Node:
"""A Node class. Stores a number and a type Node.
Attributes:
__data (int): The size of the square.
__next_node (:obj:`Node`): A 'pointer' to the next node.
"""
def __init__(self, data, next_node=None):
"""Initialization of Node object with data and next node.
"""
self.data = data
self.next_node = next_node
@property
def data(self):
"""The data stored.
For the setter:
Args:
value (int): The data of the Node.
Raises:
TypeError: Data entered must be an integer.
"""
return self.__data
@data.setter
def data(self, value):
if not isinstance(value, int):
raise TypeError("data must be an integer")
self.__data = value
@property
def next_node(self):
"""The 'pointer' to the next node.
For the setter:
Args:
value (:obj:`Node`): A Node.
Raises:
TypeError: Next node has to be Node or None.
"""
return self.__next_node
@next_node.setter
def next_node(self, value):
if not (value is None or isinstance(value, Node)):
raise TypeError("next_node must be a Node object")
self.__next_node = value
class SinglyLinkedList:
"""A Singly Linked List Class. It sorts the inserted items and
preps the list to be printed by print()
Attributes:
__head (:obj:`Node`): The head of the list.
"""
def __init__(self):
"""Initialization of List object with a None head.
"""
self.__head = None
def __str__(self):
"""Formats the string to be printed by print()
Returns:
The formatted string.
"""
current = self.__head
string = ""
while (current is not None):
string += str(current.data)
if (current.next_node is not None):
string += "\n"
current = current.next_node
return string
def sorted_insert(self, value):
"""Inserts a node with its value in the correct order.
Args:
value (int): The value of the Node to be inserted.
"""
node = Node(value)
current = self.__head
if current is None:
self.__head = node
return
if value < current.data:
node.next_node = self.__head
self.__head = node
return
while (current.next_node is not None and
value >= current.next_node.data):
current = current.next_node
node.next_node = current.next_node
current.next_node = node
| true |
e62c99e0a88f67778b9573559d2de096255a3e2d | AlfredPianist/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-append_write.py | 479 | 4.28125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""2-append_write
This module has the function write_file which writes a text to a file.
"""
def append_write(filename="", text=""):
"""Writes some text to a file.
Args:
filename (str): The file name to be opened and read.
text (str): The text to be written.
Returns:
int: The number of characters written.
"""
with open(filename, 'a', encoding='utf-8') as f:
return f.write(text)
| true |
c51da4549dc5effcf1187071aaa8a55fbdd2be74 | Herrj3026/CTI110 | /P3HW2_DistanceTraveled_HerrJordan.py | 888 | 4.34375 | 4 | #
# A program to do a basic calcuation of how far you travled
# 6/22/2021
# CTI-110 P3HW2 - DistanceTraveled
# Jordan Herr
#
#section for the inputs
car_speed = float(input("Please enter car speed: "))
time_travled = float(input("Please enter distance travled: "))
#math section for the calculations
dis_travled = car_speed * time_travled
if time_travled > 0:
print()#white space to make it neat
print("Speed entered:", car_speed)
print("Time entered:", time_travled)
print()#white space to make it neat
print("Distance Travled", dis_travled)
elif time_travled <= 0:
time_travled = 1
print("Error!!! Time must be greater than 0!!!")
print()#white space to make it neat
print("Speed entered:", car_speed)
print("Time:", time_travled)
print()#white space to make it neat
print("Distance Travled", dis_travled)
| true |
3cec4c83350a40b81dc8e58910b57ce3e5c5428d | SBrman/Project-Eular | /4.py | 792 | 4.1875 | 4 | #! python3
"""
Largest palindrome product
Problem 4
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def isPalindrome(num):
num = str(num)
for i in range(len(num)):
if num[i] != num[-(i+1)]:
return False
return True
largestNumber = 0
for num1 in range(999, 100, -1):
for num2 in range(999, 100, -1):
number = num1 * num2
if isPalindrome(number):
if number > largestNumber:
largestNumber = number
number_1, number_2 = num1, num2
print(largestNumber, ' = ', number_1, ' * ', number_2)
| true |
9af7f0f7a29798891798048deea3137e95eca3f4 | Jimmyopot/JimmyLeetcodeDev | /Easy/reverse_int.py | 2,193 | 4.15625 | 4 | '''
- Given a signed 32-bit integer x, return x with its digits reversed.
If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
'''
# soln 1
class Solution(object):
def reverse(self, x):
# number = 123
def divide(number, divider):
return int(number * 1.0 / divider)
def mod(number, m):
if number < 0:
return number % -m
else:
return number % m
'''
remember:
123 % 10 = 3
-123 % 10 = 7
-123 % -10 = 3
'''
MAX_INT = 2 ** 31 - 1
MIN_INT = -2 ** 31
result = 0
while x:
pop = mod(x, 10)
x = divide(x, 10)
if result > divide(MAX_INT, 10) or (result == divide(MAX_INT, 10) and pop > 7):
return 0
if result < divide(MIN_INT, 10) or (result == divide(MIN_INT, 10) and pop < -8):
return 0
result = result * 10 + pop
return result
# TIME COMPLEXITY = O(n)
# SPACE COMPLEXITY = 0(1)
# soln2 (STRING REVERSE METHOD)****************BEST SOLN********************
def reverse_integer(x):
y = str(abs(x)) # converts int x to a string
y = y.strip() # strip all leading 0's (e.g, 120-> 21, 1000-> 1)
y = y[::-1] # reverses the string
output = int(y) # reverses back to INTEGER
if output >= 2 ** 31 -1 or output <= -2 ** 31:
return 0
elif x < 0:
return -1 * output
else:
return output
print(reverse_integer(-12345))
# TIME COMPLEXITY = O(n)
# soln3
def reverse_signed(num):
sum = 0
sign = 1
if num < 0:
sign = -1
num = num * -1
while num > 0:
rem = num % 10
sum = sum * 10 + rem
num = num // 10
if not -2147483648 < sum < 2147483648:
return 0
return sign * sum
print(reverse_signed(456)) | true |
399cb2a542e995969b17089d75fb73b1018dc706 | dspec12/real_python | /part1/chp05/invest.py | 923 | 4.375 | 4 | #!/usr/bin/env python3
'''
Write a script invest.py that will track the growing amount of an investment over time. This script includes an invest()
function that takes three inputs: the initial investment amount, the annual compounding rate, and the total number of years
to invest. So, the first line of the function will look like this:
def invest(amount, rate, time):
The function then prints out the amount of the investment for every year of the time period.
In the main body of the script (after defining the function), use the following code to test your function:
invest(100, .05, 8)
invest(2000, .025, 5)
'''
def invest(amount, rate, time):
print("principal amount: ${}".format(amount))
print("annual rate of return:", rate)
for t in range(1, time + 1):
amount = amount * (1 + rate)
print("year {}: ${}".format(t, amount))
print()
invest(100, .05, 8)
invest(2000, .025, 5)
| true |
665ba4de4b55bc221d03af876d0c17a9d3b6e602 | dspec12/real_python | /part1/chp05/5-2.py | 928 | 4.46875 | 4 | #!/usr/bin/env python3
#Write a for loop that prints out the integers 2 through 10, each on a new line, by using the range() function
for n in range(2, 11):
print("n = ", n)
print("Loop Finished")
"""
Use a while loop that prints out the integers 2 through 10 (Hint: you'll need to create a new integer first; there
isn't a good reason to use a while loop instead of a for loop in this case, but it's good practice...)
"""
n = 2
while n < 11:
print("n = ", n)
n = n + 1
print("Loop Finished")
'''
Write a function doubles() that takes one number as its input and doubles that number three times using a loop,
displaying each result on a separate line; test your function by calling doubles(2) to display 4, 8, and 16
'''
def doubles(num):
'''Takes input and doubles that number three times'''
num = num * 2
return(num)
number = 2
for n in range(0, 3):
number = doubles(number)
print(number)
| true |
1e6aba46347bc53f8abe7a864d239759a1fd6f91 | Coryf65/Python-Basics | /PythonBasics.py | 807 | 4.1875 | 4 | #Python uses Snake Case for naming conventions
first_name = "Ada"
last_name = "Lovelace"
print("Hello," + first_name + " ")
print(first_name + " " + last_name + " is an awesome person!")
# print() automatically adds spaces
print("These", "will be joined", "together by spaces!")
# Python will save vars like JS kinda
is_int = 12
print(is_int)
# getting user input and saving as a var
current_mood = input("How are you today ? ")
# displaying the mood !
print("I am glad that you are ,", current_mood)
# PEMDAS...
print("PEMDAS: ", 0.1 + 0.1 + 0.1 - 0.3)
# we get 0.0000005
# now we can round this
print("rounding: ",round(0.1 + 0.1 + 0.1 - 0.3))
# this Method helps give info about the passed in function or Argument!
#help(str)
# finding strings in strings
print("corn" in "Buttered Popcorn") | true |
6338ec300caac0b9eeb18103ec9d35d12bb5d61b | mohsin-siddiqui/python_practice | /lpth_exercise/MyRandomPrograms/areaOfCircle.py | 238 | 4.21875 | 4 | pi = 22/7
R = input("Please Enter the Radius of the Circle(in meter):\n") # R stands for Radius of the circle
A = pi * float(R) ** 2 # A stands for Area of the circle
print("The required Area of the circle is :",round(A),"square-meters")
| true |
41c9edbb34832ccd2fc656a366bd89103b171e67 | arl9kin/Python_data | /Tasks/file_function_questions.py | 2,256 | 4.25 | 4 | '''
Question 1
Create a function that will calculate the sum of two numbers. Call it sum_two.
'''
# def sum_two(a, b):
# c = a + b
# print (c)
# sum_two (3,4)
'''
Question 2
Write a function that performs multiplication of two arguments. By default the
function should multiply the first argument by 2. Call it multiply.
'''
# def multiply (a,b=2):
# c = a * b
# print (c)
# multiply (2)
# multiply (2,3)
'''
Question 3
Write a function to calculate a to the power of b. If b is not given
its default value should be 2. Call it power.
'''
# def power (a, b=2):
# c = a**b
# print (c)
# power(2)
# power(2,3)
'''
Question 4
Create a new file called capitals.txt , store the names of five capital cities
in the file on the same line.
'''
# file = open('capitals.txt', 'w')
# file.write('London, Moscow, Berlin, Rome, Tokyo')
# file.close()
# file = open('capitals.txt', 'r')
# print(file.readlines())
# file.close()
'''
Question 5
Write some code that requests the user to input another capital city.
Add that city to the list of cities in capitals. Then print the file to
the screen.
'''
# with open ('capitals.txt','r') as f:
# for i in f.readlines():
# print (i ,end = ' ')
# user = str.lower (input ('Do you want to add new capital (y/n): \n\t>>'))
# while user == "yes" or user == "y":
# user = str.lower (input ('enter new capital: \n\t>>'))
# with open ("capitals.txt", 'a') as f:
# f.write(f', {user.title()}')
# with open ('capitals.txt','r') as f:
# for i in f.readlines():
# print (i ,end = ' ')
# user = str.lower (input ('Do you want to add new capital (y/n): \n\t>>'))
# if user == 'n' or user == "no":
# print ("thanks for using my programm")
# else:
# print ("please use only y/n")
'''
Question 6
Write a function that will copy the contents of one file to a new file.
'''
# def clone (a='capitals.txt', b='capitals_copy.txt'):
# """Creates copy of original file (a)"""
# copy = []
# with open (a, 'r') as origin:
# for i in origin.readlines():
# copy.append(i)
# with open (b, 'w') as cop:
# for i in copy:
# cop.write (i)
# clone() | true |
348dc81dd001a621ab8fe2f5cf970a86981f6294 | letugade/Code-Club-UWCSEA | /Python/Lesson01/Lesson01.py | 508 | 4.21875 | 4 | # Printing
print("Hello world")
# Variables
a = 3
# Printing variables
print("The value of a is", a)
# User input
name = input("What is your name? ")
print("Hello", name)
# Conditional statements
if name == "Bob":
print("Your name is Bob")
elif name == "John":
print("Your name is John")
else:
print("Your name is not Bob or John")
print("This will always print")
# Lists
alphaList = ["a", "b", "c", "d"]
alphaList.append("e")
# Dictionaries
alphaDict = {"a":1, "b":2, "c":3}
print(alphaList[0])
| true |
d8fd66f43d8a296a435c9bc94d0c79a67249abc9 | rmwenzel/project_euler | /p1/p1.py | 286 | 4.15625 | 4 | #!usr/bin/python
import numpy as np
def sum_multiples(n):
"""Sum multiples of 3 or 5 that are < n."""
def f(x):
return x if (x % 3 == 0 or x % 5 == 0) else 0
return sum(np.array(list(map(f, np.arange(1, n)))))
if __name__ == "__main__":
sum_multiples(1000)
| true |
5bc2ead9259f699053de317c62b911bc86f75e3f | vivek-x-jha/Python-Concepts | /lessons/cs14_decorators_args.py | 713 | 4.3125 | 4 | """
Python Tutorial: Decorators With Arguments
https://youtu.be/KlBPCzcQNU8
"""
def prefix_decorator(prefix):
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(prefix, 'Executed Before', original_function.__name__)
result = original_function(*args, **kwargs)
print(prefix, 'Executed After', original_function.__name__, '\n')
return result
return wrapper_function
return decorator_function
@prefix_decorator('wtuppppp:')
def display_info(name, age):
print(f'display_info ran with arguments ({name}, {age})')
if __name__ == '__main__':
display_info('John', 25)
display_info('Travis', 30)
| true |
564cb1318d466a5eeb2fbe7a7825380de3227322 | prasannakumar2495/QA-Master | /pythonPractice/samplePractice/IFcondition.py | 786 | 4.3125 | 4 | '''
Created on 25-Dec-2018
@author: prasannakumar
'''
number = False
string = False
if number or string:
print('either of the above statements are true')
else:
print('neither of the above statements are true')
if number:
print('either of the above statements are true')
elif not(string) and number:
print('the data is not string but number')
elif not(number) and string:
print('the data is not number but string')
else:
print('neither of the above statements are true')
num1 = input('enter the 1st number')
num2 = input('enter the 2nd number')
num3 = input('enter the 3rd number')
def max_num():
if num1>num2 and num1>num3:
return num1
elif num2>num1 and num2>num3:
return num2
else:
return num3
print(max_num()) | true |
ea1f557a5eee486e0afd435d1eb339dd40caad0e | sis00337/BCIT-CST-Term-1-Programming-Methods | /02. Three Short Functions/create_name.py | 891 | 4.375 | 4 | """
Author: Min Soo Hwang
Github ID: Delivery_KiKi
"""
import random
import string
def create_name(length):
"""
Check if length of a name is less than or equal to 0.
:param length: an integer that indicates the length of a name
:return: the result of the function named create_random_name
"""
if length <= 0:
return None
else:
return create_random_name(length)
def create_random_name(length):
"""
Creating a randomized name.
:param length: an integer that indicates the length of a name
:return: Capitalized and randomized name
"""
name = (''.join(random.choices(string.ascii_lowercase, k=length)))
name_capitalized = name.capitalize()
return name_capitalized
def main():
# Program starts here
test = create_name(12)
print(test)
if __name__ == '__main__':
# invoke the main function
main()
| true |
9e80ca85c78c6ccba160eb3ce0a7e60ab1e49392 | DavidAlen123/Radius-of-a-circle | /Radius of a circle.py | 255 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 11 07:15:17 2021
@author: DAVID ALEN
"""
from math import pi
r = float(input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
| true |
100cf26661e730aa38efa2852aaa63e87067bac4 | 4anajnaz/Devops-python | /largestnumber.py | 460 | 4.375 | 4 | #Python program to find largest number
try:
num1= input("Enter first number")
num2= input("Enter second number");
num3= input("Enter third number");
if (num1>num2) and (num1>num3):
largest = num1
elif (num2>num1) and (num2>num3):
largest = num2
else:
largest = num3
print("The largest number is :", largest)
except Exception as e:
print ("Exception block called:")
print (e) | true |
126fac3aba52940e7c6d68b6469b33a3687ec2fb | aaron-lee/mathmodule | /from math import constant.py | 257 | 4.15625 | 4 | from math import pi #importing only the pi constant from the module
def circumference(radius):
circum = 2*pi*radius #circumference formula
return circum
print("The circumference of circle with radius 20 is %f" % circumference(20))
| true |
1eba38a72a5777e42e51f82ad189db3764ca7689 | teamneem/pythonclass | /Projects/proj02.py | 2,144 | 4.65625 | 5 | #/****************************************************************************
# Section ?
# Computer Project #2
#****************************************************************************/
#Program to draw a pentagon
import turtle
import math
print 'This program will draw a congruent pentagon. The user may choose a red'
print 'green, blue ration to make the internal fill color of the pentagon.'
print 'The user will also input the length of the pentagon sides.'
red = float(raw_input('What is the red value (0-1): ')) #user imput for color
green = float(raw_input('What is the green value (0-1): '))
blue = float(raw_input('What is the blue value (0-1): '))
length = int(raw_input('What is the length of a pentagon side: '))
pred = float(1-red) #values for the pen color from inverse of fill color
pgreen = float(1-green)
pblue = float(1-blue)
x1 = length*-0.5
#calculates x coordinate of bottom left corner of pentagon
y1 = -length/10*math.sqrt(25+10*(math.sqrt(5)))
#calculates y coordinate of bottom left corner of pentagon
turtle.up()
turtle.goto(x1,y1) #move turtle from origin so final pentagon is centered
turtle.pencolor(pred, pgreen, pblue) #pencolor is inverse of fill color
turtle.pensize(5)
turtle.fillcolor(red, green, blue) #colors the inside of the pentagon
turtle.begin_fill()
turtle.down() #turtle only draws when pen is down
turtle.forward(length) #draw one side of pentagon
turtle.left(72) #change pen angle to draw next side of pentagon
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.left(72)
turtle.forward(length)
turtle.end_fill()
turtle.up() #turtle will not draw with pen up
turtle.right(18)
turtle.forward(20)
turtle.write('R:'+(str(red))+' ', move=True, align='left', font=('Arial', 8, 'normal'))
turtle.write('G:'+(str(green))+' ', move=True, align='left', font=('Arial', 8, 'normal'))
turtle.write('B:'+(str(blue))+' ', move=False, align='left', font=('Arial', 8, 'normal'))
turtle.hideturtle()
import time #keep turtle window open
time.sleep(30)
import os
os._exit(1)
| true |
99c3e82a14d1eb3a0fa1419a10d07812937784a0 | caiopetreanu/PythonMachineLearningForTradingCourseCodes | /_py/01-01_to_01-03/14_numpy_arrays_random_values.py | 1,172 | 4.125 | 4 | """ Generating random numbers. """
import numpy
import numpy as np
def run():
# generate an array full of random numbers, uniformly sampled from [0.0, 1.0)
print("pass in a size tuple", np.random.random((5, 4))) # pass in a size tuple
print("function arguments (not a tuple)", np.random.rand(5, 4)) # function arguments (not a tuple)
# sample numbers from a Gaussian (normal) distribution
print('"standard normal" (mean = 0, s.d. = 1)"', np.random.normal(size=(2, 3))) # "standard normal" (mean = 0, s.d. = 1)
print('change mean to 50 and s.d. to 10', np.random.normal(50, 10, size=(2, 3))) # change mean to 50 and s.d. to 10
# random integers
print("a single integer in [0, 10)", np.random.randint(10)) # a single integer in [0, 10)
print("same as above, specifying [low, high) explicit", np.random.randint(0, 10)) # same as above, specifying [low, high) explicit
print("5 random integers as a 1D array", np.random.randint(0, 10, size=5)) # 5 random integers as a 1D array
print("2x3 array of random integers", np.random.randint(0, 10, size=(2, 3))) # 2x3 array of random integers
if __name__ == "__main__":
run() | true |
7c8cb97e1b50b85c8a7d5ec746a2b6c58bfee416 | chav-aniket/cs1531 | /labs/20T1-cs1531-lab05/encapsulate.py | 695 | 4.5 | 4 | '''
Lab05 Exercise 7
'''
import datetime
class Student:
'''
Creates a student object with name, birth year
and class age method
'''
def __init__(self, firstName, lastName, birth_year):
self.name = firstName + " " + lastName
self.birth_year = birth_year
def age(self):
'''
Added this function to encapsulate the age
'''
now = datetime.datetime.now()
return now.year - self.birth_year
def print_age(self):
'''
Used to print out the age
'''
print(f"{self.name} is {self.age()} years old")
if __name__ == '__main__':
NEW = Student("Rob", "Everest", 1961)
NEW.print_age()
| true |
c961c1845e80e88496fefbb12ff75ab957c59e1a | mdadil98/Python_Assignment | /21.py | 323 | 4.53125 | 5 | # Python3 program to print all numbers
# between 1 to N in reverse order
# Recursive function to print
# from N to 1
def PrintReverseOrder(N):
for i in range(N, 0, -1):
print(i, end=" ")
# Driver code
if __name__ == '__main__':
N = 5;
PrintReverseOrder(N);
# This code is contributed by 29AjayKumar
| true |
bd7b188ddcb0026ce6c83a6ac7323b441ccc42a5 | brohum10/python_code | /daniel_liang/chapter06/6.12.py | 1,190 | 4.40625 | 4 | #Defining the function 'printChars'
def printChars(ch1, ch2, numberPerLine):
#y is a variable storing the count of
#elements printed on the screen
#as we have to print only a given number of characters per line
y=0
#Running a for loop
#'ord' function returns the ASCII value of the character
#Thus, Running the loop from the ASCII value of the starting character to
#the ASCII value of the last character
for x in range(ord(ch1),ord(ch2)+1):
#incrementing y by 1
y+=1
#checking if the limit of character to be printed
#per line is reached or not
if(y%numberPerLine==0):
#printing the character
#the 'chr' function converts the ASCII value back to character
print(chr(x))
else:
#else printing the character with a " " at the end
print(chr(x), end=" ")
def main():
#Calling the printChars function and passing the arguments
printChars("I", "Z",10)
#Calling the main function
main()
| true |
7bbecf05287d5a11f158524c18c01143f42d534c | MantaXXX/python | /6- while/6-1.py | 205 | 4.28125 | 4 | # For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order.
n = int(input())
i = 1
while i**2 <= n:
print(i**2, end=' ')
i += 1 | true |
4a902e6c95a8b980fbcf6ca3193bbc2af259988c | MantaXXX/python | /3- if else /3.A.py | 392 | 4.15625 | 4 | # Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif a == b or a == c or b == c:
print(2)
else:
print(0)
| true |
6c8b2745c7e34271a007e2ecaaf634938cd3b851 | johnmarcampbell/concord | /concord/member.py | 956 | 4.25 | 4 | class Member(object):
"""This object represents one member of congress"""
def __init__(self, last_name='', first_name='', middle_name='',
bioguide_id='', birth_year='', death_year='', appointments=[]):
"""Set some values"""
self.last_name = last_name
self.first_name = first_name
self.middle_name = middle_name
self.bioguide_id = bioguide_id
self.birth_year = birth_year
self.death_year = death_year
self.appointments = appointments
def __str__(self):
"""String representation of a Member object"""
# Set middle name to empty string if there isn't one
if self.middle_name:
m = ' {}'.format(self.middle_name)
else:
m = ''
mask = '{}, {}{} [{}] - ({}-{})'
return mask.format(self.last_name, self.first_name, m, self.bioguide_id,
self.birth_year, self.death_year)
| true |
62cd51f8869cda6893e815f3508fc07b61f7e91f | andelgado53/interviewProblems | /order_three_colors.py | 971 | 4.15625 | 4 | # Problem Statement:
# You are given n balls. Each of these balls are of one the three colors: Red, Green and Blue.
# They are arranged randomly in a line. Your task is to rearrange them such that all
# balls of the same color are together and their collective color groups are in this order:
# Red balls first, Green balls next and Blue balls last.
# This combination of colors is similar to the Dutch National Flag, hence the problem name.
# This is a popular sorting problem.
# Sample Input:
# balls = [G, B, G, G, R, B, R, G]
# Sample Output:
# [R, R, G, G, G, G, B, B]
# RGB
def order(arr):
r = 0
g = 0
b = len(arr) - 1
while g <= b:
if arr[g] == "G":
g += 1
elif arr[g] == "B":
arr[g], arr[b] = arr[b], arr[g]
b -= 1
else:
arr[r], arr[g] = arr[g], arr[r]
r += 1
g += 1
return arr
print(order(["G", "B", "G", "G", "R", "B", "R", "G"]))
| true |
e5376089499f5bce5631b85ee1581a57451f0cb2 | andelgado53/interviewProblems | /zig_zag_conversion.py | 2,140 | 4.15625 | 4 | import pprint
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
# (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string s, int numRows);
# Example 1:
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
# Example 2:
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
#
# P I N
# A L S I G
# Y A H R
# P I
def pad(letter, num_rows, offset):
column = [None] * num_rows
column[offset] = letter
return column
def get_columns(word, rows, offset):
off = offset
output = []
start_index = 0
column = []
r = 0
while start_index < len(word):
while r < rows and start_index < len(word):
column.append(word[start_index])
r += 1
start_index += 1
if len(column) > 0:
output.append(column)
column = []
r = 0
while off >= 1 and start_index < len(word):
output.append(pad(word[start_index], rows, off))
off -= 1
start_index += 1
off = offset
return output
def convert(word, row_nums):
if len(word) <= 1 or row_nums == 0:
return word
rows = get_columns(word, row_nums, row_nums - 2)
col = 0
row = 0
new_word = ''
while col < len(rows[0]):
while row < len(rows):
if col < len(rows[row]) and rows[row][col] is not None:
new_word = new_word + rows[row][col]
row += 1
col += 1
row = 0
return new_word
def test():
test_word = "PAYPALISHIRING"
assert convert(test_word, 5) == "PHASIYIRPLIGAN"
assert convert(test_word, 4) == "PINALSIGYAHRPI"
assert convert(test_word, 3) == "PAHNAPLSIIGYIR"
assert convert(test_word, 2) == "PYAIHRNAPLSIIG"
assert convert(test_word, 1) == "PAYPALISHIRING"
test()
| true |
a9ca7660d5daf407247efa3219bde5714591e492 | sanket-qp/IK | /4-Trees/invert_binary_tree.py | 1,141 | 4.3125 | 4 | """
You are given root node of a binary tree T. You need to modify that tree in place,
transform it into the mirror image of the initial tree T.
https://medium.com/@theodoreyoong/coding-short-inverting-a-binary-tree-in-python-f178e50e4dac
______8______
/ \
1 __16
/
10
\
15
should convert to
______8______
/ \
16__ 1
\
10
/
15
"""
import random
from bst import Tree as BST
def mirror_image(node):
if not node:
return
left = mirror_image(node.left)
right = mirror_image(node.right)
temp_left = left
node.left = right
node.right = temp_left
return node
def main():
tree = BST()
N = 6
_set = set([random.randint(1, N * N) for _ in range(N)])
for x in _set:
tree.insert(x, "")
tree.pretty_print()
mirror_image(tree.root)
print ""
print "after inverting"
print ""
tree.pretty_print()
if __name__ == '__main__':
main()
| true |
df7b73944b7b1d4676d64edafeb1c3cbc976d483 | sanket-qp/IK | /3-Recursion/power.py | 1,109 | 4.1875 | 4 | """
The problem statement is straight forward. Given a base 'a' and an exponent 'b'. Your task is to find a^b.
The value could be large enough. So, calculate a^b % 1000000007.
Approach:
keep dividing the exponent by two pow(2, 8) will be handled as follows
2x2x2x2 x 2x2x2x2
4x4 x 4x4
16 x 16
Time Complexity: O(b) where b is exponent
Space complexity: O(b) used by call stack
"""
count = 0
def power(a, b):
global count
count += 1
if b == 1:
return a
ans = power(a, b / 2) * pow(a, b / 2)
return ans * 1 if b % 2 == 0 else ans * a
def main():
global count
count = 1
a = 2
b = 4
assert pow(a, b) == power(a, b)
print count
a = 3
b = 8
count = 1
assert pow(a, b) == power(a, b)
print count
a = 2
b = 5
assert pow(a, b) == power(a, b)
a = 3
b = 9
assert pow(a, b) == power(a, b)
count = 1
a = 2
b = 33
assert pow(a, b) == power(a, b)
print count
if __name__ == '__main__':
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.