blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
14b215cd4bbf1eba8ad00724c8612941cf234650 | efecntrk/python_programming | /unit-1/variables.py | 786 | 4.1875 | 4 | '''
#place a name and give a value
#integer
age = 27
#float
gpa = 3.0
#boolean
has_kids = True
#check the type of a variable
print(type(age)) #This function tell what type of data it is
print(type(gpa))
print(type(has_kids))
'''
#check if a number is even
'''
number = 10
if number % 2 == 0:
print('It is even!')
else:
print('It is odd!')
'''
'''
#comparison operators
# > - greater than
#< - less than
#>= greater than or equal to
#<= less than or equal to
#== - equal to
# != not equal to
#Truthiness
'''
x = 10 #a np zero value is truthy
y = 0 # zero or negative value is falsy
z = 'Python' # a string of non zero length is truth
p = '' # a string of zero length is falsy
q = [] #an empty list is falsy
if q:
print('yes')
else:
print('no')
| true |
b3f654665c353ca0192af767791d9ed7375bae64 | CharlesBird/Resources | /coding/Algorithm_exercise/Leetcode/0435-Non-overlapping-Intervals.py | 1,208 | 4.34375 | 4 | """
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# Time Complexity: O(n)
# Space Complexity: O(n)
if not intervals:
return 0
intervals.sort(key=lambda l: l[1])
res = 0
pre = intervals[0][1]
for v in intervals[1:]:
if v[0] < pre:
res += 1
else:
pre = v[1]
return res | true |
ae6b40a94660f9b36a4e1954bd176acc098b8ca3 | Airman-Discord/Python-calculator | /main.py | 530 | 4.25 | 4 | print("Python Calculator")
loop = True
while loop == True:
first_num = float(input("Enter your first number: "))
operation = input("Enter your operation: ")
second_num = float(input("Enter your second number: "))
if operation == "+":
print(first_num + second_num)
elif operation == "-":
print(first_num - second_num)
elif operation == "*":
print(first_num * second_num)
elif operation == "/":
print(first_num / second_num)
else:
print("invalid")
| true |
96fb4e1c83c2c41d3e23f26da20a5c36af2383ea | alexmcmillan86/python-projects | /sum_target.py | 729 | 4.125 | 4 | # finding a pair of numbers in a list that sum to a target
# test data
target = 10
numbers = [ 3, 4, 1, 2, 9 ]
# test solution -> 1, 9 can be summed to make 10
# additional test data
numbers1 = [ -11, -20, 2, 4, 30 ]
numbers2 = [ 1, 2, 9, 8 ]
numbers3 = [ 1, 1, 1, 2, 3, 4, 5 ]
# function with O(n)
def sum_target(nums, target):
seen = {}
for num in nums:
remaining = target - num
if remaining in seen:
return num, remaining
else:
seen[num] = 1
return 'No pairs that sum to target'
print(sum_target(numbers, target))
print(sum_target(numbers1, target))
print(sum_target(numbers2, target))
print(sum_target(numbers3, target))
| true |
27b8e98acdd4c3e3a3eff0b4f131751a9a9c29db | jfbm74/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 440 | 4.28125 | 4 | #!/usr/bin/python3
"""
Module that returns the number of lines of a text file:
"""
def number_of_lines(filename=""):
"""
function that returns the number of lines of a text file
:param filename: File to read
:type filename: filename
:return: integer
:rtype: int
"""
counter = 0
with open("my_file_0.txt", "r", encoding='utf8') as f:
for line in f:
counter += 1
return counter
| true |
d5490fc4962001fdb36c4885e757827a11de0225 | jfbm74/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 679 | 4.4375 | 4 | #!/usr/bin/python3
"""
Module print_square
This module prints a square with the character #
Return: Nothing
"""
def print_square(size):
"""
Function print_square
This function prints a square with the character #
Args:
size: is the size length of the square
Returns: Nothing
"""
if not isinstance(size, (int, float)):
raise TypeError("size must be an integer")
elif isinstance(size, float) and size < 0:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
for i in range(size):
for j in range(size):
print("#", end="")
print("")
| true |
0022986af95ce6ad144c40436e54888205a2cdda | rraj29/Dictionaries | /game_challenge.py | 1,826 | 4.21875 | 4 | locations = {0: "You are sitting in front of a computer, learning python.",
1: "You are standing at the end of a road before a small brick building.",
2: "You are at the top of a hill.",
3: "You are inside a building, a well house for a small stream.",
4: "You are in a valley beside a stream.",
5: "You are in a forest."}
exits = {0: {"Q": 0},
1: {"W": 2,"E": 3,"N": 5,"S": 4,"Q": 0},
2: {"N": 5,"Q": 0},
3: {"W": 1,"Q": 0},
4: {"W": 1,"N": 2,"Q": 0},
5: {"W": 2,"S": 1,"Q": 0}}
vocabulary = {"QUIT": "Q",
"NORTH": "N",
"SOUTH": "S",
"WEST": "W",
"EAST": "E"}
loc = 1
while True:
available_exits = ", ".join(exits[loc].keys())
# available_exits = ""
# for direction in exits[loc].keys():
# available_exits += direction + ", "
print(locations[loc])
if loc==0:
break
direction = input("Available exits are " + available_exits).upper()
print()
#Parse the user input with vocabulary dictionary, if needed
if len(direction) > 1: #more than 1 letter, so check vocab
# for word in vocabulary: #does it contain a word that we know
# if word in direction:
# direction = vocabulary[word]
words = direction.split(" ")
for word in words: # this is more efficient as we are searching for the man word in user's input
if word in vocabulary: #rather than the whole dictionary,
direction = vocabulary[word] #coz if the dictionary was long, it would be very less efficient
break
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You can't go in that direction.")
| true |
0d2e5ff146429d2209e75b4531d833848ee66784 | sandrahelicka88/codingchallenges | /EveryDayChallenge/fizzbuzz.py | 855 | 4.3125 | 4 | import unittest
'''Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output Fizz instead of the number and for the multiples of five output Buzz. For numbers which are multiples of both three and five output FizzBuzz.'''
def fizzBuzz(n):
result = []
for i in range(1,n+1):
if i%3==0 and i%5==0:
result.append('FizzBuzz')
elif i%3==0:
result.append('Fizz')
elif i%5==0:
result.append('Buzz')
else:
result.append(str(i))
return result
class Test(unittest.TestCase):
def test_fizzBuzz(self):
output = fizzBuzz(15)
self.assertEqual(output, ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"])
if __name__ == '__main__':
unittest.main()
| true |
eb5f823180f5c69fafb99a9c0502f55045bf517b | RutujaMalpure/Python | /Assignment1/Demo10.py | 335 | 4.28125 | 4 | """
. Write a program which accept name from user and display length of its name.
Input : Marvellous Output : 10
"""
def DisplayLength(name):
ans=len(name)
return ans
def main():
name=input("Enter the name")
ret=DisplayLength(name)
print("the length of {} is {}".format(name,ret))
if __name__=="__main__":
main() | true |
cdbaac13c9d4a49dd7c6fb425b6372929aab870d | RutujaMalpure/Python | /Assignment3/Assignment3_3.2.py | 842 | 4.15625 | 4 | """
.Write a program which accept N numbers from user and store it into List. Return Maximum
number from that List.
Input : Number of elements : 7
Input Elements : 13 5 45 7 4 56 34
Output : 56
"""
def maxnum(arr):
#THIS IS ONE METHOD
#num=arr[0]
#for i in range(len(arr)):
#if(arr[i]>=num):
#num=arr[i]
#return num
#THIS IS THE SECOND METHOD I.E IN PYTHON
num=max(arr)
return num
def main():
arr=[]
print("Enter the number of elements")
size=int(input())
for i in range(size):
print("the element at position",i+1)
no=int(input())
arr.append(no)
print("the entered list is",arr)
ret=maxnum(arr)
print("The max element of list is",ret)
if __name__=="__main__":
main() | true |
8d320f16d9ab715efda548016fa5bc02e96e0588 | zkevinbai/LPTHW | /ex34.quiz.py | 2,904 | 4.46875 | 4 | # my first app
# this is a quiz program which tests a novice programmer's ability to understand
# how indexing works with ordinal (0, 1, 2) and cardinal (1, 2, 3) numbers
# list of animals/answers, and indexes/questions
animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
List = [0, 1, 2, 3, 4, 5, 'first', 'second', 'third', 'fourth', 'fifth', 'sixth']
# imports the random interger function
from random import randint
# do not know how this works, imports the text to integer function
import sys
import os
sys.path.append(os.path.abspath("/Users/kevinbai/Exercises/Tools"))
from text_to_int import text2int
# imports the numbers
import numbers
# identifies the global list count as the number of items in the list
# starts problem count at one
list_count = len(List)
problem_count = 1
# opening lines, stylized
print'''
\t Welcome to the Python Index Understanding Quiz (PIUQ)
\t Your list for today: animal
'''
# while loop that comprises the majority of the code to be used
# I could have used a for loop here but that would lower the scalability of the code
# while loop allows me to run this with any list
# this while loop runs up to the point where problem_count = list_count
while problem_count <= list_count:
# I have a local list_count_updated to keep track
# of my eliminated, already-asked questions
list_count_updated = len(List)
# my random index generator allows me to randomly select the remaining prompts
number = randint(0, list_count_updated - 1)
# my list_item variable allows me to use the prompts I randomly generate
list_item = List[number]
# prints the list being tested so that the user will always have it for reference
print "animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']"
# prints the problem count and the current prompt
print "Problem #%d: What is the animal at %r?" % (problem_count, list_item)
# asks user for their answers
user_input = raw_input("> ")
# if the prompt is a number (which half of them are)
if isinstance(list_item, numbers.Number) == True:
# the correct animal can simply be accessed from the list
correct_animal = animal[list_item]
# if the prompt is a string(word)
else:
# the prompt is coverted into a number
list_int = text2int(list_item)
# the number is then used to access the correct animal
correct_animal = animal[list_int - 1]
# if the user is correct, print correct
if user_input == correct_animal:
print "correct\n"
# if the user is incorrect, print so and produce the correct answer
else:
print "incorrect, the answer is %s\n" % correct_animal
# removes an element from the prompt list after it is asked to prevent
# duplicate problems
List.remove(list_item)
# augements the problem count by 1
problem_count += 1
| true |
c925b58fd1c717cd76feb44899fe65d3ac87722c | zkevinbai/LPTHW | /ex20.py | 965 | 4.3125 | 4 | # imports argument variables from terminal
from sys import argv
# unpacks argv
script, input_file = argv
# defines print_all() as a function that reads a file
def print_all(f):
print f.read()
# defines rewind() as a function that finds
def rewind(f):
f.seek(0)
# defines print_a_line as a function that prints one line
def print_a_line(line_count, f):
print line_count, f.readline(),
# identifies current_file as a variable which opens the input_file
current_file = open(input_file)
print "First let's print the whole file:"
# runs print_all on current_file
print_all(current_file)
print "Now let's rewind, kind of like a tape.\n"
# runs rewind on current_file
rewind(current_file)
print "Let's print 3 lines:"
# runs print a line 3 times for the 3 lines in the file
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
| true |
1a78c13413ea3afdfc85f9d38600c34572b2dad8 | ivanchen52/leraning | /ST101/mode.py | 433 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 11:36:09 2017
@author: ivanchen
"""
#Complete the mode function to make it return the mode of a list of numbers
data1=[1,2,5,10,-20,5,5]
def mode(data):
modecnt = 0
for i in range(len(data)):
icount = data.count(data[i])
if icount > modecnt:
mode = data[i]
modecnt = icount
return mode
print(mode(data1)) | true |
a502a5919e592bfaf5580f83ff294cb866ca1742 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 10/Exercise10-3.py | 293 | 4.125 | 4 | def middle(t):
"""It takes a list and return a new list with all but
the first and last elements."""
t1 = t[:]
del t1[0]
del t1[len(t1)-1]
return t1
if __name__=='__main__':
t = [True,'Hello world',431,None,12]
print('Original: ' + str(t))
print('Modified : ' + str(middle(t)))
| true |
7760610b35f45b8ae1b9493a8e210aaa5a19f867 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 6/palindrome.py | 1,160 | 4.1875 | 4 | #Exercise 6-3 from "Think python 2e"
def first(word):
"""It returns the first character of a string"""
return word[0]
def last(word):
"""It returns the last character of a string"""
return word[-1]
def midle(word):
"""It returns the string between the last and the first character of a stirng"""
return word[1:-1]
def is_palindrome(word):
"""It checks whether or not a word is palindrome"""
return is_palindrome_not_inclusive(word.upper())
def is_palindrome_not_inclusive(word):
"""It checks whether or not a word that only contains
upper case letters or only contains lower case letters is palindrome."""
if len(word)<2:
return True
elif first(word)==last(word) and is_palindrome(midle(word)):
return True
else:
return False
if __name__== "__main__":
print(midle("ab"))
print(midle("a"))
while(True):
word = input("Type a word to check whether or not it is palindrome or just press enter to exit:\n")
if len(word) > 0:
print(word + (" is palindrome." if is_palindrome(word) else " is not palindrome."))
else:
break
| true |
7b22dbbe8673675d1ecfca185877c903899b4745 | EliMendozaEscudero/ThinkPython2ndEdition-Solutions | /Chapter 10/Exercise10-5.py | 363 | 4.125 | 4 | def is_sorted(t):
"""It take a list and returns True if it's sorted in
ascending order and False otherwise."""
t1 = t[:]
t1.sort()
if t == t1:
return True
else:
return False
if __name__=='__main__':
t = [42,1,32,0,-2341,2]
t1 = [1,3,5,10,100]
print(str(t)+'\nSorted: '+str(is_sorted(t)))
print(str(t1)+'\nSorted: '+str(is_sorted(t1)))
| true |
1475f834d657d0a4bd22927def4b5ec47f8f9b24 | Chris-LewisI/OOP-Python | /week-7/set_assignment.py | 1,043 | 4.375 | 4 | # Author: Chris Ibraheem
# The following code below will use the random module to create a list of values from 1 to 10.
# Using the code below to create a random list of values, do the following:
# Count the number of times each number (1-10) appears in the list that was created. Print out a formatted string that lists the number and the count for that number Use a set object to remove the duplicates from the list. Confirm the set successfully removed the duplicates by printing out the length of the set.
# imports random library so that it can create a list with random variables
import random
random.seed(1)
list_of_numbers=[random.randint(1,10) for i in range(100)]
# counting and printing the amount of occurrences for each of the numbers 1 - 10
for x in range(1,11):
counter = 0
for y in list_of_numbers:
if x == y:
counter = counter + 1
print(f"{x}:\t{counter}")
# create a set to remove duplicates and display it to verify
set_of_numbers = set(list_of_numbers)
print(f"Set Of Numbers: {set_of_numbers}") | true |
8ce325259a74dff8fb76ded6fbbaca275aa86624 | Chris-LewisI/OOP-Python | /week-1-&-2/exercise-1.py | 267 | 4.1875 | 4 | # author: Chris Ibraheem
# takes first name as input after prompt
first_name = input("First Name: ")
# takes last name as input after prompt
last_name = input("Last Name: ")
# prints a greeting using the string input from the user
print(f"Hello {first_name} {last_name}!")
| true |
c2ca0fda6cce4e0a8461479fba4b2488dc930471 | NickjClark1/PythonClass | /Chapter 5/rebuiltfromscratch.py | 682 | 4.125 | 4 | # Output program's purpose
print("Decimal to Base 2-16 converter\n")
def main():
print("Decimal to Base 2-16 converter\n")
number = int(input("Enter a number to convert: "))
for base in range(1, 17):
print (convertDecimalTo(number, base))
#end main function
def convertDecimalTo(number, base):
result = ""
number = number // base
while number > 0:
remainder = number % base
if remainder < 10:
result = (remainder) + number
return result
else:
result = 8
return result
main()
# while number > 0: remainder = number % base | true |
ed03cef20773b13070143965de70c7ae5bbff50e | aayush26j/DevOps | /practical.py | 275 | 4.28125 | 4 | num=int(input(print("Enter a number\n")))
factorial = 1
if num < 0:
print("Number is negative,hence no factorial.")
elif num ==0:
print("The factorial is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("The factorial is ",factorial) | true |
ecb0fcd7b5843debc01afe56646dd0ad834db33b | jocassid/Miscellaneous | /sqlInjectionExample/sqlInjection.py | 2,942 | 4.15625 | 4 | #!/usr/bin/env python3
from sqlite3 import connect, Cursor
from random import randint
class UnsafeCursor:
"""Wrapper around sqlite cursor to make it more susceptible to a basic
SQL injection attack"""
def __init__(self, cursor):
self.cursor = cursor
def execute(self, sql, params=None):
"""Standard cursor.execute only allows a single SQL command to be run"""
if params is None:
for statement in sql.split(';'):
self.cursor.execute(statement)
return
print('string parameters get escaped to guard against sql injection')
print("resulting sql is " + \
sql.replace("?", "'" + params[0].replace("'", "''") + "'"))
self.cursor.execute(sql, params)
def executemany(self, sql, params):
self.cursor.executemany(sql, params)
def __iter__(self):
return self.cursor.__iter__()
with connect(':memory:') as conn:
cursor = conn.cursor()
# This is a hack to make it easy to perform the classic SQL injection hack
cursor = UnsafeCursor(cursor)
cursor.execute("CREATE TABLE Book(title text, author text)")
books = [
("Pattern Recognition", "William Gibson"),
("Hitchhiker's Guide to the Galaxy", "Douglas Adams"),
("Witches Abroad", "Terry Pratchett")
]
cursor.executemany("INSERT INTO Book VALUES(?, ?)", books)
cursor.execute("""CREATE TABLE User(username text, is_admin text)""")
cursor.execute("""INSERT INTO User VALUES('hacker', 'N')""")
conn.commit()
print("Starting Contents of database")
sql = "SELECT * FROM Book"
print(sql)
cursor.execute(sql)
for row in cursor:
print(row)
sql = "SELECT * FROM User"
print("\n" + sql)
cursor.execute(sql)
for row in cursor:
print(row)
print("\nA harmless query using author value provided by user")
author = 'William Gibson'
sql = "SELECT * FROM Book WHERE author='" + author + "'"
print(sql)
cursor.execute(sql)
for row in cursor:
print(row)
print("\nNow the hacker enters a value for author to inject a 2nd statement separated by a semicolon")
author = "'; UPDATE User SET is_admin='Y' WHERE username='hacker"
sql = "SELECT * FROM Book WHERE author='" + author + "'"
print(sql)
cursor.execute(sql)
print("\nThe hacker now has admin access")
cursor.execute("SELECT * FROM User")
for row in cursor:
print(row)
print("\nReset hacker account back to normal")
cursor.execute("UPDATE User SET is_admin='N' WHERE username='hacker'")
cursor.execute("SELECT * FROM User")
for row in cursor:
print(row)
print("\nQuery written the safe way")
cursor.execute(
"SELECT * FROM Book WHERE author=?",
(author,))
| true |
3d9afb50aa377e790a19cdabd9db440969fae7a8 | jkaria/coding-practice | /python3/Chap_9_BinaryTrees/9.2-symmetric_binary_tree.py | 1,627 | 4.25 | 4 | #!/usr/local/bin/python3
from node import BinaryTreeNode
def is_symmetric(tree):
def check_symmetric(subtree_0, subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_0 and subtree_1:
return (subtree_0.data == subtree_1.data
and check_symmetric(subtree_0.left, subtree_1.right)
and check_symmetric(subtree_0.right, subtree_1.left))
# else one is null i.e. not symmetric
return False
return not tree or check_symmetric(tree.left, tree.right)
if __name__ == '__main__':
print('Test if a binary tree is symmetric')
print("is_symmetric(None) ->", is_symmetric(None))
single_node = BinaryTreeNode(314)
print("is_symmetric(single_node) ->", is_symmetric(single_node))
symtree_1 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_1.left.right = BinaryTreeNode(2, right=BinaryTreeNode(3))
symtree_1.right.left = BinaryTreeNode(2, left=BinaryTreeNode(3))
print("is_symmetric(symtree_1) ->", is_symmetric(symtree_1))
symtree_2 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_2.left.right = BinaryTreeNode(561, right=BinaryTreeNode(3))
symtree_2.right.left = BinaryTreeNode(2, left=BinaryTreeNode(3))
print("is_symmetric(symtree_2) ->", is_symmetric(symtree_2))
symtree_3 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_3.left.right = BinaryTreeNode(561, right=BinaryTreeNode(3))
symtree_3.right.left = BinaryTreeNode(561)
print("is_symmetric(symtree_3) ->", is_symmetric(symtree_3))
| true |
9a3c939c18e9c648a02710031af7e5da96cc3374 | krunal16-c/pythonprojects | /Days_to_years.py | 440 | 4.3125 | 4 | # Converting days into years using python 3
WEEK_DAYS = 7
# deining a function to find year, week, days
def find(no_of_days):
# assuming that year is of 365 days
year = int(no_of_days/365)
week = int((no_of_days%365)/WEEK_DAYS)
days = (no_of_days%365)%WEEK_DAYS
print("years",year,
"\nWeeks",week,
"\ndays", days)
# driver code
no_of_days = int(input("Enter number of days.\n"))
find(no_of_days)
| true |
130aee595a5c7aa78c89d5ee034129315afdbe10 | mrkarppinen/the-biggest-square | /main.py | 1,804 | 4.1875 | 4 |
import sys
def find_biggest_square(towers):
# sort towers based on height
towers.sort(key=lambda pair: pair[1], reverse = True)
# indexes list will hold tower indexes
indexes = [None] * len(towers)
biggestSquare = 0
# loop thorough ordered towers list
for tower in towers:
height = tower[1]
index = tower[0]
if (height <= biggestSquare):
# if already found square with size height * height
# return biggestSquare as towers are getting shorter
return biggestSquare
indexes[index] = index
# indexes list will contain towers taller than this tower
# check how many neighbour towers are already in the list
# so the biggestSquare after this tower is added to list is
# neighborougs * height
size = tower_sequence(indexes, index, height)
if ( size > biggestSquare ):
biggestSquare = size
return None
def tower_sequence(items, i, maxLength):
leftNeighbours = neighbours(items, i, -1, max(0, i-maxLength) )
if (leftNeighbours + 1 == maxLength):
return maxLength
rightNeighbours = neighbours(items, i, 1, min(len(items)-1, i + (maxLength - leftNeighbours) ) )
return (leftNeighbours + rightNeighbours + 1)
def neighbours(items, i, step, end):
if i == end:
return 0
start = i + step
end = end + step
for index in xrange(start, end, step):
if items[index] == None:
return abs(i-index)-1
return abs(start - end)
if __name__ == "__main__":
filename = sys.argv[1] if len(sys.argv) == 2 else 'input.txt'
input = open(filename)
towers = [ (index, int(line)) for index, line in enumerate(input)]
print 'Solution ' + str(find_biggest_square(towers))
| true |
4239700e5be91ec7126fecc11dbc4ab405f22a3e | RHIT-CSSE/catapult | /Code/Raindrops/StevesObjectExamples/EmployeeClass.py | 1,055 | 4.375 | 4 | # First we define the class:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
# End of class definition
# Now we can use the class, either here, or in other python files in the same directory.
# In the latter case, we would say "import EmployeeClass" to get access to this class.
# Let's try a couple examples here:
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
print ("Employee 1 age is ",emp1.age)
# same kind of thing but usings lists
# lets give everbody a raise!
all_employees = [emp1, emp2]
for e in all_employees:
e.salary = e.salary + 100
e.displayEmployee()
| true |
69e2a5128e5c34f2968e5bde4ea733630ef74134 | RHIT-CSSE/catapult | /Code/DogBark/Session3FirstProgram.py | 2,700 | 4.75 | 5 | # This is an example of a whole program, for you to modify.
# It shows "for loops", "while loops" and "if statements".
# And it gives you an idea of how function calls would be used
# to make an entire program do something you want.
# Python reads the program from top to bottom:
# First there are two functions. These don't really "do"
# anything until they are called later.
# This function finds the prime divisors of a number.
# Nothing to do here, but it shows a function with a while-loop
# and an if-statement.
def divisorsOf(bigNumber):
listOfDivisors = [] # An empty list, to start building from
nextNumber = bigNumber
nextDivisor = 2
while (bigNumber > 1):
if (bigNumber % nextDivisor == 0):
#print(" "+str(nextDivisor))
bigNumber = bigNumber // nextDivisor
listOfDivisors.append(nextDivisor) # add to the list
else:
nextDivisor = nextDivisor+1
return listOfDivisors
# This function finds the season of a date, as in the Session 2 slides.
# The year parameter isn't used!
# This one has a "TODO" at the bottom:
def seasonOf(date): # The date is a "tuple" of month, day, year
month = date[0] # These commands separate the 3 parts of the tuple
day = date[1]
year = date[2]
season = "error" # in case a date is not assigned to a season
if (month == 10 or month == 11):
season = "fall"
elif (month == 1 or month == 2):
season = "winter"
elif (month == 4 or month == 5):
season = "spring"
elif (month == 7 or month == 8):
season = "summer"
elif (month == 12):
if (day < 21):
season = "fall"
else:
season = "winter"
elif (month == 3):
if (day < 21):
season = "winter"
else:
season = "spring"
return season
# TODO: You finish this function, for months 6 and 9, above the return!
# Then here's the part of the program which really causes
# something to happen. Code that includes calling the functions
# defined above:
print("Hello world!")
# Test cases:
print("Divisor tests:")
# The for-loop picks consecutive values from a Python "list":
for myDivisorTest in [2,3,4,5,6,7,8,9,12,13,24,35]:
print("Prime divisors of "+str(myDivisorTest))
print (divisorsOf(myDivisorTest))
print("Season tests:")
# This is a list of "tuples" representing dates:
myDateList = [ (1,1,2019), (2,1,2019), (3,1,2019), (3,25,2019),
(4,1,2019), (5,1,2019), (6,1,2019), (6,25,2019),
(7,1,2019), (8,1,2019), (9,1,2019), (9,25,2019),
(10,1,2019), (11,1,2019), (12,1,2019), (12,25,2019) ]
for myDateTest in myDateList:
print (seasonOf(myDateTest))
| true |
69beb8bab0fe28d2e94cc6f12b60ecf73dba3852 | dmaydan/AlgorithmsTextbook-Exercises | /Chapter4/exercise2.py | 210 | 4.28125 | 4 | # WRITE A RECURSIVE FUNCTION TO REVERSE A LIST
def reverse(listToReverse):
if len(listToReverse) == 1:
return listToReverse
else:
return reverse(listToReverse[1:]) + listToReverse[0:1]
print(reverse([1])) | true |
0cc02c8d3f8a59c29a8ef55ab9fee88a2f768399 | Suiname/LearnPython | /dictionary.py | 861 | 4.125 | 4 | phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print phonebook
phonebook2 = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print phonebook2
print phonebook == phonebook2
for name, number in phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
del phonebook["John"]
print phonebook
phonebook2.pop("John")
print phonebook2
# Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# write your code here
phonebook["Jake"] = 938273443
phonebook.pop("Jill")
# testing code
if "Jake" in phonebook:
print "Jake is listed in the phonebook."
if "Jill" not in phonebook:
print "Jill is not listed in the phonebook."
| true |
2fb640ca926f9769d4ee6f9c0de68e1de8b5729c | organisciak/field-exam | /stoplisting/__init__.py | 1,421 | 4.1875 | 4 | '''
Python code
Example of word frequencies with and without stopwords.
Uses Natural Language Toolkit (NLTK) - Bird et al. 2009
bush.txt is from http://www.bartleby.com/124/pres66.html
obama.txt is from http://www.whitehouse.gov/blog/inaugural-address
'''
from nltk import word_tokenize
from nltk.probability import FreqDist
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize
def main():
# Number of words to display
count = 40
# Open files as strings
obama = open("obama.txt", "r").read()
bush = open("bush.txt", "r").read()
#Tokenize texts into words, then count frequencies for all words
top_obama = FreqDist(word.lower() for word in word_tokenize(obama))
top_bush = FreqDist(word.lower() for word in word_tokenize(bush))
#Return top {count} most occurring words
print "No stoplist".upper()
print "Obama/2009\t".upper(), " ".join(item[0] for item in top_obama.items()[:count])
print "Bush/2001\t".upper(), " ".join(item[0] for item in top_bush.items()[:count])
#Return most occurring words that are not in the NLTK English stoplist
print
print "Stoplisted".upper()
print "Obama/2009\t".upper(), " ".join([item[0] for item in top_obama.items() if not item[0] in stopwords.words('english')][:count])
print "Bush/2001\t".upper(), " ".join([item[0] for item in top_bush.items() if not item[0] in stopwords.words('english')][:count])
if __name__ == '__main__':
main()
| true |
6d315993b7fe772ac2d2fe290db19438efad581e | sumittal/coding-practice | /python/print_anagram_together.py | 1,368 | 4.375 | 4 | # A Python program to print all anagarms together
#structure for each word of duplicate array
class Word():
def __init__(self, string, index):
self.string = string
self.index = index
# create a duplicate array object that contains an array of Words
def create_dup_array(string, size):
dup_array = []
for i in range(size):
dup_array.append(Word(string[i], i))
return dup_array
# Given a list of words in wordArr[]
def print_anagrams_together(wordArr, size):
# Step 1: Create a copy of all words present in
# given wordArr.
# The copy will also have orignal indexes of words
dupArray = create_dup_array(wordArr, size)
# Step 2: Iterate through all words in dupArray and sort
# individual words.
for i in range(size):
dupArray[i].string = ''.join(sorted(dupArray[i].string))
# Step 3: Now sort the array of words in dupArray
dupArray = sorted(dupArray, key=lambda k: k.string)
# Step 4: Now all words in dupArray are together, but
# these words are changed. Use the index member of word
# struct to get the corresponding original word
for word in dupArray:
print(wordArr[word.index])
# Driver program
wordArr = ["cat", "dog", "tac", "god", "act"]
size = len(wordArr)
print_anagrams_together(wordArr, size)
| true |
39ac1ff3e0e7a78438a9015f83708fc95fdcf1b4 | sumittal/coding-practice | /python/trees/diameter.py | 930 | 4.1875 | 4 | """
Diameter of a Binary Tree
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.
"""
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
def diameter(root):
if root is None:
return 0
# Get the height of left and right sub-trees
lh = height(root.left)
rh = height(root.right)
# Get the diameter of left and irgh sub-trees
ld = diameter(root.left)
rd = diameter(root.right)
return max(1 + lh + rh, max(ld, rd))
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Diameter of given binary tree is %d" %(diameter(root)))
| true |
0b6eaf6f099c3b7197101b2d8892e3529f2f0c75 | FabioOJacob/instruct_test | /main.py | 2,136 | 4.1875 | 4 | import math
class Point():
"""
A two-dimensional Point with an x and an y value
>>> Point(0.0, 0.0)
Point(0.0, 0.0)
>>> Point(1.0, 0.0).x
1.0
>>> Point(0.0, 2.0).y
2.0
>>> Point(y = 3.0, x = 1.0).y
3.0
>>> Point(1, 2)
Traceback (most recent call last):
...
ValueError: both coordinates value must be float
>>> a = Point(0.0, 1.0)
>>> a.x
0.0
>>> a.x = 3.0
>>> a.x
3.0
"""
def __init__(self, x, y):
self.x = x
self.y = y
if type(self.x) != float and type(self.y) != float:
raise ValueError('both coordinates value must be float')
def __repr__(self):
return f'{self.__class__.__name__}({str(self.x)}, {str(self.y)})'
def verifica(a, b):
if type(a) != Point:
raise ValueError('a must be a Point')
elif type(b) != Point:
raise ValueError('b must be a Point')
def euclidean_distance(a, b):
"""
Returns the euclidean distance between Point a and Point b
>>> euclidean_distance(Point(0.0, 0.0), Point(3.0, 4.0))
5.0
>>> euclidean_distance((0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: a must be a Point
>>> euclidean_distance(Point(0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: b must be a Point
"""
from math import sqrt
verifica(a, b)
dist = sqrt( (a.x - b.x)**2 + (a.y - b.y)**2 )
return dist
def manhattan_distance(a, b):
"""
Returns the manhattan distance between Point a and Point b
>>> manhattan_distance(Point(0.0, 0.0), Point(3.0, 4.0))
7.0
>>> manhattan_distance((0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: a must be a Point
>>> manhattan_distance(Point(0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: b must be a Point
"""
from math import fabs
verifica(a, b)
dist = fabs( a.x - b.x) + fabs( a.y - b.y)
return dist
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
a2df6569fb7553f72667c03ae67ace637b9b9dbb | akaliutau/cs-problems-python | /problems/sort/Solution406.py | 1,615 | 4.125 | 4 | """ You are given an array of people, people, which are the attributes of some
people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith person of height hi with exactly ki other people in front
who have a height greater than or equal to hi. Reconstruct and return the
queue that is represented by the input array people. The returned queue
should be formatted as an array queue, where queue[j] = [hj, kj] is the
attributes of the jth person in the queue (queue[0] is the person at the
front of the queue).
Example 1: Input: people =
[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] Output:
[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Explanation: Person 0 has height 5 with
no other people taller or the same height in front. Person 1 has height 7
with no other people taller or the same height in front. Person 2 has height
5 with two persons taller or the same height in front, which is person 0 and
1. Person 3 has height 6 with one person taller or the same height in front,
which is person 1. Person 4 has height 4 with four people taller or the same
height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with
one person taller or the same height in front, which is person 1. Hence
[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
IDEA:
1) use sorting to track the shortest person
2) on each check compare (the number of people already in queue) with (number of needed persons to be ahead)
3) add the person at optimal position
"""
class Solution406:
pass
| true |
657280e2cf8fbbc26b59ed7830b342713cac502b | akaliutau/cs-problems-python | /problems/hashtable/Solution957.py | 1,240 | 4.15625 | 4 | """ There are 8 prison cells in a row, and each cell is either occupied or
vacant.
Each day, whether the cell is occupied or vacant changes according to the
following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant,
then the cell becomes occupied. Otherwise, it becomes vacant. (Note that
because the prison is a row, the first and the last cells in the row can't
have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] ==
1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N
days (and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0]
Explanation: The following table summarizes the state of the prison on each
day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
"""
class Solution957:
pass
| true |
1ac4822dd02e34f946f4183122d8a6b5ec804d02 | akaliutau/cs-problems-python | /problems/greedy/Solution678.py | 1,937 | 4.25 | 4 | """ Given a string containing only three types of characters: '(', ')' and '*',
write a function to check whether trightBoundarys string is valid. We define
the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any
right parenthesis ')' must have a corresponding left parenthesis '('. Left
parenthesis '(' must go before the corresponding right parenthesis ')'. '*'
could be treated as a single right parenthesis ')' or a single left
parenthesis '(' or an empty string. An empty string is also valid.
Example 1: Input: "()" Output: True
( * ) )
l 1 0 -1 -2
t 1 2 1 0
When checking whether the string is valid, we only cared about the "balance":
the number of extra, open left brackets as we parsed through the string. For
example, when checking whether '(()())' is valid, we had a balance of 1, 2,
1, 2, 1, 0 as we parse through the string: '(' has 1 left bracket, '((' has
2, '(()' has 1, and so on. This means that after parsing the first i symbols,
(which may include asterisks,) we only need to keep track of what the balance
could be.
For example, if we have string '(***)', then as we parse each symbol, the set
of possible values for the balance is
[1] for '(';
[0, 1, 2] for '(*';
[0, 1, 2, 3] for '(**';
[0, 1, 2, 3, 4] for '(***', and
[0, 1, 2, 3] for '(***)'.
Furthermore, we can prove these states always form a contiguous interval.
Thus, we only need to know the left and right bounds of this interval. That
is, we would keep those intermediate states described above as [lo, hi] = [1,
1], [0, 2], [0, 3], [0, 4], [0, 3].
Algorithm
Let lo, hi respectively be the smallest and largest possible number of open
left brackets after processing the current character in the string.
"""
class Solution678:
pass
| true |
f4248de8ff831fbb0103ccce3c0effde23ea28ad | akaliutau/cs-problems-python | /problems/backtracking/Solution291.py | 830 | 4.4375 | 4 | """ Given a pattern and a string s, return true if s matches the pattern. A
string s matches a pattern if there is some bijective mapping of single
characters to strings such that if each character in pattern is replaced by
the string it maps to, then the resulting string is s. A bijective mapping
means that no two characters mapping to the same string, and no character maps to
two different strings.
Example 1: Input: pattern = "abab", s =
"redblueredblue" Output: true
Explanation: One possible mapping is as
follows: 'a' -> "red" 'b' -> "blue"
IDEA:
1) start with smallest cut, then expanding initial string
2) apply this process recursively to the rest part of the string
Example:
pattern = aba, s = bluewhiteblue
"""
class Solution291:
pass
| true |
9369936045f15e39fe607e57906f4811c519fde6 | akaliutau/cs-problems-python | /problems/bfs/Solution1293.py | 1,001 | 4.28125 | 4 | """ Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In
one step, you can move up, down, left or right from and to an empty cell.
Return the minimum number of steps to walk from the upper left corner (0, 0)
to the lower right corner (m-1, n-1) given that you can eliminate at most k
obstacles. If it is not possible to find such walk return -1.
Example 1:
Input: grid =
[
[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]
],
k = 1 Output: 6
Explanation: The shortest path without eliminating any obstacle is 10. The
shortest path with one obstacle elimination at position (3,2) is 6. Such path
is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
IDEA:
1) use a classical BFS - which is ALWAYS return the shortest path due to its nature
2) track a current number of overcome obstacles - and traverse this value along with coords on next cell to process
"""
class Solution1293:
pass
| true |
41acdd2f91669a03c8ab44e35ea7a7b786be3454 | anettkeszler/ds-algorithms-python | /codewars/6kyu_break_camel_case.py | 508 | 4.4375 | 4 | # Complete the solution so that the function will break up camel casing, using a space between words.
# Example
# solution("camelCasing") == "camel Casing"
import re
def solution(s):
result = ""
for char in s:
if char.isupper():
break
result += char
result += " "
splitted = re.findall('[A-Z][^A-Z]*', s)
result += " ".join(splitted)
return result
hello = solution("camelCasing")
print(hello)
hello = solution("helloNettiHowAreYou")
print(hello)
| true |
b5b4ebc84d31f10c982dfc65275c44cf9d6a6703 | saraatsai/py_practice | /number_guessing.py | 928 | 4.1875 | 4 | import random
# Generate random number
comp = random.randint(1,10)
# print (comp)
count = 0
while True:
guess = input('Guess a number between 1 and 10: ')
try:
guess_int = int(guess)
if guess_int > 10 or guess_int < 1:
print('Number is not between 1 and 10. Please enter a valid number.')
else:
# Guess is too big
if int(guess) > comp:
count += 1
print('Too big, guess again')
# Guess is too small
elif int(guess) < comp:
count += 1
print('Too small, guess again')
else:
print('You win!')
print('Number of guesses: ', count+1)
break
except ValueError:
try:
float(guess)
break
except ValueError:
print('Invalid input. Please enter a valid number.')
| true |
bb20892c11b9fedb0fe35696b45af31451bbe7e8 | Devbata/icpu | /Chapter3/Fexercise3-3-1.py | 594 | 4.25 | 4 | # -*- coding: utf-8 -*-
#Bisecting to find appproximate square root.
x = float(input('Please pick a number you want to find the square root of: '))
epsilon = 1*10**(-3)
NumGuesses = 0
low = 0.0
high = max(1.0, abs(x))
ans = (high + low)/2.0
while abs(ans**2 - abs(x)) >= epsilon:
print('low =', low, 'high =', high, 'ans =', ans)
NumGuesses += 1
if ans**2 < abs(x):
low = ans
else:
high = ans
ans = (high + low)/2.0
if x < 0:
ans = str(ans)+'i'
print('NumGuesses =', NumGuesses)
print(ans, 'is hella close- to the square root of', x) | true |
6858af583e1ad4657650d185b87f289aec26a1a4 | Anvin3/python | /Basic/divisor.py | 261 | 4.15625 | 4 | '''
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
'''
num=int(input("Please enter a number of your choice:"))
subList=[i for i in range(2,num) if num%i==0 ]
print("All the divisors are",subList) | true |
382dbb2572586d26f9f335e004f6886f74abdc07 | anjana-analyst/Programming-Tutorials | /Competitive Programming/DAY-29/metm.py | 323 | 4.15625 | 4 | def time(hh,mm,ss):
return hh+(mm/60)+(ss/60)/60
def distance():
m=int(input("Enter the meters"))
hh=int(input("Enter the hours"))
mm=int(input("Enter the minutes"))
ss=int(input("Enter the seconds"))
miles=(m*0.000621372)/time(hh,mm,ss);
print("Miles per hour is ",miles)
distance()
| true |
63d10fa7f02ba38539f03a49c09dccb6d36dbc70 | MiguelBim/Python_40_c | /Challenge_31.py | 1,250 | 4.1875 | 4 | # CHALLENGE NUMBER 31
# TOPIC: Funct
# Dice App
# https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060876#overview
import random
def dice_app(num_of_dice, roll_times):
total_count = 0
print("\n-----Results are as followed-----")
for rolling in range(roll_times):
val_from_rolling = random.randint(1, num_of_dice)
print("\t\t{}".format(val_from_rolling))
total_count += val_from_rolling
print("The total value of your roll is {}.".format(total_count))
return
if __name__ == '__main__':
print("Welcome to the Python Dice App")
run_app = True
while run_app:
dice_sides = int(input("\nHow many sides would you like on your dice: ").strip())
dice_number = int(input("How many dice would you like to roll: "))
print("\nYou rolled {} {} side dice.".format(dice_number, dice_sides))
dice_app(dice_sides,dice_number)
play_again = input("\nWould you like to roll again (y/n): ").lower().strip()
if play_again == 'n':
run_app = False
print("Thank you for using the Python Dice App.")
elif play_again != 'y':
run_app = False
print('\nThat is not a valid option. Exiting from app.') | true |
18a56761663e1202e10e77d40b4a6cfb5cd47763 | JordiDeSanta/PythonPractices | /passwordcreator.py | 1,600 | 4.34375 | 4 | print("Create a password: ")
# Parameters
minimunlength = 8
numbers = 2
alphanumericchars = 1
uppercasechars = 1
lowercasechars = 1
aprobated = False
def successFunction():
print("Your password is successfully created!")
aprobated = True
def printPasswordRequisites():
print("The password requires:")
print(minimunlength, "characters minimum")
print(numbers, "numbers")
print(alphanumericchars, "alpha numeric characters")
print(uppercasechars, "uppercase characters")
print("Please write other password: ")
# While the password is not aprobated, ask to the user again
while aprobated == False:
# USername ask
password = input()
# Check character per character if the password pass the security test
uppercaseCount = 0
lowercaseCount = 0
numberCount = 0
alphanumericCount = 0
for i in range(len(password)):
# Uppercase check
if(password[i].isupper()):
uppercaseCount += 1
# Lowercase check
if(password[i].islower):
lowercaseCount += 1
# Numbers check
if(password[i].isnumeric()):
numberCount += 1
# Aphanumeric check
if(password[i].isalnum()):
alphanumericCount += 1
pass
# Final check with the requirements
if(len(password) >= minimunlength and uppercaseCount >= uppercasechars and lowercaseCount >= lowercasechars and numberCount >= numbers and alphanumericCount >= alphanumericchars):
successFunction()
else:
printPasswordRequisites()
pass
pass
| true |
736fbfee5775cb351f4ee8acabeb5321c0a38c84 | SinglePIXL/CSM10P | /Homework/distanceTraveled.py | 451 | 4.3125 | 4 | """
Alec
distance.py
8-21-19
Ver 1.4
Get the speed of the car from the user then we calculate distances traveled for
5, 8, and 12 hours.
"""
mph = int(input('Enter the speed of the car:'))
time = 5
distance = mph * time
print('The distance traveled in 5 miles is:', distance)
time = 8
distance = mph * time
print('The distnace traveled in 8 miles is:', distance)
time = 12
distance = mph * time
print('The distance traveled in 12 miles is:', distance) | true |
e7acd1abad675af9ccd1b1b8bddc11884020ea8b | SinglePIXL/CSM10P | /Testing/10-7-19 Lecture/errorTypes.py | 982 | 4.125 | 4 | # IOError: if the file cannot be opened.
# ImportError: if python cannot find the module.
# ValueError: Raised when a built in operation or function recieves an argument
# that has the right type but an inapropriate value
# KeyboardInterrupt: Raised when the user hits the interrupt key
# EOFError: Raised one of the builtin functions (like input()) hits an end
# of file condition (EOF) without reading any
# forty = ValueError
# Using "assert" statement ou ca initially create your own exception
# assert statement checks for a condition. If the condition is not met(false)
# then it will throw exception error.
def input_age(age):
try:
assert int(age)>18
except ValueError:
return 'ValueError: cannot convert to int'
else:
return 'Age is saved succesfully.'
def main():
age = int(input('Enter your age'))
print(input_age(age))
print(input_age('23'))
print(input_age(25))
print(input_age('nothing'))
main() | true |
288f685744aa6609b795bf433a18ea2ffbb24008 | SinglePIXL/CSM10P | /Testing/9-13-19 Lecture/throwaway.py | 489 | 4.1875 | 4 | def determine_total_Grade(average):
if average <= 100 and average >= 90:
print('Your average of ', average, 'is an A!')
elif average <= 89 and average >= 80:
print('Your average of ', average, 'is a B.')
elif average <= 79 and average >= 70:
print('Your average of ', average, 'is a C')
elif average <= 69 and average >= 70:
print('Your average of ', average, 'is a D')
else:
print('Your average of ', average, 'is an F') | true |
6e1fb9392f9533ac4803cc93cb122d4ddd85ab52 | SinglePIXL/CSM10P | /Lab/fallingDistance.py | 874 | 4.21875 | 4 | # Alec
# fallingDistance.py
# 9-21-19
# Ver 1.3
# Accept an object's falling time in seconds as an argument.
# The function should return the distance in meters that the object has fallen
# during that time interval. Write a program that calls the function in a loop
# that passes the values 1 through 10 as arguments and displays the return
# value
# Display calculation for distance of a falling object
def main():
# Seconds: Range is 1 second to 10
for i in range(1,11):
# Print the calculation
print('Object has traveled', format (falling_distance(i),',.2f'),\
'meters per', i, 'second/s.')
# Define variables gravity and distnace
# Time is passed into this function through the timeTraveled arguement
def falling_distance(timeTraveled):
gravity = 9.8
distance = 0.5 * gravity * (timeTraveled ** 2)
return distance
main() | true |
d1f1e3c5760e32f745a2d798bba26f1c1abb3ca2 | MyloTuT/IntroToPython | /Homework/HW1/hw1.py | 1,213 | 4.25 | 4 | #!/usr/bin/env python3
#Ex1.1
x = 2 #assign first to variable
y = 4 #assign second to variable
z = 6.0 #assign float to variable
vsum = x + y + z
print(vsum)
#Ex1.2
a = 10
b = 20
mSum = 10 * 20
print(mSum)
#Ex1.3
var = '5'
var2 = '10'
convert_one = int(var) #convert var into an int and assign to a variable
convert_two = int(var2) #convert var2 into an int and assign to a variable
var_total = convert_one + convert_two
print(var_total) #print the total of var and var2 as converted integers
#Ex1.4
user_var = input('Please enter an integer: ') #request a integer from a user
user_doubled = int(user_var) * 2
print(user_doubled)
#Ex1.5
user_place = input('Name your favorite place: ')
print('Hello,' + ' ' + user_place + '!')
#Ex1.6
multi_exclamation = input('Please enter your excitement level: ')
print('Hello,' + ' ' + user_place + '!' * int(multi_exclamation))
#Ex1.7
thirty_five = 35.30
tf_output = round(thirty_five)
print(tf_output)
#Ex1.8
tf_super_float = 35.359958
tf_rounded_two = round(tf_super_float, 2)
print(tf_rounded_two)
#Ex1.9
var = "5"
var2 = "4"
var_conversion = int(var)
var2_conversion = int(var2)
var_sum = var_conversion / var2_conversion
print(var_sum)
| true |
ce5015940881770acdbb6fd87af458b35d99c86b | GingerBeardx/Python | /Python_Fundamentals/type_list.py | 908 | 4.40625 | 4 | def tester(case):
string = "String: "
adds = 0
strings = 0
numbers = 0
for element in case:
print element
# first determine the data type
if isinstance(element, float) or isinstance(element, int) == True:
adds += element
numbers += 1
elif isinstance(element, basestring) == True:
# if string - determine if string is short or long
string += element + " "
strings += 1
if strings > 0 and numbers > 0:
print "The list you entered is of mixed types"
elif strings > 0:
print "The list you entered is of string type"
elif numbers > 0:
print "The list you entered is of integer type"
print string
print "Sum:", adds
case_1 = ['magical unicorns', 19, 'hello', 98.98, 'world']
case_2 = [2, 3, 1, 7, 4, 12]
case_3 = ['magical', 'unicorns']
tester(case_2)
| true |
a2c485ba03991204912d6dd23b32d8d17daa3c25 | GingerBeardx/Python | /Python_Fundamentals/loops.py | 340 | 4.34375 | 4 | for count in range(0, 5):
print "looping - ", count
# create a new list
# remember lists can hold many data-types, even lists!
my_list = [4, 'dog', 99, ['list', 'inside', 'another'], 'hello world!']
for element in my_list:
print element
count = 0
while count < 5: # notice the colon!
print 'looping - ', count
count += 1
| true |
780c24fd5b63cab288383303d3ac8680691afd18 | MicheSi/code_challenges | /isValid.py | 1,421 | 4.34375 | 4 | '''
Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just character at index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.
For example, if , it is a valid string because frequencies are . So is because we can remove one and have of each character in the remaining string. If however, the string is not valid as we can only remove occurrence of . That would leave character frequencies of .
Function Description
Complete the isValid function in the editor below. It should return either the string YES or the string NO.
isValid has the following parameter(s):
s: a string
Input Format
A single string .
Constraints
Each character
Output Format
Print YES if string is valid, otherwise, print NO.
Sample Input 0
aabbcd
Sample Output 0
NO
'''
def isValid(s):
visited = []
for i in s:
if i not in visited:
visited.append(i)
s = s.replace(i, '', 1)
print(visited, s)
if i in visited:
s = s.replace(i, '', 1)
print(len(s))
if len(s) == 0:
return 'YES'
else:
return 'NO'
isValid('aabbcd')
isValid('aabbccddeefghi')
isValid('abcdefghhgfedecba') | true |
aa2e42c78db54ca867c25ce2113b7914bcc666ee | Keshav1506/competitive_programming | /Bit_Magic/004_geeksforgeeks_Toggle_Bits_Given_Range/Solution.py | 2,703 | 4.15625 | 4 | #
# Time :
# Space :
#
# @tag : Bit Magic
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
# GeeksForGeeks: Toggle bits given range
#
# Description:
#
# Given a non-negative number N and two values L and R.
# The problem is to toggle the bits in the range L to R in the binary representation of n,
# i.e, to toggle bits from the rightmost Lth bit to the rightmost Rth bit.
# A toggle operation flips a bit 0 to 1 and a bit 1 to 0.
# Print n after the bits are toggled.
#
#
# Example 1:
#
# Input:
# n = 17 , L = 2 , R = 3
# Output:
# 23
# Explanation:
# (17)10 = (10001)2. After toggling all
# the bits from 2nd to 3rd position we get
# (10111)2 = (23)10
# Example 2:
#
# Input:
# n = 50 , L = 2 , R = 5
# Output:
# 44
# Explanation:
# (50)10 = (110010)2. After toggling all
# the bits from 2nd to 3rd position we get
# (101100)2 = (44)10
#
#
# Your Task:
# You don't need to read input or print anything. Your task is to complete the function toggleBits()
# which takes 3 Integers n, L and R as input and returns the answer.
#
#
# Expected Time Complexity: O(1)
# Expected Auxiliary Space: O(1)
#
#
# Constraints:
# * 1 <= n <= 105
# * 1 <= L<=R <= Number of Bits in n
#
# **************************************************************************
# Source: https://practice.geeksforgeeks.org/problems/toggle-bits-given-range0952/1 (GeeksForGeeks - Toggle bits given range)
# **************************************************************************
#
# **************************************************************************
# Solution Explanation
# **************************************************************************
# Refer to Solution_Explanation.md
#
# **************************************************************************
#
import unittest
class Solution(object):
def toggleBitsFromLtoR(self, n: int, L: int, R: int) -> bool:
# calculating a number
# 'num' having 'r'
# number of bits and
# bits in the range l
# to r are the only set bits
num = ((1 << R) - 1) ^ ((1 << (L - 1)) - 1)
# toggle bits in the
# range l to r in 'n'
# Besides this, we can calculate num as: num=(1<<r)-l .
# and return the number
return n ^ num
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_toggleBitsFromLtoR(self) -> None:
sol = Solution()
for n, L, R, solution in ([17, 2, 3, 23], [50, 2, 5, 44]):
self.assertEqual(solution, sol.toggleBitsFromLtoR(n, L, R))
# main
if __name__ == "__main__":
unittest.main()
| true |
31f5a45e28ccb77adff1f5f3761e9297a121f0cd | Keshav1506/competitive_programming | /Tree_and_BST/021_leetcode_P_366_FindLeavesOfBinaryTree/Solution.py | 2,439 | 4.25 | 4 | #
# Time : O(N) [ We traverse all elements of the tree once so total time complexity is O(n) ] ; Space: O(1)
# @tag : Tree and BST ; Recursion
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
#
# LeetCode - Problem - 366: Find Leaves of Binary Tree
#
# Description:
#
# Given a binary tree, you need to compute the length of the diameter of the tree.
# The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
# This path may or may not pass through the root.
#
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
#
# **************************************************************************
# Source: https://leetcode.com/problems/find-leaves-of-binary-tree/ (Leetcode - Problem 366 - Find Leaves of Binary Tree)
#
from typing import List
import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findLeavesHelper(self, root, results):
"""
push root and all descendants to results
return the distance from root to farthest leaf
"""
if not root:
return -1
ret = 1 + max(
self.findLeavesHelper(child, results) for child in (root.left, root.right)
)
if ret >= len(results):
results.append([])
results[ret].append(root.val)
return ret
def findLeaves(self, root: TreeNode) -> List[List[int]]:
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret = []
self.findLeavesHelper(root, ret)
return ret
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_findLeaves(self) -> None:
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right = TreeNode(3)
self.assertEqual([[4, 5, 3], [2], [1]], s.findLeaves(root))
if __name__ == "__main__":
unittest.main()
| true |
0fff29228279abcae6d9fa67f111602e0423db66 | hakepg/operations | /python_sample-master/python_sample-master/basics/deepcloning.py | 757 | 4.15625 | 4 | import copy
listOfElements = ["A", "B", 10, 20, [100, 200, 300]]
# newList= listOfElements.copy() -- list method- performs shallow copy
newList = copy.deepcopy(listOfElements) # Deep copy -- method provided by copy module
newList1 = copy.copy(listOfElements) # Shallow copy -- method provided by copy module
print("Before modification: \n\nOriginal List: ", listOfElements)
print("Copied List due to shallow cloning: ", newList1)
print("Copied List due to deep cloning: ", newList)
# Modification
listOfElements[1] = 100
newList[4][0] = 200
newList1[4][2] = 100
print("\n\nAfter modification: \n\nOriginal List: ", listOfElements)
print("Copied List due to shallow cloning: ", newList1)
print("Copied List due to deep cloning: ", newList) | true |
10841b4db43d984e677eec6a8dcd00415bc8c098 | hakepg/operations | /python_sample-master/python_sample-master/basics/listExample.py | 525 | 4.15625 | 4 | # Sort in the list
# Two ways: list method -- sort and built in function -- sorted
listOfElements = [10,20,30,45,1,5,23,223,44552,34,53,2]
# Difference between sort and sorted
print(sorted(listOfElements)) # Creates new sorted list
print(listOfElements) # original list remains same
print(listOfElements.sort()) # Return None, make changes in the given list
print(listOfElements)
print(listOfElements.sort(reverse=True)) # Reverese sorting, Return None, make changes in the given list
print(listOfElements) | true |
5e49178aa33566d2e953913f919101f8a2bc1e93 | akjadon/HH | /Python/Python_Exercise/Python_Exercise1/ex38.py | 569 | 4.28125 | 4 | """Write a program that will calculate the average word length of a text
stored in a file (i.e the sum of all the lengths of the word tokens in the
text, divided by the number of word tokens)."""
from string import punctuation
def average_word_length(file_name):
with open(file_name, 'r') as f:
for line in f:
# Clean each line of punctuations, we want words only
line = filter(lambda x: x not in punctuation, line)
# We get only the length of the words
words = map(len, line.split())
print sum(words) / len(words)
average_word_length('hapax.txt') | true |
f50269a35eb4da827425795badc0ba7eab421a92 | akjadon/HH | /Python/Python_Exercise/Python_Exercise1/ex46.py | 2,938 | 4.4375 | 4 | """An alternade is a word in which its letters, taken alternatively in a
strict sequence, and used in the same order as the original word, make up at
least two other words. All letters must be used, but the smaller words are not
necessarily of the same length. For example, a word with seven letters where
every second letter is used will produce a four-letter word and a three-letter
word. Here are two examples:
"board": makes "bad" and "or".
"waists": makes "wit" and "ass".
Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt,
write a program that goes through each word in the list and tries to make two
smaller words using every second letter. The smaller words must also be members
of the list. Print the words to the screen in the above fashion."""
import re
from collections import defaultdict
# I'm still not sure if this is the best solution.
# But I think it does what the problem asks for :/
# But my, my, my, it takes around 2 minutes to finish building.
# Please, help!
def alternade_finder(file_name):
# Get our words
with open(file_name, 'r') as f:
words = re.findall(r'\w+', f.read())
# Prepare our dictionary
foundalternades = defaultdict(list)
# For each word in the list
for word in words:
# We make a copy of the words list and prepare our variables
wordlist, smallerwordeven, smallerwordodd = words[:], '', ''
# We remove the word from the list so it doesn't choose itself
# as an alternade
wordlist.remove(word)
# We only do that for words that are longer than 1 letter
if len(word) > 1:
for letters in word: # For each letter in the word
# Get the position of this letter
letter_pos = word.index(letters)
# If the letter is at an even position
if letter_pos % 2 == 0:
smallerwordeven += letters # Add this letter to the variable
# If the smaller word is in the words list and is not yet
# in the dictionary for the current word, add it to the dict
if smallerwordeven in wordlist and \
smallerwordeven not in foundalternades[word]:
foundalternades[word].append(smallerwordeven)
# If the letter is at an odd position
if letter_pos % 2 != 0:
smallerwordodd += letters # Add this letter to the variable
# If the smaller word is in the words list and is not yet
# in the dictionary for the current word, add it to the dict
if smallerwordodd in wordlist and \
smallerwordodd not in foundalternades[word]:
foundalternades[word].append(smallerwordodd)
# For each word in the dictionary
for word, alternades in foundalternades.items():
# Make a string out of all the alternades
alt = reduce(lambda x, y: x + y, alternades)
# If all the letters in the word have been used to create all
# the alternades, print this word and its alternades
if sorted(alt) == sorted(word):
print '"%s": makes %s' % (word, alternades)
#test
alternade_finder('unixdict.txt') | true |
2a5f3f611ca53f2e173c3ec12fba914a98480d6f | gmastorg/CSC121 | /M2HW1_NumberAnalysis_GabrielaCanjura(longer).py | 1,275 | 4.1875 | 4 | # gathers numbers puts them in a list
# determines correct number for each category
# 02/12/2018
# CSC-121 M2HW1 - NumberAnalysis
# Gabriela Canjura
def main():
total = float(0)
numOfNumbers = int(20) # decides loop count and used for average
total,numbers = get_values(numOfNumbers)
get_lowest(numbers)
get_highest(numbers)
get_total(total)
get_average(total, numOfNumbers)
def get_values(numOfNumbers):
values = [] # holds list of numbers
total = float(0)
for x in range (numOfNumbers): #creates loop
num = float(input("Enter a number: "))
total += num; # holds the total as numbers are entered in loop
values.append(num) # creates list
return total, values
def get_lowest(numbers):
lowest = min(numbers) # gets lowest number
print("The lowest number in the list is: " , lowest)
def get_highest(numbers):
highest = max(numbers) # gets highest number
print("The highest number in the list is: " , highest)
def get_total(total):
print("The total of the numbers is: ", total)
def get_average(total, numOfNumbers):
ave = total/numOfNumbers
print("The average of the numbers is: ", ave)
main()
| true |
1f9f2c05bffaf755d40164b3704909532d50243a | motaz-hejaze/lavaloon-problem-solving-test | /problem2.py | 1,451 | 4.1875 | 4 | print("***************** Welcome ********************")
print("heaviest word function")
print("python version 3.6+")
print("run this script to test the function by yourself")
print("or run test_problem2 for unittest script ")
# all alphabets
alphabet_dict = {
"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, \
"l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21,\
"v": 22, "w": 23, "x": 24, "y": 25, "z": 26
}
def heaviest_word(sentence):
# a dict to put all calculated words
all_words_sums = {}
# split sentence into list of words
words_list = sentence.split(" ")
# loop through all words in words_list
for word in words_list:
# split current word into a list of characters
chars_list = [c for c in word]
word_weight = 0
# loop through all characters of current word
for c in chars_list:
# calculate each character and add to word_weight
word_weight += alphabet_dict[c]
# add key , value to all words dictionary
all_words_sums[word] = word_weight
# return the (first) key with maximum weight
first_max_word = max(all_words_sums, key=all_words_sums.get)
return first_max_word
if __name__ == '__main__':
sentence = input("Please enter a sentence of words : ")
print("The Heaviest word is ({})".format(str(heaviest_word(sentence))))
| true |
0c62ff7ab5bf7afeb43db3d74580deb06abe89a2 | rohit2219/python | /decorators.py | 1,068 | 4.1875 | 4 | '''
decorator are basically functions which alter the behaviour/wrap the origonal functions and use the original functions
output to add other behavious to it
'''
def add20ToaddFn(inp):
def addval(a,b):
return inp(a,b) + 20
addval.unwrap=inp # this is how you unwrap
return addval
@add20ToaddFn
def addFn(x,y):
return x+y
d = {}
def decorFn(addFn):
def decorInnerFn(a,b):
if (a,b) in d:
print('return from cache')
return d((a,b))
else:
print('return from fn')
d[(a,b)]= addFn(a,b)
return addFn(a,b)
return decorInnerFn
@decorFn
def add(x,y):
return x+y
print(add(7,2))
#print(addFn(2,3),addFn.unwrap(2,3))
#generators
def numberGen(x):
for i in range(x):
yield i
for i in numberGen(5):
print(i)
file="./data.txt"
try:
fileObj=open(file,'r')
except FileNotFoundError:
print('File not found')
else:
i=file.readline()
print(i)
fileObj.close()
finally:
print('The above set of statemnets done with/without erro') | true |
069de02a13505fa4c356308b8ed189446807612c | BondiAnalytics/Python-Course-Labs | /13_list_comprehensions/13_04_fish.py | 333 | 4.25 | 4 | '''
Using a listcomp, create a list from the following tuple that includes
only words ending with *fish.
Tip: Use an if statement in the listcomp
'''
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = list(fish_tuple)
print([i for i in fish_list if i[-4:] == "fish"])
# fishy = []
# for i in fish_tuple:
# | true |
cd318be0b06227fc766e910ea786fb792c02fced | BondiAnalytics/Python-Course-Labs | /14_generators/14_01_generators.py | 245 | 4.375 | 4 | '''
Demonstrate how to create a generator object. Print the object to the console to see what you get.
Then iterate over the generator object and print out each item.
'''
gen = (x**2 for x in range(1,6))
for i in gen:
print(i)
print(gen) | true |
6de2ac2bbde9274df1540b29f9c983a39253bd57 | the-matrixio/ml_competition_didi | /preprocess_data/get_weekday.py | 630 | 4.1875 | 4 | '''
Given absolute time, return weekday as an integer between 0 and 6
Arguments:
Absolute time (integer)
Returns:
Integer between 0 and 6 inclusive. Monday is 0, Sunday is 6.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import calendar
def get_weekday(absolute_time):
# First determine the year, month, day
# NOTE: Below code only works for Jan/Feb 2016, it's not scalable but OK for this competition
year = 2016
month = absolute_time // (144*31) + 1
day = (absolute_time - (144*31) * (month - 1)) // 144 + 1
return calendar.weekday(year, month, day) | true |
77db9841cf16c96919bf770b7f01e9a2e9abd864 | tegamax/ProjectCode | /Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_8/8_11.py | 1,260 | 4.21875 | 4 | '''
8-11. Archived Messages: Start with your work from Exercise 8-10.
Call the function send_messages() with a copy of the list of messages.
After calling the function, print both of your lists to show that the original list has retained its messages.
'''
'''
def send_messages(short_list):
sent_messages = []
current_message = short_list.pop()
sent_messages.append(current_message)
#print(sent_messages)
messages = ['monitor','mouse','laptop','keyboard']
send_messages(messages)
print(messages)
'''
'''
def send_messages(short_list):
sent_messages = []
current_message = short_list.pop()
sent_messages.append(current_message)
return sent_messages
messages = ['monitor', 'mouse', 'laptop', 'keyboard']
#sent_messages = []
#send_messages(messages[:])
print(messages[:])
'''
def show_messages(messages):
print("Printing all messages")
for message in messages:
print(message)
def send_messages(messages,sent_messages):
while messages:
removed_messages = messages.pop()
sent_messages.append(removed_messages)
print(sent_messages)
messages = ['monitor', 'mouse', 'laptop', 'keyboard']
show_messages(messages)
sent_messages = []
send_messages(messages[:], sent_messages)
| true |
4a6aa2ffcf88c2e4a38ce56fab7d316f6d4e0114 | tegamax/ProjectCode | /Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_9/Ex_9_4.py | 1,639 | 4.28125 | 4 | '''
9-4. Number Served: Start with your program from Exercise 9-1 (page 162). Add an attribute called number_served with a default value of 0.
Create an instance called restaurant from this class. Print the number of customers the restaurant has served,
and then change this value and print it again.
Add a method called set_number_served() that lets you set the number of customers that have been served.
Call this method with a new number and print the value again.
Add a method called increment_number_served() that lets you increment the number of customers who’ve been served.
Call this method with any number you like that could represent how many customers were served in, say, a day of business.
'''
class Restaurant:
def __init__(self):
self.number_served=0 #Attribute
def number_of_customers(self): #Method
print(f"The Number of customers served today was {self.number_served}.")
def set_number_served(self):
print(f"We served {self.number_served} clients this week")
def increment_number_served(self,served_customers):
self.number_served += served_customers
return self.number_served
#print(self.number_served)
#print(served_customers) num_of_customers_served
#a,
restaurant = Restaurant() #Instance
#print(restaurant.number_of_customers)
restaurant.number_of_customers()
#b,
restaurant.number_served=23
restaurant.number_of_customers()
restaurant.number_served=90
restaurant.set_number_served()
total=restaurant.increment_number_served(20)
print(f"In total we served {total} customers today") | true |
b2def23578d639e50d6eea882e5b9a8246edb01b | Pajke123/ORS-PA-18-Homework07 | /task2.py | 469 | 4.1875 | 4 |
"""
=================== TASK 2 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def main():
# Test your function here
pass
if __name__ == "__main__":
main()
| true |
077e070ecddeedee387a0a9b9b658262af4eccaf | AMfalme/OOP-python-Furniture-sales | /OOP_file.py | 1,182 | 4.1875 | 4 | from abc import ABCMeta, abstractmethod
class Electronics(object):
"""docstring for Electronics
This is an abstract Base class for a vendor selling Electronics of various types.
"""
__metaclass__ = ABCMeta
def __init__(self, make, year_of_manufacture, sale_date, purchase_price, selling_price, purchase_date):
super(Electronics, self).__init__()
self.make = make
self.year_of_manufacture = year_of_manufacture
self.sale_date = sale_date
self.purchase_price = purchase_price
self.selling_price
def profit_after_sale(self):
profit = self.selling_price - self.purchase_price
return profit
def make(self):
return self.make
@abstractmethod
def type_of_electronic(self):
return self.make
class computer(Electronics):
"""docstring for computer"""
def __init__(self, model):
self.model = model
def type_of_electronic(self):
return "Computer"
def insert_ram_capacity(self):
ram_in_gb = raw_input("What is the ram of this computer")
self.ram = ram_in_gb
return self.ram
def Insert_processor_capacity(self):
processor = raw_input("kindly input the processor capacity on this computer")
laptop = computer("HP")
print(laptop.make)
| true |
61123681d1a35d9a00b4cfba76103fc78ca105e5 | dionysus/coding_challenge | /leetcode/088_MergeSortedArray.py | 1,297 | 4.1875 | 4 | '''
88. Merge Sorted Array
URL: https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2,
merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold
additional elements from nums2.
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
'''
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
'''
two index
'''
if n == 0:
return nums1
i = 0
j = 0
# while nums1 has elements larger than nums2
while i < m and j < n:
if nums1[i] > nums2[j]:
nums1[i+1:] = nums1[i:m]
nums1[i] = nums2[j]
j += 1
m += 1
i += 1
# copy rest of nums2
if j < n:
nums1[i:] = nums2[j:]
if __name__ == "__main__":
# nums1 = [1,2,3,0,0,0]
# m = 3
# nums2 = [2,5,6]
# n = 3
nums1 = [2,0]
m = 1
nums2 = [1]
n = 1
nums1 = [4,5,6,0,0,0]
m = 3
nums2 = [1,2,3]
n = 3
test = Solution()
test.merge(nums1, m, nums2, n)
print(nums1) | true |
05d0485e40117cf2b4e8063942e6cb4154569ac6 | MankaranSingh/Algorithms-for-Automated-Driving | /code/exercises/control/get_target_point.py | 981 | 4.125 | 4 |
import numpy as np
def get_target_point(lookahead, polyline):
""" Determines the target point for the pure pursuit controller
Parameters
----------
lookahead : float
The target point is on a circle of radius `lookahead`
The circle's center is (0,0)
poyline: array_like, shape (M,2)
A list of 2d points that defines a polyline.
Returns:
--------
target_point: numpy array, shape (,2)
Point with positive x-coordinate where the circle of radius `lookahead`
and the polyline intersect.
Return None if there is no such point.
If there are multiple such points, return the one that the polyline
visits first.
"""
# Hint: A polyline is a list of line segments.
# The formulas for the intersection of a line segment and a circle are given
# here https://mathworld.wolfram.com/Circle-LineIntersection.html
raise NotImplementedError | true |
5a129e2a8a4dd86d3d295899ff3cf8e015afd5fb | calvinstudebaker/ssc-scheduling | /src/core/constants.py | 2,840 | 4.28125 | 4 | """Hold values for all of the constants for the project."""
class Constants():
"""This is a class for managing constants in the project."""
STRINGS = {}
@classmethod
def get_string(cls, val, dictionary=None):
"""Get the string representation of the given constant val.
Looks in the subclass's dictionary called STRINGS. If there is none,
returns the empty string.
Parameters
----------
cls: class
Name of the class in this file
val: string
value to retrieve
dictionary: dictionary
dictionary to use. default is cls.STRINGS
Returns the value from the dictionary.
"""
if not dictionary:
dictionary = cls.STRINGS
if val in dictionary:
return dictionary[val]
return ""
@classmethod
def string_to_val(cls, string_rep):
"""Find which constant value the STRING_REP is associated with.
Given a string STRING_REP, find which constant value
it is associated with.
Parameters
----------
cls: class
Name of the class in this file
string_rep: string
String representation of the constant value to look up
Returns int.
"""
for pair in cls.STRINGS.iteritems():
const = pair[0]
string = pair[1]
if string == string_rep:
return const
return -1
class Days(Constants):
"""Constants for days of the week."""
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
STRINGS = {}
STRINGS[SUNDAY] = "Sunday"
STRINGS[MONDAY] = "Monday"
STRINGS[TUESDAY] = "Tuesday"
STRINGS[WEDNESDAY] = "Wednesday"
STRINGS[THURSDAY] = "Thursday"
STRINGS[FRIDAY] = "Friday"
STRINGS[SATURDAY] = "Saturday"
class Jobs(Constants):
"""Constants for the different possible jobs."""
MUNCHKINS = 0
SNOOPERS = 1
MENEHUNES = 2
YAHOOS = 3
MIDOREES = 4
SUAVES = 5
TEENS = 6
SKI_DOCK = 7
TENNIS = 8
HIKING = 9
OFFICE = 10
CRAFTS = 11
ART = 12
PHOTO = 13
KIDS_NAT = 14
ADULT_NAT = 15
THEATER = 16
MUSIC = 17
KGC = 18
STAPH_D = 19
STRINGS = {}
STRINGS[MUNCHKINS] = "Munchkins"
STRINGS[SNOOPERS] = "Snoopers"
STRINGS[MENEHUNES] = "Menehunes"
STRINGS[YAHOOS] = "Yahoos"
STRINGS[MIDOREES] = "Midorees"
STRINGS[SUAVES] = "Suaves"
STRINGS[TEENS] = "Teens"
STRINGS[SKI_DOCK] = "Ski Dock"
STRINGS[TENNIS] = "Tennis"
STRINGS[HIKING] = "Hiking"
STRINGS[OFFICE] = "Office"
STRINGS[CRAFTS] = "Crafts"
STRINGS[ART] = "Art"
STRINGS[PHOTO] = "Photo"
STRINGS[KIDS_NAT] = "Kids Naturalist"
STRINGS[ADULT_NAT] = "Adult Naturalist"
STRINGS[THEATER] = "Theater"
STRINGS[MUSIC] = "Music Director"
STRINGS[KGC] = "Kids Group Coordinator"
STRINGS[STAPH_D] = "Staph Director"
class ShiftCategory(Constants):
"""Constants for the different types of shifts."""
SPECIAL = 0
OFF_DAY = 1
PROGRAMMING = 2
STRINGS = {}
STRINGS[SPECIAL] = "Special"
STRINGS[OFF_DAY] = "Off Day"
STRINGS[PROGRAMMING] = "Programming"
| true |
a6da2062585d75edf9643bdac2f9df4619211327 | vijaypatha/python_sandbox | /numpie_mani.py | 2,173 | 4.375 | 4 | '''
pretty simple:
1) Create a array
2) Manipylate the arary: Accessing, deleting, inserting, slicing etc
'''
#!/usr/bin/env python
# coding: utf-8
# In[10]:
import numpy as np
#Step 1: Create a array
x = np.arange(5,55,5).reshape(2,5)
print("Array X is:")
print(x)
print("Attrubute of Array X is:")
print("# of axis of x: ", x.ndim)
print("# row and columns in X:", x.shape)
print("Data type of X:",x.dtype)
print("# of elements in the array X:", x.size)
# In[11]:
#Step 2: Access a element in the array
x[1,3] #expecting 2 row, 4th colum element -> 45
print(x[1,3])
# In[12]:
#Step 3: Changing 45 to 95
x[1,3] = 95
print(x)
# In[13]:
#Step 4: Changing 95 to 45
x[1,3] = 45
print(x)
# In[32]:
#Step 5: delete something along Axis 1
print("array x is: ")
print(x)
y = np.delete(x,[1,3],1) # deleting array's index 1 and 3 along the axis 1 -> a columnwise opreation
print("modified x after deleting index [0,4] along axis 1 is:")
print(y)
# In[33]:
#Step 5: delete something along Axis 1
print("array x is: ")
print(x)
z = np.delete(x,[0,4]) # deleting array's index 1 and 3 along the axis 0 -> a rowwise operation
print("modified x after deleting index [0,4] is",z)
# In[38]:
print("z = ", z)
t = np.delete(z, [0,2], axis=0)
print("modifed z =",t)
# In[45]:
# Step 6: Appending rows and columns
print("y", y)
print("appended new column:")
print(np.append(y, [[55],[60]], axis = 1)) #notice the difference between appending a row vs. Column.
#The new rows and columns match the shapes arrays
# In[49]:
print("y", y)
print("appended new row:")
print(np.append(y, [[55,60,65]], axis = 0)) #notice the difference between appending a row vs. Column.
#The new rows and columns match the shapes arrays
# In[ ]:
# Step 7: Inserting rows and colummns np.insert(ndarray, index, elements, axis)
print("y array is",y)
w = np.insert(y, 2, [55,60,65],axis = 0)
print ("Inserted Y array is:")
print(w)
print("y array is")
print(y)
w = np.insert(y, 3, [[55],[60],[65]],axis = 1)
print ("Inserted Y array is:")
print(w)
# STep 8: Vstack and Hstack
print("y array is")
print(y)
w = np.hstack(y)
print ("hstacked Y array is:")
print(w) | true |
86f2268590847d4f99e6899e8049b7a2abe72ac4 | anjalak/Code-Archive | /Python_Code/python code/bitOperator.py | 892 | 4.21875 | 4 | # Create a function in Python called bitOperator that takes two bit strings of length 5 from the user.
# The function should return a tuple of the bitwise OR string, and the bitwise AND string
# (they need not be formatted to a certain length, see examples).
def bitOperator(int1, int2):
num1 = int(int1,2);
num2 = int(int2,2);
str1 = format(num1|num2,'b');
str2 = format(num1&num2,'b');
ans = (str1,str2);
return ans;
# Test cases
# 1.
# result = bitOperator('01001','00100')
# possible_solution_1 = ('1101', '0')
# possible_solution_2 = ('01101', '00000')
# print (result==possible_solution_1 or result==possible_solution_2)
# True
# 2.
# result = bitOperator('10001', '11011')
# solution = ('11011', '10001')
# print (result==solution)
# True
# 3.
# result = bitOperator('11001', '11100')
# solution = ('11101', '11000')
# print (result==solution)
# True
| true |
8782817b87ac1f819b078b3c773778f2c72a93ee | davide-coccomini/Algorithmic-problems | /Python/steps.py | 988 | 4.15625 | 4 | # Given the number of the steps of a stair you have to write a function which returns the number of ways you can go from the bottom to the top
# You can only take a number of steps based on a set given to the function.
# EXAMPLE:
# With N=2 and X={1,2} you can go to the top using 2 steps or you can use a single step (valued 2) so return 2
# Easy example with constant X
# def numWays(n):
# if n== 0 or n == 1:
# return 1
# else:
# return numWays(n-1) + numWays(n-2)
# We can notify that the result of the N case is the result of the sum of the 2 previosly results
# N output
# 0 1
# 1 1
# 2 2
# 3 3
# 4 5
# ...
# So we can just remember the previously 2 results and sum them
def numWays(n, x):
if n == 0 or n == 1:
return 1
nums = n+1 * [0]
nums[0] = 1
for i in range(1, n):
total = 0
for j in x:
total += nums[i - j]
nums[i] = total
return nums[n]
# Asked by Amazon | true |
b3080fe028e3a62ade5b64a57da7ce9276c650ae | niksm7/March-LeetCoding-Challenge2021 | /Palindromic Substrings.py | 622 | 4.15625 | 4 | '''
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
'''
class Solution:
def countSubstrings(self, s: str) -> int:
@lru_cache(None)
def ispalindrome(i, j):
if i >= j: return True
return s[i] == s[j] and ispalindrome(i+1, j-1)
return sum(ispalindrome(i, j) for i in range(len(s)) for j in range(i, len(s))) | true |
77de892bfce5df9d0d5c9bad7cde7b401e1ba38e | TheDarkKnight1939/FirstYearPython | /3.py | 539 | 4.28125 | 4 | #!/usr/bin/python
import random #Imports the class random
r=random.randint(10,66) #Uses the randint function to choose a number from 10 to 66
print(r) #Prints the random number choosen
if r<35: #If loop which checks if the number is lesser than 35
print(r)
print(": is less than 35 \n")
exit
elif r==30:#If loop which checks if the number is equal to 30
print(" 30 is multiple of 10 and 3, both ")
elif r>=35:#If loop which checks if the number is lesser than 35
print(r, " is greater than 35")
else:
print("your number is : ", r)
| true |
aad35df15da4265e65defc8f609290a342e727f3 | gaurav-singh-au16/Online-Judges | /Binary_Search_Problems/nth_fibonacci_no.py | 916 | 4.1875 | 4 | """
Nth Fibonacci Number
The Fibonacci sequence goes like this: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number can be found by adding up the two numbers before it, and the first two numbers are always 1.
Write a function that takes an integer n and returns the nth Fibonacci number in the sequence.
Constraints
n ≤ 30
Example 1
Input
n = 1
Output
1
Explanation
This is the base case and the first fibonacci number is defined as 1.
Example 2
Input
n = 6
Output
8
Explanation
Since 8 is the 6th fibonacci number: 1, 1, 2, 3, 5, 8.
Example 3
Input
n = 7
Output
13
Explanation
Since 13 is the seventh number: 1, 1, 2, 3, 5, 8, 13
Solved
2,779
Attempted
3,007
Rate
92.42%
"""
def solve(n):
dp = [0]* 10
dp[0] = 0
dp[1] = 1
for i in range(n+1):
if i !=0 and i !=1:
dp[i] = dp[i-2]+dp[i-1]
return dp[n]
if __name__ == "__main__":
n = 3
print(solve(n))
| true |
86a7c2270c42fdd3e898d027dac3f0c63d07fbc8 | gaurav-singh-au16/Online-Judges | /Leet_Code_problems/69. Sqrt(x).py | 543 | 4.15625 | 4 | """
69. Sqrt(x)
Easy
1657
2143
Add to List
Share
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
Constraints:
0 <= x <= 231 - 1
"""
class Solution:
def mySqrt(x):
return int(x**(1/2))
| true |
d5fee0cdc323a6feca2f3b7cf95cc59f909bbfab | tsakaloss/pycalculator | /calculator.py | 2,930 | 4.375 | 4 | import sys
from lib import operations
# Manage the operations
def mathing_func(a, b, sign):
if sign == '+':
return operations.Calculations.plus(a, b)
elif sign == '-':
return operations.Calculations.minus(a, b)
elif sign == '*':
return operations.Calculations.multiply(a, b)
elif sign == '/':
return operations.Calculations.divine(a, b)
else:
print("Wrong sign detected.")
sys.exit(1)
def calculator():
try:
while True:
sign_position_counter = 0
position_list_counter = 0
numbers_listed = []
signs_only = []
counter = 1 # For the text to input third+ sign or = for result
# Get first user's input.
start_quit = input(
'Type \'start\' to start using this calculator or type close to quit: ')
if start_quit == 'close':
sys.exit(0)
if start_quit == 'start':
while True:
number_for_list = float(
input('Enter a number of your choice: '))
numbers_listed.insert(
position_list_counter, number_for_list)
position_list_counter += 1
if counter == 1:
sign_for_operation = input(
'Enter one of the following: + - * or / : ')
signs_only.insert(sign_position_counter,
sign_for_operation)
counter += 1
position_list_counter += 1
sign_position_counter += 1
else:
# Can later add it with '+' at the end of the string after one run
sign_for_operation = input(
'Enter one of the following: + - * / OR = to do the math : ')
if sign_for_operation == '=':
amount = len(numbers_listed)
amount -= 1
for i in range(amount):
result = mathing_func(
numbers_listed[i], numbers_listed[i + 1], signs_only[i])
numbers_listed.remove(numbers_listed[i + 1])
numbers_listed.insert(i + 1, result)
print("The result is: ", result)
break
else:
signs_only.insert(
sign_position_counter, sign_for_operation)
sign_position_counter += 1
except KeyboardInterrupt:
print("\nExiting...")
sys.exit(0) # gracefull exit.
if __name__ == '__main__':
# Run calculator.
calculator()
| true |
0c3925c9dfd8736a0f5836d2139fdf6d6a259a70 | lightdarkx/python-snippets | /LinearSearch.py | 513 | 4.28125 | 4 | # Program to implement linear search in a given array/list
def linearSearch(arr,search_item):
print(f"search_item: {search_item}")
for i in arr:
if (i == search_item):
return -2,i
#print(f"i: {i}")
return -1,-1
arr = [1,2,3,4,5]
search_item = 4
ans,position = linearSearch(arr, search_item)
#print(f"ans: {ans}")
if ans == -1:
print("Item not in array")
elif ans == -2:
print(f"Item is in array at position: {position}")
| true |
e9a6d1c8de9290cf452f81f35df46f9ab2f9e48a | Meeds122/Grokking-Algorthms | /4-quicksort/quicksort.py | 1,280 | 4.21875 | 4 | #!/usr/bin/python3
def quickSort(arr):
working_array = arr.copy()
working_array_length = len(working_array)
if working_array_length <= 1:
# Empty element or single element case
return working_array
elif working_array_length == 2:
# only 2 elements case
if working_array[0] <= working_array[1]:
# already sorted
return working_array
else:
# sort array
return [working_array[1], working_array[0]]
else:
# more than 2 elements
# select the last element as the pivot
pivot = [working_array[working_array_length - 1]]
less_array = []
greater_array = []
for i in range(working_array_length - 1):
if working_array[i] > pivot[0]:
greater_array.append(working_array[i])
if working_array[i] <= pivot[0]:
less_array.append(working_array[i])
return quickSort(less_array) + pivot + quickSort(greater_array)
def testing():
import random
test_array = []
for i in range(random.randint(1,20)):
test_array.append(random.randint(1,30))
print("Unsorted array:")
print(test_array)
print("Sorted array:")
print(quickSort(test_array))
testing() | true |
def9cd930313f4fe0e6f5219f51e25e31ff04788 | andrewswellie/Python_Rock_Paper_Scissors | /RockPaperScissors.py | 1,537 | 4.15625 | 4 | # Incorporate the random library
import random
restart = 1
while restart != "x":
print("Let's Play Rock Paper Scissors!!!")
options = ["r", "p", "s"]
computer_choice = random.choice(options)
user_choice = input("You are playing against the computer. His choice is completely random. Make your Choice: (r)ock, (p)aper, (s)cissors? ")
if (user_choice == "r") and (computer_choice == "p"):
print("You Lose.")
restart = input("press any key to start again, or x to exit.")
elif (user_choice == "p") and (computer_choice == "s"):
print("You Lose.")
restart = input("press any key to start again, or x to exit.")
elif (user_choice == "s") and (computer_choice == "r"):
print("You Lose.")
restart = input("press any key to start again, or x to exit.")
if (user_choice == "s") and (computer_choice == "p"):
print("You WIN!!!")
restart = input("press any key to start again, or x to exit.")
elif (user_choice == "r") and (computer_choice == "s"):
print("You WIN!!!")
restart = input("press any key to start again, or x to exit.")
elif(user_choice == "p") and (computer_choice == "r"):
print("You WIN!!!")
restart = input("press any key to start again, or x to exit.")
if (user_choice == computer_choice):
print("TIE! Kind of like kissing your sister. Try again.")
restart = input("press any key to start again, or x to exit.")
| true |
368ec147cd5f547160e88580a4c11783f2f79f98 | pani-vishal/String-Manipulation-in-Python | /Problem 7.txt | 221 | 4.21875 | 4 | #Program to count no. of letters in a sentence/word
sent=input("Enter a sentence: ")
sent=sent.lower()
count=0
for x in sent:
if (x>='a' and x<='z'):
count+=1
print("Number of letters: "+str(count))
| true |
f91a700285537cbbd9f51fb70d8d7ae0559d1709 | jeremymatt/DS2FP | /drop_illogical.py | 713 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 22:59:05 2019
@author: jmatt
"""
def drop_illogical(df,var1,var2):
"""
Drops records from the dataframe df is var1 is greater than var2
For example, if var1 is spending on clothing and var2 is total income
it is not logical that var1 is greater than var2
"""
#Mask the illogical entries
mask = df[var1]>df[var2]
#Record the number of entries
NumRecords = df.shape[0]
#drop the illogical entries
df = df[df.keys()][~mask]
#Notify the user how many records were dropped
print('{} records dropped because {} is greater than {}'.format(NumRecords-df.shape[0],var1,var2))
return df
| true |
051d08ec216fff8651d3a096578c7fa38ba875ed | CLAHRCWessex/math6005-python | /Labs/wk1/if_statement_preview.py | 1,884 | 4.6875 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Week 1 Extra Material: If-then statements
A short look ahead at conditionals and if statements.
We will cover these in detail in week 2. But feel free to have edit the code
below to see how it works.
In most Python programmes that you write you will be using if-then statements.
These allow you to make conditional choices in your code.
To use if-then statements you need to understand
a.) boolean comparisons e.g. x > 1
b.) if, elif and else statements
c.) Python whitespace and indentation rules
@author: tom
"""
#%%
# =============================================================================
# Boolean comparisons - return True or False
# =============================================================================
foo = 2
bar = 'spam'
print('is foo equal to 2?: {0}'.format(foo == 2))
print('is foo less than or equal to 5?: {0}'.format(foo <= 5))
print('is foo greater than or 100?: {0}'.format(foo > 5))
print("is bar equal to 'eggs': {0}".format(bar == 'eggs'))
print("is bar the same type as foo?: {0}".format(type(bar) == type(foo)))
#%%
# =============================================================================
# We use boolean comparisons in 'if' statements
# =============================================================================
foo = 100 # why not try changing the value of foo to 10, 'bar' and 'eric'
if foo == 100:
#notice that the print statement is indented.
#This is mandatory in python. Otherise you get an error!
print("Hello! You branched here, because foo == 100 evaluated to 'True'")
elif foo == 10:
print("Hello again, you branched here because foo equals 10 this time")
elif foo == 'bar':
print("Gosh, hello. This time foo looked a bit different!")
else:
print("So foo didn't equal any of the above. I am the default branch")
#%%
| true |
c7d99b39a0557d62a59e5607c9620f2bcfcab248 | eshanmherath/neural-networks | /perceptron/simple_perceptron_OR_gate.py | 2,098 | 4.15625 | 4 | import numpy as np
class Perceptron:
def __init__(self, number_of_inputs, learning_rate):
self.weights = np.random.rand(1, number_of_inputs + 1)[0]
self.learning_rate = learning_rate
"""A step function where non-negative values are returned by a 1 and negative values are returned by a -1"""
def activate(self, z):
if z >= 0:
return 1
else:
return -1
def feed_forward(self, input_values):
inputs = np.array([
input_values[0], input_values[1], -1
])
z = inputs.dot(self.weights.transpose())
return self.activate(z)
def update_weights(self, actual_x, error):
x = np.array([
actual_x[0], actual_x[1], -1
])
self.weights += self.learning_rate*error*x
"""
Below code simulates a perceptron learning to act as an OR gate.
(-1) represents 0
(+1) represents 1
"""
if __name__ == "__main__":
print("\nPerceptron learning the OR gate functionality\n")
np.random.seed(1111)
perceptron = Perceptron(2, 0.01)
training_x = np.array([[-1, -1], [-1, 1], [1, -1], [1, 1]])
training_y = np.array([[-1], [1], [1], [1]])
for epoch in range(25):
total_error = 0
for example in range(len(training_x)):
y_predicted = perceptron.feed_forward(training_x[example])
y_expected = training_y[example][0]
error = y_expected - y_predicted
total_error += error
perceptron.update_weights(training_x[example], error)
print("epoch " + str(epoch) + " Total Error " + str(total_error))
if total_error == 0:
break
print("Final Weights : " + str(perceptron.weights))
"Testing final weights"
print("\nTesting final weights")
print('Input [-1, -1] Output ' + str(perceptron.feed_forward([-1, -1])))
print('Input [-1, +1] Output ' + str(perceptron.feed_forward([-1, +1])))
print('Input [+1, -1] Output ' + str(perceptron.feed_forward([+1, -1])))
print('Input [+1, +1] Output ' + str(perceptron.feed_forward([+1, +1])))
| true |
e347dab6cada8dfd16b370d9f40f3b590b949a2e | tvocoder/learning_python | /python_functional_programming.py | 1,191 | 4.59375 | 5 | # Functional Programming
print("---= Functional Programming =---")
print("--= Map =--")
# Description: Applies function to every item of an iterable and returns a list of the results.
# Syntax: map(function,iterable[,...])
# -- function: Required. A function that is used to create a new list.
# -- iterable: Required. An iterable object or multiple comma-seperated iterable objects.
# Return Value: list
# Remarks: If additional iterable arguments are passed, function must take that many arguments and is applied
# -- to the items from all iterables in parallel.
# If one iterable shorter than another it is assumed to be extended with None items.
# If function is None, the identity function is assumed; if there are multiple arguments,
# -- map() returns a list consisting of tuples containing the corresponding items from all iterables.
# The iterable arguments may be a sequence or any iterable object; the result is always a list.
# Example:
l = map(lambda x, y, z: x+y+z, [1, 2, 3], [4, 5, 6], [7, 8, 9])
print(list(l))
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
l = map(lambda x : x + x, numbers)
print(list(l)) | true |
304598e5e382fad84021f4a95d5a395b957a4456 | tvocoder/learning_python | /python_callable_func.py | 2,317 | 4.5 | 4 | print("---= Callables Operators =---")
print("-- *(tuple packing) --")
# Description: Packs the consecutive function positional arguments into a tuple.
# Syntax: def function(*tuple):
# -- tuple: A tuple object used for storing the passed in arguments.
# All the arguments can be accessed within the function body the same way as with any other tuple.
# Remarks: The tuple name *args is used by convention.
# Example:
def add(*args):
total = 0
for arg in args:
total += arg
return total
x = add(1, 2, 3)
print(x)
print("*************************")
print("-- **(dictionary packing) --")
# Definition: Packs the consecutive function keyword arguments into a dictionary.
# Syntax: def function(**dict):
# -- dict: A dictionary object used for storing the passed in arguments.
# All the arguments can be accessed within the function body with the same way as with any other dictionary.
# Remarks: The dict name **kwargs is used by convention.
# Example:
def example(**kwargs):
return kwargs.keys()
d = example(a = 1, b = 20, c = [10, 20, 30])
print(d)
print("*************************")
print("-- *(tuple unpacking) --")
# Definition: Unpacks the contents of a tuple into the function call
# Syntax: function(*iterable)
# Remarks:
# Example:
def add(a, b):
return a + b
t = (2 ,3)
print(add(*t))
print(add(*"AD"))
print(add(*{1: 1, 2: 2}))
print("*************************")
print("-- **(dictionary unpacking) --")
# Definition: Unpacks the contents of a dictionary into a function call
# Syntax: function(**dict)
# -- dict: The dictionary containing pairs of keyword arguments and their values.
# Remarks:
# Example:
def add(a=0, b=0):
return a + b
d = {'a': 2, 'b': 3}
print(add(**d))
print("*************************")
print("-- @(decorator) --")
# Definition: Returns a callable wrapped by another callable.
# Syntax: @decorator
# def function():
# decorator: A callable that takes another callable as an argument.
# Remarks:
# Decorator Syntax:
def decorator(f):
pass
@decorator
def function():
pass
# Is equivalent to:
def function():
pass
function = decorator(function)
# Example:
print("*************************")
print(" -- ()(call operator --")
# Definition:
# Syntax:
# Remarks:
# Example:
print("*************************")
| true |
2690b3fb0d1b3339f9b29f8c5c81638c0eefb682 | Python-aryan/Hacktoberfest2020 | /Python/sum of list-elements.py | 287 | 4.25 | 4 | #Calculates the sum of a list of numbers
number = int(input("Enter number of elements: "))
elements = []
for i in range(number):
x = int(input("Enter {} number: ".format(i+1)))
elements.append(x)
sum=0
for i in elements:
sum=sum+i
print("Sum of the list elements is: ",sum)
| true |
bb62b6e47c6d5606a253690c003d9b72b6aea79e | docljn/python-self-study | /wesleyan_intro/module_3/name_phone.py | 925 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 15:48:51 2018
@author: DocLJN
"""
import sys
import csv
# open the csv file here
filename = sys.argv[1]
file = open(filename, 'w')
while True:
nextname = input("Enter a friend's name, press return to end: ")
if nextname == "":
break # break jumps out of the loop
nextphone = input("Enter the friend's phone number: ")
print(nextname)
print(nextphone)
option = input("Is this correct? y/n ")
if option == 'y':
entry = [nextname, nextphone]
csv.writer(file).writerow(entry)
print('Added',nextname, nextphone)
else:
print('Next: ')
# add lines here to build a row (that is, a list) and append these
# two pieces of data to it. Write to the csv file
# don't forget to close the csv file
file.close()
| true |
4585d9c998c7312a8a2541259970987d700b45ab | Scorch116/PythonProject---Simple-calculator | /Calculator.py | 1,261 | 4.25 | 4 | '''Simple calculator used to perform basic calculator functions such as addition,
subtraction,division and multplication'''
def Addition(value1, value2): # this function will add the two numbers
return value1 + value2
def subtract (value1, value2):
return value1 - value2
def Divide(value1, value2):
return value1 / value2
def multiply(value1,value2):
return value1 * value2
#print statement for selecting function
print("please selection function \n > Add \n > Subtract \n > Divide \n > Multiply")
#Input form the user to select function
FunctionInput = input("Enter option :")
Num1 = int(input("Please enter the first number: "))
Num2 = int(input("PLease enter the second number: "))
# If statement done to select function and read in values
if FunctionInput == "Add":
print("The answer is ",Addition( Num1, Num2))
elif FunctionInput == "Subtract":
print("The answer is ",subtract( Num1, Num2))
elif FunctionInput == "Divide":
print("The answer is ",Divide( Num1, Num2))
elif FunctionInput == "Multipy":
print("The answer is ",multiply( Num1, Num2))
else:
print("Error, PLease try again")
#else statement with print error - incase something gose wrong you know its working
#better that and actual error
| true |
d6374434fb6c9d67a684c3db37d6bc34e7701fd9 | abhinavmittal93/Week1_Circle_Radius | /Week1_coding.py | 320 | 4.1875 | 4 | import math
import datetime
def calc_radius():
radius = float(input('Enter the radius of the circle: '))
area = math.pi * radius**2
print(f'Area of the circle is: {area:.2f}')
def print_date_time():
time = datetime.datetime.now()
print(f'Today\'s date: {time}')
print_date_time()
calc_radius()
| true |
9b31816c42dc2107fdbe3af38c21992213168768 | danel2005/triple-of-da-centry | /Aviel/8.3.3.py | 675 | 4.3125 | 4 | def count_chars(my_str):
"""
returns a dict that the keys are the letters and the valus are how many of them were in the string
:param my_str: the string we want to count every letter
:type my_str: str
:return: a dict that the keys are the letters and the valus are how many of them were in the string
:rtype: dict
"""
dict = {}
my_list = list(my_str.replace(" ", ""))
for letter in my_list:
if letter in dict.keys():
dict[letter] += 1
else:
dict[letter] = 1
return dict
def main():
magic_str = "abra cadabra"
print(count_chars(magic_str))
if __name__ == "__main__":
main() | true |
1c6125e33f932902b101c449ffd44c5236788bc0 | danel2005/triple-of-da-centry | /Aviel/6.4.2.py | 876 | 4.15625 | 4 | def try_update_letter_guessed(letter_guessed, old_letters_guessed):
"""
Adds the letter guessed to the array of letters that has already been guessed
:param letter_guessed: the guess that the user inputing
:param old_letters_guessed: all the letters the user already guessed
:type letter_guessed: string
:type old_letters_guessed: array
:return: true or false, the letter is valid or not and if its already been guessed
:rtype: bool
"""
if len(letter_guessed) >= 2 or not (letter_guessed >= "a" and letter_guessed <= "z" or letter_guessed >= "A" and letter_guessed <= "Z") or (letter_guessed.lower() in old_letters_guessed):
old_letters_guessed_str = ' -> '.join(sorted(old_letters_guessed))
print("X")
print(old_letters_guessed_str)
return False
old_letters_guessed += letter_guessed
return True | true |
2c772ed45516775c12da8c4ae9ba0d6330ab5105 | danel2005/triple-of-da-centry | /Aviel/6.4.1.py | 651 | 4.1875 | 4 | def check_valid_input(letter_guessed, old_letters_guessed):
"""
Checks if the guess is valid or not
:param letter_guessed: the guess that the user inputing
:param old_letters_guessed: all the letters the user already guessed
:type letter_guessed: string
:type old_letters_guessed: array
:return: true or false, the letter is valid or not and if its already been guessed
:rtype: bool
"""
if len(letter_guessed) >= 2 or not (letter_guessed >= "a" and letter_guessed <= "z" or letter_guessed >= "A" and letter_guessed <= "Z") or (letter_guessed.lower() in old_letters_guessed):
return False
return True | true |
c889e0e9d7f44f7c13658bfeaebdb60e6ffaea8c | danel2005/triple-of-da-centry | /Aviel/7.2.2.py | 677 | 4.28125 | 4 | def numbers_letters_count(my_str):
"""
returns a list that the first number is the numbers count and the second number is the letters count
:param my_str: the string we want to check
:type my_str: str
:return: list that the first number is the numbers count and the second number is the letters count
:rtype: list
"""
count_letters = 0
count_nums = 0
for letter in my_str:
if letter >= "0" and letter <= "9":
count_nums += 1
else:
count_letters += 1
return [count_nums, count_letters]
def main():
print(numbers_letters_count("Python 3.6.3"))
if __name__ == "__main__":
main() | true |
76cde6d34c1a99e235e6c828c1aa0495810947ec | mossi1mj/SentenceValidator | /SentenceValidator.py | 882 | 4.21875 | 4 | import string
# take in sentence as variable
sentence = input("Enter a sentence: ")
# take words in sentence and place in array[] with split() function
word = sentence.split()[0] # first word in array will be 0
capitalWord = word.capitalize() # capitalize() function puts first character of a string to uppercase
# check for capital letter in first word in sentence
if word != capitalWord:
print("This sentence does not begin with a capital letter.")
# make the first word with a capital letter with replace() function
sentence = sentence.replace(word, capitalWord)
# check for punctuation mark at the end of sentence
if not sentence[-1] in string.punctuation: # -1 is the last element in array using the punctuation() function
print("This sentence does end with punctuation.")
# add punctuation to sentence
sentence = sentence + '.'
print(sentence)
| true |
e9cf929eb3f418b403cbebf5b171db97ef597d76 | alejogonza/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 316 | 4.125 | 4 | #!/usr/bin/python3
"""
1-my_list
"""
class MyList(list):
"""
prints to stdout list in order
"""
def print_sorted(self):
"""
prints the list
"""
sorted_list = MyList()
for item in self:
sorted_list.append(item)
print(sorted(sorted_list))
| true |
9ef602b0e1df3f4111037ecd84e1d78d5994fffb | wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python | /myPrograms/Chapter_4_exerciseSolution/ex4_14.py | 903 | 4.21875 | 4 | ######################################################
# 4.14 #
######################################################
rows = 7
for r in range (rows):
for c in range (rows-r):
print ('*', end = ' ')
print()
#####################################################
# end = ' ' means do not print a new line as print
# function automatically prints a new line,adds space
# at the end and next print will be printed after
# this space on the same line..if no end = ' ' then
# the cursor moves to next line on the screen
#####################################################
# Note that print () at the 4th line is necessary
# because it moves the screen to next line..end=' '
# prints a space after every iteration in column
# we have c in range (row-r) because we want to ite-
# rate this (inner loop) loop 7 times first and decr-
#crease gradually
| true |
15f146f69ea979780ba6d2a9610f064e0c327cc8 | wesenu/COP3035-CGS5935-Introduction-to-Programming-Using-Python | /loopExerciseStarter.py | 382 | 4.1875 | 4 | inputPIN = 0
validPIN = False
userPIN = 9999 # for example use only !
inputPIN = int(input("Please enter your PIN -> "))
validPIN = (inputPIN == userPIN)
while not validPIN:
inputPIN = int(input("Please try again. Enter your PIN -> "))
validPIN = (inputPIN == userPIN)
# know complement is true after loop exits
# therefore the PIN entered is valid here
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.