blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
608309973a1b4917b47c610e571f5c14b0fe521b | gurmeetkhehra/python-practice | /list after removing.py | 383 | 4.3125 | 4 | # 7. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
# Go to the editor
# Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
# Expected Output : ['Green', 'White', 'Black']
colors = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
colors.remove('Red')
colors.remove('Pink')
colors.remove('Yellow')
print(colors) | true |
f25df7963a9a9c81d8b28186b223350cf8d9ba87 | wudizhangzhi/leetcode | /medium/merge-two-binary-trees.py | 2,296 | 4.40625 | 4 | # -*- coding:utf8 -*-
"""
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
root = TreeNode(t1.val + t2.val)
root.left = self.mergeTrees(t1.left, t2.left)
root.right = self.mergeTrees(t1.right, t2.right)
return root
else:
return t1 or t2
def print_node(node):
print(node.val)
def _print_node(nodelist):
next_level = []
for node in nodelist:
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
if next_level:
print([i.val for i in next_level])
_print_node(next_level)
else:
return
_print_node([node])
'''
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
'''
if __name__ == '__main__':
t1 = TreeNode(1, left=TreeNode(3,left=TreeNode(5)), right=TreeNode(2))
t2 = TreeNode(2, left=TreeNode(1, right=TreeNode(4)), right=TreeNode(3, right=TreeNode(7)))
sol = Solution()
result = sol.mergeTrees(t1, t2)
print_node(result)
| true |
2c8eea9be7b8b5de96a5c44cf1d3c8e365eda746 | ChrisMatthewLee/Lab-9 | /lab9-70pt.py | 847 | 4.25 | 4 | ############################################
# #
# 70pt #
# #
############################################
# Create a celcius to fahrenheit calculator.
# Multiply by 9, then divide by 5, then add 32 to calculate your answer.
# TODO:
# Ask user for Celcius temperature to convert
# Accept user input
# Calculate fahrenheit
# Output answer
#----------------------------------------------------------------------
#ask
print "Put in the amount of degrees celcius that you would like to convert to fahrenheit"
#define variable
cel = int(raw_input())
#calculate
def fahcalc(cel):
fah = cel * 9
fah = fah / 5
fah = fah + 32
return fah
#Give answer
print "It is " + str(fahcalc(cel)) + " degrees fahrenheit." | true |
93ed0f3ceef0a0fa18cb59080ff6542697db2335 | KyleKing/dash_charts | /dash_charts/equations.py | 2,691 | 4.4375 | 4 | """Equations used in scipy fit calculations."""
import numpy as np
def linear(x_values, factor_a, factor_b):
"""Return result(s) of linear equation with factors of a and b.
`y = a * x + b`
Args:
x_values: single number of list of numbers
factor_a: number, slope
factor_b: number, intercept
Returns:
y_values: as list or single digit
"""
return np.add(
np.multiply(factor_a, x_values),
factor_b,
)
def quadratic(x_values, factor_a, factor_b, factor_c):
"""Return result(s) of quadratic equation with factors of a, b, and c.
`y = a * x^2 + b * x + c`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
factor_c: number
Returns:
y_values: as list or single digit
"""
return np.add(
np.multiply(
factor_a,
np.power(x_values, 2),
),
np.add(
np.multiply(factor_b, x_values),
factor_c,
),
)
def power(x_values, factor_a, factor_b):
"""Return result(s) of quadratic equation with factors of a and b.
`y = a * x^b`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
Returns:
y_values: as list or single digit
"""
return np.multiply(
factor_a,
np.power(
np.array(x_values).astype(float),
factor_b,
),
)
def exponential(x_values, factor_a, factor_b):
"""Return result(s) of exponential equation with factors of a and b.
`y = a * e^(b * x)`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
Returns:
y_values: as list or single digit
"""
return np.multiply(
factor_a,
np.exp(
np.multiply(factor_b, x_values),
),
)
def double_exponential(x_values, factor_a, factor_b, factor_c, factor_d):
"""Return result(s) of a double exponential equation with factors of a, b, c, and d.
`y = a * e^(b * x) - c * e^(d * x)`
Args:
x_values: single number of list of numbers
factor_a: number
factor_b: number
factor_c: number
factor_d: number
Returns:
y_values: as list or single digit
"""
return np.subtract(
np.multiply(
factor_a,
np.exp(
np.multiply(factor_b, x_values),
),
),
np.multiply(
factor_c,
np.exp(
np.multiply(factor_d, x_values),
),
),
)
| true |
6f1d5c730e20841150ac7b491b56cb52d28b221e | zingpython/december | /day_four/Exercise2.py | 1,322 | 4.28125 | 4 |
def intToBinary(number):
#Create empty string to hold the binary number
binary = ""
#To find a binary number divide by 2 untill the number is 0
while number > 0:
#Find the remainder to find the binary digit
remainder = number % 2
#Add the binary digit to the left of the current binary number
binary = str(remainder) + binary
#Divide the number by 2 using integer division
number = number // 2
# print(number)
#Return the completed binary number
return binary
print( intToBinary(210) )
def binaryToInt(binary):
# #Reverse the string so we can use a for loop going forwards instead of backwards
# binary = binary[::-1]
# #Create a total variable that will hold the total of the binary number
# total = 0
# #Create a variable that holds how much to increase the total by on a "1"
# increase = 1
# #FOr each digit in the binary number
# for digit in binary:
# #If the digit is a "1" increase the total by increase
# if digit == "1":
# total = total + increase
# #As the last step in the for loop double increase
# increase = increase * 2
# #Return the total of the binary number
# return total
binary = binary[::-1]
total = 0
for index in range( len(binary) ):
if binary[index] == "1":
total = total + (2 ** index)
return total
print( binaryToInt("11010010") ) | true |
8cb15496c6ef28903d1ea910ab0abb964522d3d9 | missbanks/pythoncodes | /21062018.py | 359 | 4.125 | 4 | # TASK
# print(51 % 48)
name = input ("Hi what is your name")
add_time = 51
current_time = int(input("What is your current time"))
alarm_time = 5
extra_time = 3
if current_time == "2pm":
print("your alarm will go off at 5pm you have {} extra hours to go".format(extra_time))
else:
print("sorry you entered the wrong time, try again ")
# ASSIGNMENT
| true |
75e03f156082c03a2170993e90c2507dff58721a | ge01/StartingOut | /Python/chapter_03/programming_exercises/pe_0301/pe_0301/pe_0301.py | 1,107 | 4.65625 | 5 | #########################################################
# Kilometer Converter #
# This program asks the user to enter a distance in #
# kilometers, and then converts that distance to miles. #
# The conversion formula is as follows: #
# Miles = Kilometers * 0.6214 #
#########################################################
CONSTANT = 0.6214
def main():
# Display the intro screen.
intro()
# Get the distance in kilometers.
kilometers = float(input('Enter the distance in kilometers: '))
# Convert the kilometers to miles.
kilometers_to_miles(kilometers)
# The intro function displays an introductory screen.
def intro():
print('This program converts distance to miles.')
print('')
# The kilometers_to_miles function accepts a number in
# kilometers and displays the equivalent number in miles.
def kilometers_to_miles(kilos):
miles = kilos * CONSTANT
print('That converts to', \
format(miles, '.2f'), \
'miles. \n')
# Call the main function
main() | true |
abdd052b5d57d6181e0d12a28283889354f045e5 | jjsanabriam/JulianSanabria | /Taller_1/palindromo.py | 410 | 4.4375 | 4 | '''It reads a word and it validates if word is a palindrome
Args:
PALABRA (string): word to validate
Returns (print):
resultado (string): Result of validate word (False or True)
+ word validate
'''
print("Ingrese Palabra: ")
PALABRA = input()
PALABRA_MAYUSCULA = PALABRA.upper()
if PALABRA_MAYUSCULA != PALABRA_MAYUSCULA[::-1]:
print("False " + PALABRA)
else:
print("True " + PALABRA)
| true |
facc0ddf980a825b8587cc05e4caf70ff85415b8 | bdllhdrss3/fizzbuzz | /fizzbuzz.py | 556 | 4.1875 | 4 | #making a fizz buzz app
#creating input of list
list1 = input("Enter list one : ")
list2 = input("Enter list two : ")
length1 = len(list(list1))
length2 = len(list(list2))
sumation = length1 + length2
fizz = sumation%3
buzz = sumation%5
#now creating the fizzbuzz function
def fizzbuzz():
if buzz == 0 and fizz == 0:
print('fizzbuzz')
elif buzz == 0:
print('buzz')
elif fizz == 0:
print('fizz')
else:
print('the lists are neither a fizzbuzz nor buzz nor fizz')
fizzbuzz()
| true |
a8b0b1306df3c42d9333f9d979b494a39ca79d96 | Resham1458/Max_Min_Number | /max_min_nums.py | 520 | 4.34375 | 4 | total=int(input("How many numbers you want to enter?")) #asks user the total number he/she wants to enter
numbers = [int(input("Enter any whole number:")) for i in range(total)] # lets the user to enter desired number of numbers
print("The list of numbers you entered is:",numbers) #displays list of numbers
print("The largest number you entered is:",max(numbers)) #out puts largest number
print ("The smallest number you entered is:",min(numbers)) #out puts smallest number
| true |
0cc4375b4bdce67644fa9a56784738b057b847f5 | kathytuan/CoffeeMachine | /main.py | 2,606 | 4.125 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
profit = 0
resources = {
"water": 300,
"milk": 200,
"coffee": 100
}
def menu_cost():
"""print items on menu and their cost"""
print("=== MENU ===")
for item in MENU:
item_cost = MENU[item]["cost"]
print(f"{item}: ${item_cost}")
# TODO: 3. check to see if resources are sufficient
def check_inv(order):
"""takes user's order and check to see if there's sufficient amount of resource inventory"""
for items in MENU:
if order == items:
recipe = MENU[items]["ingredients"]
# print(recipe)
for i in recipe:
if recipe[i] > resources[i]:
print(f"sorry, there's not enough {i}.")
else:
resources[i] -= recipe[i]
# check_inv(order)
# TODO: 4. process coins
def payment(order):
order_cost = MENU[order]["cost"]
input("Please insert coins.")
quarter = int(input("how many quarters? "))
dime = int(input("how many dime? "))
nickle = int(input("how many nickle? "))
penny = int(input("how many penny? "))
payment_total = round((quarter * 0.25 + dime * 0.10 + nickle * 0.05 + penny * 0.01), 2)
# TODO 5. check transaction successful
if payment_total >= order_cost:
global profit
profit += order_cost
change = round(float(payment_total - order_cost), 2)
print(f"Here's ${change} in change")
print(f"Here is your {order} ☕ Enjoy!")
else:
print("Sorry that's not enough money. Money refunded")
# payment(order)
def coffee_machine():
machine_if_off = False
while not machine_if_off:
menu_cost()
# TODO: 1. print report of the resources
order = (input("What would you like? (espresso/latte/cappuccino) "))
if order == "report":
for ingredients in resources:
print("{}: {}".format(ingredients, resources[ingredients]))
print(f"money: {profit}")
elif order == "off":
machine_if_off = True
exit()
else:
check_inv(order)
payment(order)
coffee_machine()
| true |
a87fa54c7333f4b517a7c4daf7883b6d463a6234 | kayanpang/champlain181030 | /week5-2_functions_181129/function.py | 684 | 4.34375 | 4 | # example: repetition
print("this is line 1")
print("---------------")
print("this is line 2")
print("---------------")
print("this is line 3")
print("---------------")
# so create a function to do this repetition
def print_underscores():
print("---------------")
# function needs to be defined before used
print("this is line 1")
print_underscores()
print("this is line 2")
print_underscores()
print("this is line 3")
# give a line to separate between function line
def print_equal():
print("==========")
def print_dash():
print("___---___")
def print_separator(width):
for w in range(width):
print("*", end="")
print("this is line 1")
print_separator(50) | true |
e4754d3dce75fe063cd24ecfc5dc2d543cdf0932 | kayanpang/champlain181030 | /190225_revision/different-kinds-of-array.py | 1,524 | 4.5625 | 5 | # list is ordered and changeable. Allows duplicate members. it uses [] square brackets
# – Use lists if you have a collection of data that does not need random access.
# Try to choose lists when you need a simple, iterable collection that is modified frequently.
mylist = [1, 2, 'Brendan']
print(mylist[1])
# tuple is ordered and unchangeable. Allows duplicate members. it uses () round brackets
# – Use tuples when your data cannot change.
mytuple = ('apple', 'banana', 'cherry', 1)
print(mytuple[1])
# a set is unordered and unindexed. it uses {} curly bracket
# need a for loop to get access to the set, cannot refer to index
# – Use a set if you need uniqueness for the elements
myset = {'apple', 'banana', 'cherry', 1, 2}
for x in myset:
print(x)
# a dictionary is unordered, changeable and indexed. it has keys and values. it uses {} curly bracket
# can access the items in a dictionary using its key name
# When to use a dictionary:
# – When you need a logical association between a key:value pair.
# – When you need fast lookup for your data, based on a custom key.
# – When your data is being constantly modified. Remember, dictionaries are mutable.
# https://monjurulhabib.wordpress.com/2016/09/22/python-when-to-use-list-vs-tuple-vs-dictionary-vs-set-theory/
mydict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
y = mydict["model"]
print(y)
# use for loop to access to a dictionary
for key, value in mydict.items():
print("\nKey: " + key)
print("Value: " + value) | true |
c8b21caf9356d06471480f3488522d6ca31b01ed | kayanpang/champlain181030 | /week7-2_private-contribution/encapsulation.py | 859 | 4.375 | 4 | # worker - employee - contractor initializer in child Classes (slide15)
# read everything about class he whole chapter
class Worker:
"""this class represents a worker"""
def __init__(self, worker_name=""):
self.name = worker_name
def set_name(self, new_name):
self.__name - new_name
def get_name(self):
return self.__name
class Employee(Worker):
"""this class specializes Worker and is salaried."""
def __init__(self, initial_salary, initial_name):
self.__salary = initial_salary
super().__init__(initial_name)
# super represents parent (Worker), it specify __init__
def set_salary(self, new_salary):
self.__salary = new_salary
def get_salary(self):
return self.__salary
e1 = Employee(50000, "Bob")
print(e1.get_name())
print(e1.get_salary())
print(e1.__salary) | true |
6c01d290efd21c4d689c0c102398550d308dda30 | adesanyaaa/ThinkPython | /fermat.py | 941 | 4.46875 | 4 | """
Fermat's Last Theorem says that there are no positive integers a, b, and c such that
a^n=b^n=c^n
Write a function named check_fermat that takes four parameters-a, b, c
and n-and that checks to see if Fermat's
theorem holds. If n is greater than 2 and it turns out to be true
the program should print, "Holy smokes, Fermat was wrong!"
Otherwise the program should print, "No, that doesn't work."
Write a function that prompts the user to input values
for a, b, c and n, converts them to integers, and uses
check_fermat to check whether they violate Fermat's theorem.
"""
def check_fermat():
a = int(input("Enter the first number:"))
b = int(input("Enter the second number:"))
c = int(input("Enter the third number:"))
n = int(input("Enter the value of n:"))
if (a ** n + b ** n == c ** n and n > 2):
print("HOly Smokes Fermat was wrong")
else:
print("Nope, that doesnt work")
check_fermat()
| true |
32c8fe672f6a6127973b4b28a62ab056321249bf | adesanyaaa/ThinkPython | /lists10.py | 862 | 4.15625 | 4 | """
To check whether a word is in the word list, you could use the in operator, but it
would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search (also
known as binary search), which is similar to what you do when you look a word up in the dictionary
"""
def binary_search(my_list, word):
if len(my_list) == 0:
return False
else:
midpoint = len(my_list) // 2
if my_list[midpoint] == word:
return True
else:
if word < my_list[midpoint]:
return binary_search(my_list[:midpoint], word)
else:
return binary_search(my_list[midpoint + 1:], word)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42, ]
print(binary_search(testlist, 3))
print(binary_search(testlist, 13))
| true |
3f7e4990a911eabae25c224a4d9454f1196d4e4e | adesanyaaa/ThinkPython | /VolumeOfSphere.py | 300 | 4.375 | 4 | """ The volume of a sphere with radius r is (4/3)*pi*r^3
What is the volume of a sphere with the radius 5
Hint: 392.7 is wrong
"""
# For this we will be using the math.pi function in python
# first we need to import the math class
import math
r = 5
volume = (4 / 3) * math.pi * r ** 3
print(volume)
| true |
712e3c920965f9a21bedcdd7df712a7f79cd9dbd | adesanyaaa/ThinkPython | /dictionary2.py | 502 | 4.34375 | 4 | """
Dictionaries have a method called keys that returns the keys of the dictionary, in
no particular order, as a list.
Modify print_hist to print the keys and their values in alphabetical order.
"""
hist = {1: 2, 3: 4, 5: 6, 7: 8}
mydict = {'carl': 40,
'alan': 2,
'bob': 1,
'danny': 3}
def print_hist():
myList = mydict.keys()
# Use of keys() function now for sorting the file
print(myList)
for key in sorted(mydict):
print(key)
print_hist()
| true |
88140b85b4cbc6075b2f18b09f12beb48eacc55a | adesanyaaa/ThinkPython | /store_anagrams.py | 1,116 | 4.1875 | 4 | """
Write a module that imports anagram_sets and provides two new functions: store_anagrams
should store the anagram dictionary in a "shelf;" read_anagrams should look up a word and return
a list of its anagrams.
"""
import shelve
import sys
from anagram_set import *
def store_anagrams(filename, ad):
"""Stores the anagrams in ad in a shelf.
filename: string file name of shelf
ad: dictionary that maps strings to list of anagrams
"""
shelf = shelve.open(filename, 'c')
for word, word_list in ad.iteritems():
shelf[word] = word_list
shelf.close()
def read_anagrams(filename, word):
"""Looks up a word in a shelf and returns a list of its anagrams.
filename: string file name of shelf
word: word to look up
"""
shelf = shelve.open(filename)
sig = signature(word)
try:
return shelf[sig]
except KeyError:
return []
def main(command='store'):
if command == 'store':
ad = all_anagrams('words.txt')
store_anagrams('anagrams.db', ad)
else:
print(read_anagrams('anagrams.db', command))
main()
| true |
a6ae696b7ffe00652f7ef0d1c5ab8c4a7de0b474 | adesanyaaa/ThinkPython | /lists3.py | 570 | 4.21875 | 4 | """
Write a function that takes a list of numbers and returns the cumulative sum
that is, a new list where the ith element is the sum of the
first i + 1 elements from the original list. For
example, the cumulative sum of [1, 2, 3] is [1, 3, 6]
"""
def nested_sum():
a = int(input("Enter the number of Elements you want to add:"))
mylist = []
for i in range(0, a):
mylist.append(int(input()))
mylist2 = []
mysum = 0
for i in range(0, a):
mysum = mysum + mylist[i]
mylist2.append(mysum)
print(mylist2)
nested_sum()
| true |
481095e995d267d95df513b8deace98d3492090a | adesanyaaa/ThinkPython | /VariableAndValues.py | 849 | 4.6875 | 5 | """ Assume that we execute the following statements
width= 17
height=12.0
delimiter='.'
for each of the expressions below write down the expression and the type
1. width/2
2. width/2.0
3. height/3
4. 1+2*5
5. delimiter*5
"""
width = 17
height = 12.0
delimiter = '.'
# 1. Width /2 should give an integer value of 8.5-float
first = width / 2
print(first)
print(type(first))
# Width /2.0 should give an integer value of 8.5-float
second = width / 2.0
print(second)
print(type(second))
# height/3 should give 4.0 as float
third = height / 3
print(third)
print(type(third))
# Printing a simple mathematical expression will give an int value
maths = 1 + 2 * 5
print(maths)
print(type(maths))
# delimiter*5 will print the delimiter five times and the type will be string
print(delimiter * 5)
FiveDelimiter = delimiter * 5
print(type(FiveDelimiter))
| true |
97914bc6f8c62c76aa02de1bd5c5f2a82e02e6db | nuria/study | /EPI/11_real_square_root.py | 748 | 4.1875 | 4 | #!usr/local/bin
import sys
import math
def inner_square_root(_max, _min, n):
tolerance = 0.05
middle = (_max - _min) *0.5
middle = _min + middle
print "max: {0}, min:{1}, middle:{2}".format(_max, _min, middle)
if abs(middle* middle -n) < tolerance:
return middle
elif middle * middle < n:
return inner_square_root(_max, middle, n)
else:
return inner_square_root(middle, _min, n)
def square_root(n):
# square root can be bigger than the number if the number <1
if n >= 1:
# solution is between [1,n/2]
return inner_square_root(n, 1, n)
else:
return inner_square_root(1, n, n)
if __name__=="__main__":
n = int(sys.argv[1])
print square_root(n)
| true |
fd5abb56732e9ddf37f093fe007c6c848d414b44 | nuria/study | /misc/five-problems/problem3.py | 714 | 4.25 | 4 | #!/usr/local/bin/python
'''
Write a function that computes the list of the first 100 Fibonacci numbers. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
'''
def main():
# caches prior fib numbers to avoid recurring for ever
# using an array
cache = []
def fib(i):
if i>= len(cache):
f = cache[i-1] + cache[i-2]
cache.append(f)
return cache[i]
cache.append(0)
cache.append(1)
for n in range(0, 101):
print fib(n)
if __name__ == "__main__":
main()
| true |
d929b25cb329d8a2c6589856e48e660c372b7aae | nuria/study | /crypto/xor.py | 1,748 | 4.46875 | 4 | #!/usr/local/bin/python
import sys
import bitstring
import virtualenv
# snipet given in coursera crypto course
# note xor of 11 and 001 will be 11, chops the last '1' at the longer string
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
def random(size=16):
return open("/dev/urandom").read(size)
def encrypt(key, msg):
c = strxor(key, msg)
print
print c.encode('hex')
return c
def _main():
key = random(1024)
ciphertexts = [encrypt(key, msg) for msg in MSGS]
#returns raw ascii codes (decimal)
def getAscii(text):
asciiText = ''
for ch in text:
asciiText = asciiText+" "+ str(ord(ch))
return asciiText
# assumes input is a hex string, decides it before doing an xor
def main():
ct1 = sys.argv[1];
ct2 = sys.argv[2];
# let's xor all strings together and see what we get
_next = strxor(ct1.decode("hex"),ct2.decode("hex"));
print getAscii(ct1.decode("hex"));
print getAscii(ct2.decode("hex"));
# print everything with ascii codes
print _next.encode("hex");
print _next
'''
When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
'''
if __name__ == '__main__':
main()
| true |
352b8196d758694512da5c5105977cf6d4e76ce4 | nuria/study | /EPI/tmp_linked_list_flatten.py | 1,957 | 4.1875 | 4 | #!usr/local/bin
# define each node with two pointers
class llNode:
def __init__(self, value, _next = None, head = None):
self.value = value
# next node
self.next = _next
self.head = head
def __str__(self):
if self.value is None:
return 'None ->'
return self.value + "->"
def flatten(head):
# simply walk the list
node = head
prior = None
while (node is not None):
if node.value is not None:
# continue, lawful value
prior = node
node = node.next
else:
# this is the head of a list, two possible
# ways, remove it (it is empty)
# or flatten it
if node.head is None:
# remove this node, it is an empty head
prior.next = node.next
# prior does not change
node = node.next
else:
# this node is the start of a list
# find list end
item = node.head
while (item.next is not None):
item = item.next
# item contains last node of this list
prior.next = item
item.next = node.next
prior = item
node = item.next
return head
def print_list(head):
node = head
while (node is not None):
print node
node = node.next
if __name__=="__main__":
# as coded all elements have null head pointers
# not just one
# the empty head that has to be removed just has '' value
a = llNode('a')
b = llNode('b')
c = llNode('c')
d = llNode('d')
e = llNode('e')
empty_1 = llNode(None)
empty_2 = llNode(None)
a.next = b
b.next = empty_1
empty_1.next = c
c.next = empty_2
empty_2.head = d
d.next = e
print_list(a)
print "****"
print_list(flatten(a))
| true |
cc3c31b09a402b7637ed05d98a01476620f26280 | nuria/study | /misc/five-problems/problem6.py | 1,726 | 4.25 | 4 | #!/usr/local/bin/python
import sys
def main():
'''
Given a sorted array and a target value, return the index
if the target is found. If not, return the index where
it would be if it were inserted in order. There won't be duplicate values in the array.
For example:
[1, 3, 5, 6] with target value 5 should return 2.
[1, 3, 5, 6] with target value 2 should return 1.
[1, 3, 5, 6] with target value 7 should return 4.
[1, 3, 5, 6] with target value 0 should return 0.
make sure it works for arrays that are large enough
Call like: python problem6.py 2 '1 2 3 4'
'''
def find_target(t, l, left_index):
# binary search, we need to keep track of indexes,
# just remember left and right index of the sublist in which we are looking
size = len(l)
if size == 1:
if t == l[0]:
# base case
print str(left_index)
else:
if l[0] < t:
print left_index + 1
else:
if left_index != 0:
print left_index - 1
else:
print 0
else:
# split in two
middle = int(size/2)
if l[middle] == t:
print left_index + middle
elif l[middle] > t:
left = l[left_index:middle]
find_target(t, left, left_index)
elif l[middle] < t:
right = l[middle:size]
find_target(t, right, left_index + middle)
target = sys.argv[1]
l = sys.argv[2].split()
find_target(target, l, 0)
if __name__ == "__main__":
main()
| true |
e37aeda0aa6f7d493dd27b2715d362a25138392a | maike-hilda/pythonLearning | /Ex2_5.py | 469 | 4.28125 | 4 | #Exercise 2.5
#Write a program that prompts the user for a Celsius temperature,
#convert the temperature to Fahrenheit, and print out the converted
#temperature
#Note: 0 deg C equals 32 deg F and 1 C increase equals 9/5 F increase
C = raw_input('Enter the current temperature in Degree Celcius:\n')
try:
C = float(C)
except:
print 'Please enter a number.'
F = C * 9/5 + 32
print 'The current temperature is ' + str(F) + ' degree Fahrenheit'
| true |
767d08be4e912dd1824c4431dc5a4a047b53f805 | maike-hilda/pythonLearning | /Ex6_3.py | 326 | 4.21875 | 4 | #Exercise 6.3
#Write a function named count that accepts a string and a letter to
#be counted as an argument
def count(word, countLetter):
count = 0
for letter in word:
if letter == countLetter:
count = count + 1
print 'The letter', countLetter, 'appeared', count, 'times.'
| true |
14e0fa9c2a493870a09bd9be0818e2c0d0766ca2 | priya510/Python-codes | /01.10.2020 python/min.py | 419 | 4.125 | 4 |
num1=int(input("Enter the first number: "));
num2=int(input("Enter the second number: "));
num3=int(input("Enter the Third number: "));
def find_Min():
if(num1<=num2) and (num1<=num2):
smallest=num1
elif(num2<=num1) and (num2<=num3):
smallest=num2
elif(num3<=num1) and (num3<=num2):
smallest=num3
print("minimum number is",smallest)
find_Min();
| true |
886ab87338fe873257b61abdb90971044bfb1db1 | jdn8608/Analysis_of_Algo_hw_2 | /src/sphere.py | 2,341 | 4.1875 | 4 | import math
'''
Name: Joseph Nied
Date: 2/12/20
Class: CSC-261
Question: 3
Description: Algorithm to see if given a points, if any would lie on a sphere together
'''
def main() -> None:
SIZE = int(input())
#Create an empty array with size SIZE
Magnitude = [None] * SIZE
#Get the input coordinates
for i in range(SIZE):
inputVal = input()
list = inputVal.split()
temp_x = int(list[0])
temp_y = int(list[1])
temp_z = int(list[2])
#Enter in the magnitude^2 for each point (this stays an int)
Magnitude[i] = int((math.pow(temp_x, 2) + math.pow(temp_y, 2) + math.pow(temp_z, 2)))
determind(Magnitude, SIZE)
def determind(Magnitude, size):
#Determine the max value in magnitude
max = Magnitude[0]
for x in range(1, len(Magnitude)):
if max < Magnitude[x]:
max = Magnitude[x]
#Sort the data in about O(n) time:
radixSort(Magnitude, max, size)
#loop through the array in O(n) time
#See if any neighbors are equal, if so, they lie on a sphere together
answer = 'NO';
for i in range(len(Magnitude)-1):
if Magnitude[i] == Magnitude[i+1]:
answer = 'YES'
print(answer)
def countSort(Magnitude, power,size):
#answer array that will hold the sorted data
answer = [0] * len(Magnitude)
#empty array that will contain the counts
count = [0] * size
#counts the occureces of a #//power % size
#this is specifc for radixsort
for i in range(len(Magnitude)):
digitValue = (Magnitude[i]//power)%size
count[digitValue]+=1
#makes the count array cummalative
for j in range(1,len(count)):
count[j] = count[j-1] + count[j]
#loops through backwards and slowly fills the answer array given the count array
k = len(Magnitude)-1
while k >=0:
digitValue = (Magnitude[k]//power)%size
answer[count[digitValue] - 1] = Magnitude[k]
count[digitValue] -= 1
k-=1
#Convert Magnitude to the answer array
for l in range(len(Magnitude)):
Magnitude[l] = answer[l]
def radixSort(Mag, maxVal,size):
place = 1
while (maxVal/place) > 0:
countSort(Mag, place, size)
#increment place but a multiplicity of size
place = place*size
if __name__ == '__main__':
main() | true |
61af3f82b452f1e0402cafc2a5797e3ffbb399be | Tamabcxyz/Python | /th2/dictionariescollectioninpython.py | 371 | 4.15625 | 4 | #A dictionary is a collection unordered can changeable, index. In python dictionary are written with curly brackets
#the have keys and values
a={"name":"Tran Minh Tam", "age":22}
print(a)
for x in a.values():
print(x)
for x in a.keys():
print(x)
for x,y in a.items():
print(f"a have key {x} values is {y}")
#add item you can write below
a["address"]="VL_CT"
print(a) | true |
d5438545ead5bb2d41c7791b6e86c72c4f93aa66 | LuannaLeonel/data-structures | /src/python/InsertionSort.py | 314 | 4.125 | 4 | def insertionSort(value):
for i in range(len(value)):
j = i
while (j > 0 and value[j] <= value[j-1]):
value[j], value[j-1] = value[j-1], value[j]
j -= 1
return value
a = [1,3,7,9,5]
b = [5,5,7,3,0,2,1,52,10,6,37]
print insertionSort(a)
print insertionSort(b)
| true |
37679aa5f19d56a0cd004f0349fb566d902f9464 | nara-l/100pythonexcercises | /Ex66basic_translator.py | 299 | 4.125 | 4 |
def translator(word):
d = dict(weather="clima", earth="terra", rain="chuva")
try:
return d[word.lower()]
except KeyError:
return "We don't understand your choice."
word = input("Please enter a word to translate, weather, earth, rain etc. \n ")
print(translator(word))
| true |
7d614f93d73dae587402e28e85e31062bafbdfa6 | matthewosborne71/MastersHeadstartPython | /Programs/Exercise1.py | 411 | 4.125 | 4 | # Write a program that generates a random integer between 1 and 100
# and then has the user guess the number until they get it correct.
import random
Number = random.randint(1,100)
Guess = -99
print "I thought of a number, want to guess? "
while Guess != Number:
Guess = int(raw_input())
if Guess != Number:
print "You're wrong, loser. Guess again."
print "Way to go! You did it! Awesome!"
| true |
b68ed99d0e68860f0ccdff2b272babe8ab836381 | InFamousGeek/PythonBasics | /ProgramToFindTheLngthOfAString1.py | 276 | 4.375 | 4 | # Python Program to find the length of a String (2nd way)
# using for loop
# Returns length of string
def findLen(str):
counter = 0
for i in str:
counter += 1
return counter
str = str(input("Enther the string : "))
print(findLen(str))
| true |
cf0fcc053e157beaa2b6eee2a78fa788d7cb2b8c | jonathan-murmu/ds | /data_structure/leetcode/easy/344 - Reverse String/reverse_string.py | 991 | 4.3125 | 4 | '''
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
'''
class Solution:
def reverseString(self, s) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# length = len(s)
# for i in range( length//2 ):
# temp = s[i]
# s[i] = s[(length-1) - i]
# s[(length - 1) - i] = temp
#
# # s[i], s[(length - 1) - i] = s[(length - 1) - i], s[i]
l = 0
r = len(s) - 1
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return s
s = ["h","e","l","l","o"]
# s = ["H","a","n","n","a","h"]
obj = Solution()
print(obj.reverseString(s)) | true |
05a2eece1e470e7324b753635da58de637b61b7c | Descent098/schulich-ignite-winter-2021 | /Session 3/Solutions/Exercise 1.py | 1,266 | 4.34375 | 4 | """Exercise 1: Country Roads
Steps:
1. Fill out fill_up() so that it fills the fuel level to the gas tank size (line 18)
2. Fill out drive() so that it removes the amount of fuel it should for how far you drove(line 22)
3. Fill out kilometres_available so that it returns the amount of kilometers left based on the fuel economy(line 26)
"""
class Car:
"""A class representing a car with details about how far it can travel"""
def __init__(self, gas_tank_size, fuel, litres_per_kilometre):
self.gas_tank_size = gas_tank_size
self.fuel = fuel
self.litres_per_kilometre = litres_per_kilometre
def fill_up(self):
"""Fills up the car's Fuel"""
self.fuel = self.gas_tank_size
def drive(self, kilometres_driven):
"""Remove the amount of fuel, based on distance driven"""
self.fuel -= (self.litres_per_kilometre * kilometres_driven)
def kilometres_available(self):
"""Return the number of kilometers that the car could drive with the current amount of fuel"""
return self.fuel / self.litres_per_kilometre
# Code to test
c = Car(10,9,2)
print(c.kilometres_available())
c.drive(4)
print(c.kilometres_available())
c.fill_up()
print(c.kilometres_available())
| true |
4b88131b589761baf17e03992be46cb9742c0a62 | praemineo/backpropagation | /backpropagation.py | 1,720 | 4.15625 | 4 | import numpy as np
#define sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# X is a unit vector
x = np.array([0.5, 0.1, -0.2])
# target that we want to predict
target = 0.6
#learning rate or alpha
learnrate = 0.5
#weight that we initialize
weights_input_hidden = np.array([[0.5, -0.6],
[0.1, -0.2],
[0.1, 0.7]])
#weight that produced by hidden layer as a output
weights_hidden_output = np.array([0.1, -0.3])
# # Feed - Forward
## Forward pass
hidden_layer_input = np.dot(x, weights_input_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
print("hidden_layer_output :",hidden_layer_output)
output_layer_input = np.dot(hidden_layer_output, weights_hidden_output)
output = sigmoid(output_layer_input)
print("Predicted output : ", output)
# # Backpropagation
## Backwards pass
## Calculating output error
error = target - output
print("error: ", error)
# Calculating error term for output layer
output_error_term = error * output * (1 - output)
# Calculating error term for hidden layer
hidden_error_term = np.dot(output_error_term, weights_hidden_output) * hidden_layer_output * (1 - hidden_layer_output)
# Calculating change in weights for hidden layer to output layer
delta_weight_hidden_output = learnrate * output_error_term * hidden_layer_output
# Calculate change in weights for input layer to hidden layer
delta_weight_input_hidden = learnrate * hidden_error_term * x[:, None]
# # Weight change between the layers
print('Change in weights for hidden layer to output layer:')
print(delta_weight_hidden_output)
print('\nChange in weights for input layer to hidden layer:')
print(delta_weight_input_hidden)
| true |
5a47d18b0353a71db8c6d177beed9cbda00ab3b6 | birdcar/exercism | /python/scrabble-score/scrabble_score.py | 584 | 4.1875 | 4 | from typing import Dict
# Generates a mapping of letters to their scrabble score e.g.
#
# { 'A': 1, ..., 'Z': 10 }
#
SCORE_SHEET: Dict[str, int] = dict(
[(x, 1) for x in 'AEIOULNRST'] +
[(x, 2) for x in 'DG'] +
[(x, 3) for x in 'BCMP'] +
[(x, 4) for x in 'FHVWY'] +
[(x, 5) for x in 'K'] +
[(x, 8) for x in 'JX'] +
[(x, 10) for x in 'QZ']
)
def score(word: str) -> int:
"""
Given a word, compute the scrabble score for that word.
"""
if not x.isalpha():
return 0
return sum(SCORE_SHEET[char] for char in word.upper())
| true |
d7025c13f88527f24d10fc1a9b131f0c7e7bd627 | TheAughat/Setting-Out | /Python Practice/app4.py | 641 | 4.15625 | 4 | # The following block of code writes the times table for anything till times 10. Users can enter 'please stop' to quit
print('Writes the times table for anything till times 10. Enter "please stop" to quit.')
while True:
print()
tables = input("Which number do you want to see the tables of? ")
number = 0
if tables.lower() == "please stop":
print()
print("Alright, kiddo. Enough math for now.")
print()
break
else:
for times10 in range(int(tables), int(tables) * 11, int(tables)):
number += 1
print(f'{int(tables)} x {number} = {times10}')
| true |
9208bc3b8e1ef3b6ef3e291d410057f926b0a2ac | kenedilichi1/calculator | /main.py | 917 | 4.15625 | 4 |
def add(x, y):
''' Adds 2 numbers '''
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
isRunning = True
while isRunning:
choice = input("operator: ")
if choice in ('add', 'subtract', 'multiply', 'divide'):
num1 = float(input("Enter num1: "))
num2 = float(input("Enter num2: "))
if choice == 'add':
result = add(num1, num2)
print(int(result))
elif choice == 'subtract':
result = subtract(num1, num2)
print(int(result))
elif choice == 'multiply':
result = multiply(num1, num2)
print(int(result))
elif choice == 'divide':
result = divide(num1, num2)
print(int(result))
else:
print("Input error")
| true |
8a4a09865d205160bc4fdbcbedbd77e8d1f48124 | Prithvi103/code-with-me | /Longest Mountain in Array {Medium}.py | 2,314 | 4.125 | 4 | """
Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
B.length >= 3
There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(Note that B could be any subarray of A, including the entire array A.)
Given an array A of integers, return the length of the longest mountain.
Return 0 if there is no mountain.
Example 1:
Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: [2,2,2]
Output: 0
Explanation: There is no mountain.
Note:
0 <= A.length <= 10000
0 <= A[i] <= 10000
Follow up:
Can you solve it using only one pass?
Can you solve it in O(1) space?
"""
"""
Solved by considering situations where the current number is greater, lesser and equal to the
previous number. Single pass O(n) solution and O(1) time complexity.
"""
class Solution:
def longestMountain(self, A: List[int]) -> int:
if A is None or len(A) < 3:
return 0
start = False
down = False
up = False
highest = 0
l = 1
for i in range(1,len(A)):
if i==(len(A)-1):
if up:
if A[i]<A[i-1]:
l+=1
if l>highest:
highest = l
if A[i]>A[i-1]:
if down and up:
if l>highest:
highest = l
l = 1
down = False
if up is False:
up = True
start = True
l = 1
l += 1
if A[i]<A[i-1]:
if up:
down = True
else:
continue
l+=1
if A[i] == A[i-1]:
if up:
if down:
up = False
down = False
if l>highest:
highest = l
l = 1
else:
up = False
l = 1
else:
continue
return highest | true |
9be5923a412b0d78f7a283c93f5acb80b52ac9b8 | musicakc/NeuralNets | /Tutorial/threelayernn.py | 1,701 | 4.15625 | 4 | '''
Neural Networks Tutorial 1:
https://iamtrask.github.io/2015/07/12/basic-python-network/
3 input nodes, 4 training examples
'''
import numpy as np
'''
Nonlinearity or sigmoid function used to map a value to a
value between 0 and 1
'''
def nonlin(x,deriv=False):
#ouput can be used to create derivative
if(deriv == True):
return x*(1-x) #slope or derivative
return 1/(1 + np.exp(-x)) #formula of sigmoid fuction
#input x_(4*3)
x = np.array([[0,0,1], [0,1,1],[1,0,1],[1,1,1]])
#output y_(4*1)
y = np.array([[0,1,1,0]]).T #transpose the output array
#seed random numbers
np.random.seed(1)
'''
Initialise weights randomly with mean 0,
of dimension [3*1] for 3 inputs and 1 ouput
'''
syn0 = 2 * np.random.random((3, 4)) - 1
syn1 = 2 * np.random.random((4, 1)) - 1
#iterate multiple times to optimise our neural network
for i in range(60000):
#forward propogation
l0 = x
#hidden layer l1_(4*4) = [l0_(4*3) dot syn0_(3*4)]
l1 = nonlin(np.dot(l0,syn0))
#hidden layer l2_(4*1) = [l1_(4*4) dot syn1_(4*1)]
l2 = nonlin(np.dot(l1,syn1))
#calculate error between output and l2
l2_error = y - l2
if ((i % 10000) == 0):
print ("Error:" + str(np.mean(np.abs(l2_error))))
#slope of l2 * error to reduce error of high confidence predictions
l2_delta = l2_error * nonlin(l2,True)
'''
calculate confidence weighted error by calculating how much
each node value contributed to the error in l2
'''
l1_error = l2_delta.dot(syn1.T)
#slope of l1 * error to reduce error of high confidence predictions
l1_delta = l1_error * nonlin(l1,True)
#update weights using l2_delta
syn1 += np.dot(l1.T, l2_delta)
#update weights using l1_delta
syn0 += np.dot(l0.T, l1_delta)
#print (l1)
| true |
ca5d631772a998607acba42ead0af35f7956b6ee | nonstoplearning/python_vik | /ex13.py | 1,135 | 4.125 | 4 | from sys import argv
script, first, second, third = argv
fourth = input("Enter your fourth variable: ")
fifth = input("Enter your fifth variable: ")
print ("Together, your first variable is %r, your second variable is %r, your third variable is %r, "
"your fourth variable is %r, your fifth variable is %r" % (first, second, third, fourth, fifth))
"""
github vikram.talware$ python ex13.py stuff things
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
"""
"""
vikram.talware$ python ex13.py stuff things that vik
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: too many values to unpack (expected 4)
"""
script, first, second, third = argv, input("Enter your first variable: "), input("Enter your second variable: "), input("Enter your third variable: ")
print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
| true |
db7f21092dc6cba286f2c1270129f7c56b706d25 | cheokjw/Pytkinter-study | /tkinter/Codes/tk button.py | 849 | 4.3125 | 4 | from tkinter import *
# Initializing Tk class OOP(Object-Oriented Programming)
root = Tk()
# A function that shows the text "Look! I clicked a Button"
def myClick():
myLabel = Label(root, text = "Look! I clicked a Button !")
myLabel.pack()
# Button(root, text) = having a button for user to click
# state = DISABLED = wont allow user to click the button, but it'll still show the button
# padx = num = controlling the x-axis(width size) of the button
# pady = num = controlling the y-axis(length size) of the button
# command = func = letting the button to do something
# fg = "colour" = changing the text colour
# bg = "colour" = changing the button background color
myButton = Button(root, text = "Click Me!", padx = 50, pady = 50, fg = "Blue", bg = "light green", command = myClick)
myButton.pack()
# Tkinter loop func
root.mainloop() | true |
ac6b346fd9f0262cfd9381e374236955ee972a5e | bfakhri/deeplearning | /mini-1/bfakhri_fakhri/regressor.py | 1,365 | 4.28125 | 4 | """
Author: Bijan Fakhri
Date: 2/3/17
CSE591 - Intro to Deep Learning
This file implements the regressor class which performs a linear regression given some data
"""
import numpy as np
class regressor(object):
"""
Class that implements a regressor. After training, it will have weights that can be exported.
Args:
train_data: data with which to train the regressor.
alpha (optional): sets the regularization parameter alpha
"""
def __init__(self, train_data, **kwargs):
# Regularization Param
if 'alpha' in kwargs.keys():
self.alpha = kwargs['alpha']
else:
self.alpha = 1
# Changes name of incoming data for clearer representation below
X = train_data[0]
#X = np.append(X, np.ones(X.shape[1]), axis=0)
ones_c = np.ones((X.shape[0], 1))
X = np.concatenate((X, ones_c), axis=1)
Y = train_data[1]
# Begin Regression
m1_1 = np.dot(np.transpose(X), X)
m1_2 = np.multiply(self.alpha, np.identity(X.shape[1]))
m1 = m1_1 + m1_2
m2 = np.linalg.inv(m1)
m3 = np.dot(m2, np.transpose(X))
m4 = np.dot(m3, Y)
self.w = m4
def get_params(self):
return self.w
def get_predictions(self, test_data):
ones_c = np.ones((test_data.shape[0], 1))
test_data = np.concatenate((test_data, ones_c), axis=1)
return np.transpose(np.dot(np.transpose(self.w), np.transpose(test_data)))
if __name__=='__main__':
pass
| true |
4c483c108073d56208c7d1e56497e2dca3e6588a | NewAwesome/Fundamental-algorithms | /LeetCode/21. Merge Two Sorted Lists/Solution.py | 1,321 | 4.1875 | 4 | from ListNode import ListNode
class Solution:
# Iteration
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# create a var named 'head' node, used for point to head of the result LinkedList
# create a var named 'cur' node, used for iteration point to the smaller node of l1 and l2.
head = cur = ListNode()
# iteration
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur.next = l1 or l2
return head.next
# Recursive
# base case 是比较l1和l2的val值,如果l1.val更小,那么需要:1. l1.next指向下一个(因为不在本次base case 中,所以就指向递归调用);2. return l1
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
# end case : l1 or l2 is None
if not l1 or not l2:
return l1 or l2
# base case : compare l1.val and l2.val, the smaller one such as l1 will recursively be invoked with the arguments of l1.next and l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists1(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists1(l1,l2.next)
return l2 | true |
5e8d193c0a21c3c3dfafcb0fb94419777359e9ca | jjunsheng/learningpython | /mosh python/quiz(comparison operators).py | 438 | 4.46875 | 4 | #if name is less than 3 characters long
#name must be at least 3 characters
#otherwise if it's more than 50 characters long
#name can be a maximum of 50 chatacters
#otherwise
#name looks good
name = input('Name : ')
if len(name) < 3:
print("Name must be a minumum of 3 characters. Please try again.")
elif len(name) > 50:
print("Name can be a maximum of 50 characters. Please try again.")
else:
print("Name looks good!")
| true |
ba2ce236426a14d35f10540770106ef7e14735a2 | maheboob76/ML | /Basics/Perceptron_vs_Sigmoid.py | 1,077 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
http://neuralnetworksanddeeplearning.com/chap1.html#exercise_263792
Small example to show difference between a perceptron and sigmoid neuron
For a Machine Learning model to learn we need a mechanism to adjust output of model by small adjustments in input. This example shows
why a percptron is unsuitable for learning tasks and how sigmoid neuron is different.
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
B = 1
X = 1
N = 10
STEP = 1
W = [i for i in range(-N, N+1, STEP)]
def perceptron(w):
z = w * X + B
out = 0
if z > 0:
out =1
else:
out = 0
return out
def sigmoid(w):
z = w * X + B
out = 1.0/(1.0+np.exp(-z))
return out
y_perc = [perceptron(i) for i in W]
y_sig = [sigmoid(i) for i in W]
plt.plot(W, y_perc, '--o')
plt.plot(W, y_sig, '--X')
plt.title('Perceptron vs Sigmoid Neuron')
plt.xlabel('Input Weight')
plt.ylabel('Output Y')
plt.legend(['Perceptron', 'Sigmoid'], loc='upper left')
plt.show()
| true |
4fe62261defaeed3b3dcc21aff9d1bebdca21225 | MarcusDMelv/Summary-Chatbot | /voice.py | 1,395 | 4.125 | 4 | # Code based on https://www.geeksforgeeks.org/text-to-speech-changing-voice-in-python/
# Python program to show
# how to convert text to speech
import pyttsx3
# Initialize the converter
converter = pyttsx3.init()
# Set properties before adding
# Things to say
# Sets speed percent
# Can be more than 100
converter.setProperty('rate', 150)
# Set volume 0-1
converter.setProperty('volume', 0.7)
# Queue the entered text
# There will be a pause between
# each one like a pause in
# a sentence
converter.say("Hello Justin")
converter.say("What is Zindin doing?")
# Gets and prints list of voices available
voices = converter.getProperty('voices')
# Empties the say() queue
# Program will not continue
# until all speech is done talking
converter.runAndWait()
for voice in voices:
# to get the info. about various voices in our PC
print("Voice:")
print("ID: %s" % voice.id)
print("Name: %s" % voice.name)
print("Age: %s" % voice.age)
print("Gender: %s" % voice.gender)
print("Languages Known: %s" % voice.languages)
# Now configure for female voice
voice_id = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
# or male ID: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
# Use female voice
converter.setProperty('voice', voice_id)
converter.say("Female AIs Rule!")
converter.runAndWait()
| true |
4f3f602373b166d9a2a9af94c5a33befa671208c | grantthomas/project_euler | /python/p_0002.py | 955 | 4.1875 | 4 | # Even Fibonacci numbers
# Problem 2
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def fibonacci(n: int) -> list:
"""generate all fibonacci numbers less than n
Args:
n (int): input
Returns:
list: list of fibonacci numbers less than n
"""
i = [1, 1, 2]
while i[-1] < n:
next = i[-1] + i[-2]
if next < n:
i.append(next)
else:
break
return i
def sum_evens(items: list) -> int:
result = 0
for item in items:
if item % 2 == 0:
result += item
return result
if __name__ == "__main__":
fib = fibonacci(4e6)
result = sum_evens(fib)
print(result)
| true |
64b527ed4f5a3a18da10ee421e7b88b06e90bed7 | kkbaweja/CS303 | /Hailstone.py | 2,487 | 4.4375 | 4 | # File: Hailstone.py
# Description: A program that computes the hailstone sequence for every number in a user defined range
# Student Name: Keerat Baweja
# Student UT EID: kkb792
# Course Name: CS 303E
# Unique Number: 50860
# Date Created: 2/7/2016
# Date Last Modified: 2/9/2016
def main():
# Prompt the user to enter the starting number
start = input("\nEnter starting number of the range: ")
# Prompt the user to enter the ending number
finish = input("\nEnter ending number of the range: ")
# Check to make sure start is positive
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Check to make sure the end is positive
while (finish <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Check to make sure the start is smaller than the end
while (start >= finish):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (finish <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
while (start <= 0):
start = input("\nEnter starting number of the range: ")
finish = input("\nEnter ending number of the range: ")
# Initialize variables
max_num = 0
number = start
max_cycle_length = 0
# Perform the calculation to find the hailstone sequence for each number in the range
while (number <= finish):
result = number
cycle_length = 0
while (result != 1):
if (result % 2 == 0):
result = result // 2
elif (result % 2 == 1):
result = 3*result + 1
cycle_length = cycle_length + 1
if (cycle_length >= max_cycle_length):
max_cycle_length = cycle_length
max_num = number
number = number + 1
# Print out result
print("")
print ("The number", max_num, "has the longest cycle length of", str(max_cycle_length) + ".")
# Call main function
main()
| true |
81603ced0143981ee6540c89ee829ff663547c2f | v-erse/pythonreference | /Science Libraries/Numpy/arraymath.py | 1,033 | 4.34375 | 4 | import numpy as np
print("Array Math:")
# Basic mathematical functions operate on ndarrays in an elementwise fashion
a = np.arange(10).reshape(2, 5)
b = np.arange(10).reshape(2, 5)
print(a + b)
print(a*b)
# We can use the dot function to find dot products of vectors and multiply
# matrices (the matrixmultiplication.jpg file in this folder explains matrix
# multiplication)
# We can also use the T attribute to access the transposed version of b, which
# would be the same as b.reshape(5, 2)
print(np.dot(a, b.T))
# Sum will find the sum of all the numbers in an array, column, or row
print(np.sum(a))
print(np.sum(a, axis=0)) # sum of each column
print(np.sum(a, axis=1)) # sum of each row
print("\n\nBroadcasting:")
# Numpy broadcasting allows us to take 'shortcuts' around some possible
# obstacles when doing array math
x = np.arange(1, 13).reshape(4, 3)
print(x)
y = np.array([1, 2, 1])
# In this example, y will be treated as if it has been stacked 4 times, to
# match the shape of x. This is broadcasting
print(x + y)
| true |
afe6d64552f6328412a7129f7a2fad6eadc8c554 | andres-zibula/geekforgeeks-problems-solved | /basic/twisted_prime_number.py | 554 | 4.15625 | 4 | """
Author: Andres Zibula
Github: https://github.com/andres-zibula/geekforgeeks-problems-solved
Problem link: http://practice.geeksforgeeks.org/problems/twisted-prime-number/0
Description: A number is said to be twisted prime if it is a prime number and reverse of the number is also a prime number.
"""
import math
def isPrime(n):
return all(n % i != 0 for i in range(2, math.floor(math.sqrt(n))+1))
T = int(input())
for _ in range(T):
n = int(input())
if isPrime(n) and isPrime(int(str(n)[::-1])):
print("Yes")
else:
print("No") | true |
8f9692a0be3836b363adc733511e4addbfc12292 | coder2000-kmj/Python-Programs | /numprime.py | 595 | 4.34375 | 4 | '''
This is a program to print prime numbers starting from a number which will be given by the user
and the number of prime numbers to be printed will also be specified by the user
'''
def isprime(n,i=2):
if n<=2:
return True if n==2 else False
if n%i==0:
return False
if i*i>n:
return True
return isprime(n,i+1)
n=int(input("Enter the initial Number"))
num=int(input("enter the number of prime numbers you want"))
count=1
while count<=num:
if(isprime(n)):
print(n)
count+=1
n+=1
else:
n+=1
| true |
ecc4d29375e3c6200c6ac3b8f9f3b4f4c0769ca7 | alphashooter/python-examples | /homeworks-2/homework-2/task2.py | 574 | 4.125 | 4 | import calendar
from datetime import datetime
target: int
while True:
day_name = input(f'Enter day name ({calendar.day_name[0]}, etc.): ')
for day, name in enumerate(calendar.day_name):
if name == day_name:
target = day
break
else:
print('invalid input')
continue
break
now = datetime.now()
year, month = now.year, now.month
while True:
if calendar.weekday(year, month, 1) == target:
break
month -= 1
if month < 1:
year -= 1
month = 12
print(f'01.{month:02}.{year}')
| true |
eca16d3794404a3659a448df344b120d26e9fe2e | mey1k/PythonPratice | /PythonPriatice/InsertionSort.py | 252 | 4.15625 | 4 | def insertionSort(x):
for size in range(1, len(x)):
val = x[size]
i = size
while i > 0 and x[i-1] > val:
x[i] = x[i-1]
i -= 1
x[i] = val
print(x)
insertionSort([3,23,14,123,124,123,12,3]) | true |
bd40b86f7639ce864d19963092c1535a68118866 | kulvirvirk/list_methods | /main.py | 1,619 | 4.6875 | 5 |
# The list is a collection that is ordered and changeable. Allows duplicate members.
# List can contain other lists
# 1. create a list of fruits
# 2. using append(), add fruit to the list
# 3. use insert(), to insert another fruit in the list
# 4. use extend() method to add elements to the list
# 5. use pop() method to pop one of the elements from list
# 6. use remove() method to remove fruit from the list
# 7. use clear () method to clear the list
# 1. create a list of fruits
# 2. using append(), add fruit to the list
my_fruits_list = ['apple', 'banana', 'cherry']
print(my_fruits_list)
my_fruits_list.append('orange')
print(my_fruits_list)
print('----------------*****----------------')
# 3. use insert(), to insert another fruit in the list
print(my_fruits_list)
my_fruits_list.insert(2,'kiwi')
print(my_fruits_list)
print('----------------*****----------------')
# 4. use extend() method to add elements to the list
print(my_fruits_list)
second_fruits_list = ['mango', 'apple']
my_fruits_list.extend(second_fruits_list)
print(my_fruits_list)
print('----------------*****----------------')
# 5. use pop() method to pop one of the elements from list
print(my_fruits_list)
my_fruits_list.pop(1)
print(my_fruits_list)
print('----------------*****----------------')
# 6. use remove() method to remove fruit from the list
print(my_fruits_list)
my_fruits_list.remove('kiwi')
print(my_fruits_list)
print('----------------*****----------------')
# 7. use clear () method to clear the list
print(my_fruits_list)
my_fruits_list.clear()
print(my_fruits_list)
print('----------------*****----------------')
| true |
a232c1dbe330abefd09cb6c54916776cfae04c2b | darkscaryforest/example | /python/classes.py | 1,316 | 4.21875 | 4 | #!/usr/bin/python
class TestClass:
varList = []
varEx1 = 12
def __init__(self):
print "Special init function called."
self.varEx2 = 13
self.varEx3 = 14
def funcEx(self):
print self.varEx2
return "hello world"
x = TestClass()
print "1. Classes, like functions, must be declared before use.\n" \
"Calling a function in a class: " + x.funcEx() + "\n"\
"Note that all functions take at least one argument..a reference to the instance object itself"
print "2. There's a huge difference between class and instance attributes.\n" \
"class attributes are like static variables applied across all class instances\n" \
"and instance variables are scoped to particular class instances.\n"
y = TestClass()
y.varList.append(5)
y.varEx1 = 2
y.varEx2 = 5
print "x's arributes after changes:\n" \
"x.varList = " + str(x.varList) + "\n" \
"x.varEx1 = " + str(x.varEx1) + "\n" \
"x.varEx2 = " + str(x.varEx2) + "\n" \
"x.varEx3 = " + str(x.varEx3)
print "y's arributes after changes:\n" \
"y.varList = " + str(y.varList) + "\n" \
"y.varEx1 = " + str(y.varEx1) + "\n" \
"y.varEx2 = " + str(y.varEx2) + "\n" \
"y.varEx3 = " + str(y.varEx3)
print "The list in both x and y is changed even though we updated\n" \
"it through just y. Interestingly, the other int variable\n" \
"varEx1 did not change in x.."
| true |
0d3ea4123385980f8b24ecc5b59397e5e813372d | SnakeTweaker/PyStuff | /module 6 grocery list.py | 1,490 | 4.125 | 4 |
'''
Author: CJ Busca
Class: IT-140
Instructor: Lisa Fulton
Project: Grocery List Final
Date: 20284
'''
#Creation of empty data sctructures
grocery_item = {}
grocery_history = []
#Loop function for the while loop
stop = 'go'
while stop !='q':
#This block asks the user to input name, quantity, and price of items
item_name = input('Item name:\n')
quantity = input('Quantity purchased:\n')
cost = input('Price per item:\n')
#This block utilizes the empty list above to store the data input from the user
grocery_item['name'] = item_name
grocery_item['number'] = int(quantity)
grocery_item['price'] = float(cost)
grocery_history.append(grocery_item.copy())
#User has the option to continue inputting items or quit
stop = input("Would you like to enter another item? \nType 'c' for continue or 'q' to quit:\n")
#The grand total has a set value that gets added for each price that is entered
grand_total = 0
#This block utilizes a for loop for the iterations of the entered objects
for index, item in enumerate(grocery_history):
item_total = item['number'] * item['price']
#This block details the total of al of the items in the iteration
grand_total += (item_total)
print('%d %s @ $%.2f ea $%.2f' % (item['number'], item['name'], item['price'], item_total))
item_total = 0
#Grand total of all items is displayed only when user inputs quit command
print('Grand total: $%.2f' % grand_total)
| true |
0c4f077fa6e50d24ad81f1e7de30b08e60ac34f6 | radishmouse/2019-11-function-demo | /adding-quiz.py | 437 | 4.3125 | 4 | def add(a, b):
return a + b
# print(a + b)
# if you don't have a `return`
# your function automatically
# returns `None`
# Write a function that can be called like so:
add(1, 1)
# I expect the result to be 2
num1 = int(input("first number: "))
num2 = int(input("second number: "))
num3 = int(input("third number: "))
print(add(add(num1, num2), num3))
# And the result be 3
# Hint: the function should not print()
| true |
21e783fc5101c5cc328ec3fb5ea750e4f3773f72 | Sushmitha2708/Python | /Data Modules/JSONModulesFromFiles.py | 926 | 4.21875 | 4 | #this progam deals with how to load JSON files into python objects and then write those
# objects back to JSON files
import json
# to load a JSON file into a python object we use JSON 'load' method
#load method--> loads a file into python object
#loads method --> loads a string into a python object
# to load a file,it must be opened first
with open('countries.json') as f:
data=json.load(f)#after opening it is now loaded into a python obj
for country in data['countries']:
print(country['name'],country['pm'])
for country in data['countries']:
del country['capital']
#after deleting, the file is dumped back to a new json file usinng 'dump' method
#dump method--> dumps a file into python object
#dumps method --> dumps a string into a python object
#before dumping the data to a new json file, it must be created
with open('new_countries.json','w') as f:
json.dump(data,f,indent=2) | true |
b6d0f2e9b62f82970b371114f8734acc87026c0a | Sushmitha2708/Python | /Loops and Conditionals/ForLoop.py | 236 | 4.125 | 4 | #SET COMPREHENSIONS
# set is similar to list but with unique values
nums=[1,1,1,2,3,5,5,5,4,6,7,7,8,9,9] #list
my_set=set()
for n in nums:
my_set.add(n)
print(my_set)
#comprehension
my_set={n for n in nums}
print(my_set) | true |
7da4fa2f89f95532f15bf6e442d8d83af17f3bb4 | XanderEagle/unit6 | /unit6.py | 1,349 | 4.3125 | 4 | # by Xander Eagle
# November 6, 2019
# this program displays the Birthday Paradox showing the percent of people that have the sme birthday based on the
# amount of simulations
import random
def are_duplicates(nums):
"""finds the duplicates
:return: true if there is a duplicate
false if no duplicate
"""
for x in nums:
for y in nums[x + 1:]:
if y == x:
return True
return False
def run_it():
"""
ask the user to input the number of simulations
:return: the number of simulations
"""
return int(input("How many times do you want to run the simulation?"))
def main():
"""
tracks the variables and finds 23 random numbers out of 365
:return: the amount of duplicate birthdays along with the percentage
"""
track_variables = 0
num_times = run_it()
for nums in range(num_times):
birthdays = []
for x in range(23):
number = random.randint(1, 365)
birthdays.append(number)
if are_duplicates(birthdays):
track_variables += 1
percent_total = track_variables / num_times * 100
print("There were duplicate birthdays", track_variables, "times. That means two people had the same birthday",
percent_total, "percent of the time.")
main()
| true |
2865d43f5210b945eadc07481a14436f34b3ad23 | Mike7P/python-projects | /Guessing_game/guessing_game.py | 1,147 | 4.125 | 4 |
print("Welcome to Kelly's Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
attempts = 0
difficulty_choosing = False
random_num = randint(1, 100)
# print(f"Pssst, the correct answer is {random_num}")
def guessing_func(guess, random_num):
global attempts
attempts -= 1
if guess == random_num or attempts == 0:
return 0
elif guess < random_num:
print('Too low!')
elif guess > random_num:
print('Too high!')
while not difficulty_choosing:
choice = input("Choose a difficulty. Type 'easy' or 'hard': ")
if choice == 'easy':
attempts = 10
difficulty_choosing = True
elif choice == 'hard':
attempts = 5
difficulty_choosing = True
else:
print("Sorry, I have no idea what you typed but it wasn't easy or hard!!")
game_go = True
while game_go:
print(f"You have {attempts} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
guess_good = guessing_func(guess, random_num)
if guess_good == 0:
game_go = False
if guess == random_num:
print(f"You got it! The answer was {guess}.")
else:
print(f"Game over! {attempts} attempts left!! ")
| true |
d7dd96224064d98e702d82a4b781989d265e0fcb | nathanhwyoung/code_wars_python | /find_the_parity_outlier.py | 910 | 4.4375 | 4 | # https://www.codewars.com/kata/5526fc09a1bbd946250002dc
# You are given an array (which will have a length of at least 3, but could be very large) containing integers.
# The array is either entirely comprised of odd integers or entirely comprised of even integers except for a
# single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
def find_outlier(integers):
odds = 0
evens = 0
answer = []
for num in integers:
if num % 2 != 0:
odds += 1
elif num % 2 == 0:
evens +=1
if odds > evens:
answer = [num for num in integers if num % 2 == 0]
elif evens > odds:
answer = [num for num in integers if num % 2 != 0]
return answer[0]
# print(find_outlier([2, 4, 6, 8, 10, 3]))
# print(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))
# print(find_outlier([160, 3, 1719, 19, 11, 13, -21])) | true |
78f52eed0d2426d52462b9467f6224ead214b4fb | pavankumarNama/PythonLearnig | /Ex_Files_Python_Standard_Library_EssT/Exercise Files/Chapter 5/05_01/datetime_start.py | 810 | 4.34375 | 4 | # Basics of dates and times
from datetime import date, time, datetime
# TODO: create a new date object
tdate = date.today()
print(tdate)
# TODO: create a new time object
t = time(15, 20, 20)
print(t)
# TODO: create a new datetime object
dt = datetime.now()
dt1 = datetime.today()
print(dt)
print(dt1)
# TODO: access various components of the date and time objects
print(tdate.year)
print(tdate.month)
print(tdate.weekday())
print(t.hour)
print(t.minute)
# print('--------- ', time.hour)
# TODO: To modify values of date and time objects, use the replace function
d1 = tdate.replace(year=2021, month=12, day=31)
t1 = t.replace(hour=20, minute=33, second=45, microsecond=1000)
dt1 = dt.replace(year=2022, month=11, day=30, hour=14, minute=30, second=55, microsecond=5000)
print(d1)
print(t1)
print(dt1)
| true |
6c506a5b929738c7bfe76797f93923041020f061 | okeonwuka/PycharmProjects | /ProblemSolvingWithAlgorithmsAndDataStructures/Chapter_1_Introduction/pg29_selfcheck_practice.py | 2,996 | 4.15625 | 4 | import random
# create alphabet characters including 'space' character
alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', ' ']
# create empty list to house character matches from target sentence
sentence_generator = []
# # define random_alphabet_selector function (version 1)
# def random_alphabet_selector():
# global selected_alphabet
# selected_alphabet = random.choice(alphabet_list)
# return selected_alphabet
# define random_alphabet_selector function (version 2 - simpler)
def random_alphabet_selector():
return random.choice(alphabet_list)
# Input target sentence
target_sentence = input('Please enter desired sentence:')
print('your target sentence is: %s ' % target_sentence)
# # Monkey theorem algorithm test version 1
# for i in range(100):
# for a_character in target_sentence:
# random_alphabet_selector()
# if a_character == random_alphabet_selector():
# print('There is a match')
# sentence_generator.append(random_alphabet_selector())
# else:
# print('No match')
# print(sentence_generator)
# # Monkey theorem algorithm test version 2
# for i in range(500):
# for a_character in target_sentence:
# selected_alphabet = random_alphabet_selector()
# if a_character == selected_alphabet:
# print('yes there is a match, %s is in the target sentence' % selected_alphabet)
# if selected_alphabet in sentence_generator:
# pass
# else:
# sentence_generator.append(selected_alphabet)
# else:
# print('No match')
# print(sentence_generator)
# Monkey theorem algorithm test version 2
for i in range(10000):
for a_character in target_sentence:
selected_alphabet = random_alphabet_selector()
if a_character == selected_alphabet:
print('yes there is a match, %s is in the target sentence' % selected_alphabet)
sentence_generator.append(selected_alphabet)
else:
print('No match')
# combine items in the sentence_generator into a string and store in a variable called penultimate_sentence_generator
penultimate_sentence_generator = ''.join(sentence_generator)
print('The penultimate sentence generator is: %s' % penultimate_sentence_generator)
# Delimit/split the string in penultimate_sentence_generator by ' ' (space) and place in final_sentence_generator
final_sentence_generator = penultimate_sentence_generator.split(' ')
print('The Final sentence generated is: %s' % final_sentence_generator)
for a_word in final_sentence_generator:
word_count = final_sentence_generator.count(a_word)
for i in range(word_count):
if len(a_word) < 28:
final_sentence_generator.remove(a_word)
print('The final 27 character words are: %s' % final_sentence_generator)
| true |
8c40de2b5d9cfbb59af3428537caac07ed102c99 | okeonwuka/PycharmProjects | /Horizons/pythonPracticeNumpyArrays.py | 1,687 | 4.40625 | 4 | # The numpy module gives users access to numpy arrays and several computation tools.
# Numpy arrays are list-like objects intended for computational use.
from pprint import pprint
import numpy as np
my_array = np.array([1, 2, 3])
pprint(my_array)
# Operations on a numpy array are made element by element (unlike for lists of numbers):
pprint(my_array+1), pprint(my_array*2), pprint(np.sin(my_array))
# Numpy arrays are equipped with several useful methods such as:
my_array.shape, my_array.min(), my_array.max()
print(my_array.shape, my_array.min(), my_array.max())
# The numpy module also features some convenient array-generating functions:
# Linear space of 20 pts between 0 and 10
my_array2 = np.linspace(0, 10, 20)
pprint(my_array2)
# Sequence of numbers from 0 to 10 with step of 0.2,
# similar to range() but accepts non-integer steps
my_array3 = np.arange(0, 10, 0.2)
pprint(my_array3)
# Multi-dimensional arrays are created using nested list and a call to np.array()
# Here is an example of a 2D array:
my_array4 = np.array([[1, 2, 3], [4, 5, 6]])
pprint(my_array4)
# Items in a multi-dimensional array can be retrieved, like in a nested list, as:
my_array4[1][1]
print(my_array4[1][1])
# or
my_array4[0,2]
print(my_array4[0, 2])
# Moreover, numpy is equipped with several NaN (Not-a-Number) functions.
my_array5 = np.array([[1, np.nan], [np.nan, 2]])
pprint(my_array5)
np.nanmin(my_array5), np.nanmax(my_array5)
print(np.nanmin(my_array5), np.nanmax(my_array5))
np.isnan(my_array5)
pprint(np.isnan(my_array5))
# Finally, to concatenate numpy arrays, use:
np.concatenate([my_array,my_array2[0:5]])
pprint(np.concatenate([my_array,my_array2[0:5]]))
| true |
fa7839e158a42655a6bbdab05620c5fa0d1e7aa7 | wp-lai/xpython | /code/kthlargest.py | 922 | 4.21875 | 4 | """
Task:
Find the kth largest element in an unsorted array. Note that it is the kth
largest element in the sorted order, not the kth distinct element.
>>> find_kth_largest([3, 2, 1, 5, 6, 4], 2)
5
"""
from random import randint
def find_kth_largest(nums, k):
# find a random pivot
length = len(nums)
pivot = randint(0, length - 1)
nums[pivot], nums[0] = nums[0], nums[pivot]
# reorder so that left part > key, right part < key
key = nums[0]
i = 1
for j in range(1, length):
if nums[j] > key:
nums[i], nums[j] = nums[j], nums[i]
i += 1
nums[i - 1], nums[0] = nums[0], nums[i - 1]
# divide and conqure
if i == k:
return nums[i - 1]
elif i < k:
return find_kth_largest(nums[i:], k - i)
else:
return find_kth_largest(nums[:i - 1], k)
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
7d17cbaddef7f2dad0a85adad69a2d838c7f2936 | wp-lai/xpython | /code/int2binary.py | 1,431 | 4.1875 | 4 | """
Task:
Converting decimal numbers to binary numbers
>>> convert_to_binary(25)
'0b11001'
>>> convert_to_binary(233)
'0b11101001'
>>> convert_to_binary(42)
'0b101010'
>>> convert_to_binary(0)
'0b0'
>>> convert_to_binary(1)
'0b1'
"""
# Solution 1:
# keep dividing by 2, store the remainder in a stack
# read in reverse order
def convert_to_binary(number):
if number == 0:
return '0b0'
stack = []
while number:
stack.append(number % 2)
number = number // 2
binary_str = "0b"
while stack:
binary_str += str(stack.pop())
return binary_str
# Solution 2: using built-in function bin
def convert_to_binary(number):
return bin(number)
# Solution 3: using string formatting
def convert_to_binary(number):
return '0b{:b}'.format(number)
# Solution 4: using bitwise operation
def convert_to_binary(number):
if number == 0:
return '0b0'
stack = []
while number:
stack.append(number & 1) # append last bit
number = number >> 1 # remove last bit
binary_str = "0b"
while stack:
binary_str += str(stack.pop())
return binary_str
# Solution 5: using recursion
def convert_to_binary(number):
digit = "01"
if number < 2:
return "0b" + digit[number]
else:
return convert_to_binary(number // 2) + digit[number % 2]
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
c65b02fc056b996dacd941e299fe558d47785d6d | erinnlebaron3/python | /partitionstr.py | 2,573 | 4.78125 | 5 | # partition function works in Python is it's going to look inside the string for whatever you pass in as the argument.
# once it finds that it then partitions the entire string and separates it into three elements and so it is going to take python and it is going to be the first element.
# whenever you call partition and you perform assignment like we're doing here. It actually returns what's called a tuple collection.
# essentially what it's allowing us to do is it means that it's going to break what used to be a string which was one object into three objects.
# It's going to break it into the first the second and the third.
# very popular Python convention for whenever you have values that you do not want to use the best way to represent those is with an underscore.
# So this is not a required syntax it is simply a best practice in the Python community
heading = "Python: An Introduction"
header, _, subheader = heading.partition(': ')
print(header)
print(subheader)
answer = Python
An Introduction
# Python is whenever you have some type of situation where it looks like this where we have some elements that we want.
# But then we may have some elements that we don't care about such as what we're trying to pull out so we don't want to care about this colon
# we don't want to worry about getting rid of it.
# We simply want to say that that existed in the string but we don't need it for everything we're going to do after that.
# ability to clean it up and pull out the contents that you want and leave the things you don't want partitions are a great way of doing it
# and other developers when they come in they look at your code or when you go back and
# you look at your program months or years later when you see this underscore you'll understand that it means that whatever gets piped into that value is a throwaway value.
heading = "Python: An Introduction"
header, _, subheader = heading.partition(': ')
print(header)
print(_)
print(subheader)
answer = Python:
An Introduction
# Now once again this is simply a python convention. It is not a syntactic rule
heading = "Python: An Introduction"
first, second, third = heading.partition(': ')
print (first)
print(second)
print(third)
answer = Python:
An Introduction
# important component to remember whenever you're working with partition is that it breaks whatever you pass
# the colon is considered best practice
# EXAMPLE
fullname = "Erinn Ragan LeBaron"
firstname, _, lastname = fullname.partition('Ragan ')
print(firstname)
print(lastname)
answer = Erinn LeBaron | true |
dd552daf2cf44e1a08733c54e31204750afc4f43 | erinnlebaron3/python | /List.py | 2,563 | 4.875 | 5 | # like an array. It is a collection of values and that collection can be added to. You can remove items. You can query elements inside of it.
# Every time that you want a new database query what it's going to do is it's going to look at its set of data structures and it's going to go and it's going to put them in that.
# in the case of a list you're going to have to know how to loop through
# this is now no longer just a set of strings what we have here is actually a true data structure we have a list of these string names which would be
# like what we'd get if we queried a database with users.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
answer = ['Kristine', 'Tiffany', 'Jordan']
# add to this list
# to add the string Anthony and I want to make this a new element at the list it goes at the very front I pass in the index.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(0, 'Anthony')
print(users)
answer =
['Kristine', 'Tiffany', 'Jordan']
['Anthony', 'Kristine', 'Tiffany', 'Jordan']
# add element to list
# replace and assign elements
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
answer =
['Kristine', 'Tiffany', 'Jordan']
['Kristine', 'Anthony', 'Tiffany', 'Jordan']
['Kristine', 'Anthony', 'Tiffany', 'Jordan', 'Ian']
# square brackets and hit return you can see this last element is what gets returned. Now, this is a very key thing to understand here.
# Each one of these other times were printed this out. Notice how it had the brackets around the entire collection of data. What that means is that these are still lists.
# So each one of these is a list object which means that as Python looks at it that you can only call the types of functions that are available to the list data type.
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
print(users[2])
answer = Tiffany
# change name
"""
User Database Query
Kristine
Tiffany
Jordan
"""
users = ['Kristine', 'Tiffany', 'Jordan']
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
print(users[2])
users[4] = 'Braden'
print(users)
answer =
['Kristine', 'Anthony', 'Tiffany', 'Jordan', 'Braden'] | true |
9673ae62285d1caf5117a936bb1e05b7699a76a6 | erinnlebaron3/python | /PackageProject.py | 2,385 | 4.4375 | 4 | # will help you on the entire course capstone project
# Technically you have learned everything that you need to know in order to build out this project.
# helps to be familiar with some of the libraries that can make your life a little bit easier and
# make your code more straightforward to implement
# web scraper
# what it is going to do is go out to a Web site and it is going to go and extract components from
# that site so that you can use them, you can bring them into your own program.
# so you need to bypass the entire concept of an API
# http://www.dailysmarty.com/topics/python
# to be able to build is a program that comes to this url and then scrapes the code from this.
# leverage the requests library you're going to be able to call the url directly and then get access to all content.
'http://www.dailysmarty.com/posts/how-to-implement-fizzbuzz-in-python'
"How to Implement FizzBuzz in Python"
"""
Libraries:
-requests
-inflection
-beautifulsoup
pip install requests
pip install inflection
pip install beautifulsoup4
"""
# go to pure web page daily smarty
# program goes to url and scrapes the code from this
# leverage requests to get url directly
# select all links that go to posts
# copy link address
# right-click on this and click copy link address right here let me open up in a text editor say vim project.py
# and so I'm going to paste in right here what that url looks, and so you are going to get access to this.
# only pull out the links that are related to posts.
# only the ones that go right to a post
# take link and convert link into page title
# build function takes title text in url and make a string with caps and spaces
# final output should look like different lists of titles with "" around with caps and spacing
import requests
from bs4 import BeautifulSoup
from inflection import titleize
def title_generator(links):
titles = []
def post_formatter(url):
if 'posts' in url:
url = url.split('/')[-1]
url = url.replace('-', ' ')
url = titleize(url)
titles.append(url)
for link in links:
post_formatter(link["href"])
return titles
r = requests.get('http://www.dailysmarty.com/topics/python')
soup = BeautifulSoup(r.text, 'html.parser')
links = soup.find_all('a')
titles = title_generator(links)
for title in titles:
print(title) | true |
077bbfec6567508594cadabda71238de6829b41c | erinnlebaron3/python | /NegativeIndexStr.py | 777 | 4.15625 | 4 | # In review the first value here is zero. The next one is one and it counts all the way up in successive values.
# However if you want to get to the very back and you actually want to work backwards then we can work with negative index
sentence = 'The quick brown fox jumped over the lazy dog'
print(sentence[-1])
answer = g
# -3 and it's going to print out the O from dog and we could just keep going and grab our values in this negative index
# kind of manner that is helpful but that will only allow us to grab a single value.
sentence = 'The quick brown fox jumped over the lazy dog'
print(sentence[-4:])
answer = dog
# remember whenever we pass in a colon and we leave the rest of the argument blank then it's going to go to the very end of the string.
| true |
ad51a4b6182415c29a404f0457b9d168f2ced94d | erinnlebaron3/python | /decimalVSfloat.py | 2,791 | 4.46875 | 4 | # in python all decimals are floating numbers unless decimal is called
# you can create a decimal is to copy decimal it has to be all like this with it titled with the capital D and decimal spelled out and then because it's a
# function we're going to call decimal.
# when it comes to anything that is finance related or scientific or where the level of precision is incredibly important then it's a good idea to bring in the decimal class
# is a very important caveat when working with decimals and that is if you want to perform advanced calculations that need to be very precise than using the
# floating point number is not going to be your best option.
# to import decimal we say import the decimal library and then say from decimal
from decimal import Decimal
# Float
product_cost = 88.40
comission_rate = 0.08
qty = 450
product_cost += (comission_rate * product_cost)
print(product_cost * qty)
answer = 42962.4
from decimal import Decimal
product_cost = 88.40
commission_rate = 0.08
qty = 450
product_cost += (commission_rate * product_cost)
print(product_cost * qty) # 42962.4
product_cost = Decimal(88.40)
commission_rate = Decimal(0.08)
qty = 450
product_cost += (commission_rate * product_cost)
print(product_cost * qty) # 42962.40000000000282883716451
# CONVERTING BETWEEN INTEGER, FLOAT, DECIMAL, AND COMPLEX NUMBER DATA
# Float
# keyword is float and I can say quantity
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(float(qty))
anwer = 450.0
# INTEGER
# gives us similar behavior to how the floor division computation works where even though 88.8 is closer to 89 all that
# essentially it's doing is it's just taking the floating point variable and just throwing it away.
# if you are converting these values it doesn't round it to the Close's hole number. It simply takes whatever integer value is there and it just keeps that and ignores the rest.
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(int(product_cost))
answer = 88
# DECIMAL
# remember to import decimal we say from decimal import this decimal
from decimal import Decimal
from decimal import Decimal
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(Decimal(product_cost))
answer = 88.790232012122200
# COMMISION RATE
# say complex and this is going to give us the scientific notation for commission rate
# scientific notation in parentheses and this actually because it returns in parens this is giving you a complex object that you can work with.
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(complex(commission_rate))
from decimal import Decimal
product_cost = 88.80
commission_rate = 0.08
qty = 450
print(int(product_cost))
print(float(qty))
print(Decimal(product_cost))
print(complex(commission_rate)) | true |
f3566a6b295b511718e3fac82156d6bad58b52a0 | erinnlebaron3/python | /FuncConfigFallBck.py | 1,356 | 4.40625 | 4 | # syntax for doing is by performing something like this where I say teams and then put in the name of the key and then that is going to perform the query.
# want to have a featured team so I can say featured team store this in a variable.
teams = {
"astros": ["Altuve", "Correa", "Bregman"],
"angels": ["Trout", "Pujols"],
"yankees": ["Judge", "Stanton"],
"red sox" : ['Price', 'Bets']
}
featured_team = teams['astros']
print(featured_team)
answer = ['Altuve', 'Correa', 'Bregman']
# fallback - that's what we can do with the get function inside of Python dictionaries
# make sure that you are catching any kind of scenarios that have a situation like this where we're looking up a key that may or may not exist
# and you want to have some type of fallback and so this is going to give you instant feedback to let you know that what you tried to look up
# doesn't actually exist inside of the team's dictionary.
# GET
# get takes two arguments
# The first is a key we're looking for.
# gives us the abitlity to have multiple checks when using look ups in Python automaticaly
teams = {
"astros": ["Altuve", "Correa", "Bregman"],
"angels": ["Trout", "Pujols"],
"yankees": ["Judge", "Stanton"],
"red sox" : ['Price', 'Bets']
}
featured_team = teams.get('mets', 'No featured team')
print(featured_team)
answer = No featured team
| true |
023d47ee8dced82d994b1660c359715d72761482 | erinnlebaron3/python | /lenNegIndex.py | 1,462 | 4.46875 | 4 | # LENGTH
# the length function and it's actually called the L E N which is short for length
# this is going to give you the count for the full number of elements in a list
# there is a difference between length and index
# LENGTH
# remember the counter starts and the index starts at 0.
# even though we have four elements inside the last index item here is actually going to be three
# how we could get a count of all of the elements in the list.
tags = ['python', 'development', 'tutorials', 'code']
number_of_tags = len(tags)
print(number_of_tags)
answer = 4
# MOST OF THE LISTS YOU WORK WITH WONT BE HARD CODED
# how you could get the value from the last item even if you don't know what its index was by using a negative index.
tags = ['python', 'development', 'tutorials', 'code']
last_item = tags[-1]
print(last_item)
answer = code
# how to grab index
# once you do have the value for one of your elements you can pass it to the index function right here and then it will go traverse
# through the entire list and return the index of that value.
tags = ['python', 'development', 'tutorials', 'code']
index_of_last_item = tags.index(last_itme)
print(index_of_last_item)
answer = 3
# ALL CODE WITH ANSWERS
tags = ['python', 'development', 'tutorials', 'code']
number_of_tags = len(tags)
last_item = tags[-1]
index_of_last_item = tags.index(last_item)
print(number_of_tags)
print(last_item)
print(index_of_last_item)
answers =
4
code
3 | true |
6a88efb4a656dfda208f49f561d287175734e755 | erinnlebaron3/python | /FilesinPy.py/Create&WriteFile.py | 1,659 | 4.625 | 5 | # very common use case for working with the files system is to log values
# gonna see how we can create a file, and then add it to it.
# create a variable here where I'm going to open up a file.
# I'm going to show you here in the console that if I type ls, you can see we do not have a file called logger.
# function open is going to allow us to open or create a file.
# Python works is if you call open, if it finds a file then it will open up that file.
# you can perform whatever you need to inside of it. If it does not find a file with that name,
# then it will automatically create it.
# regular text file, and it takes another argument which is the way that we want to open it up.
# set of permissions that we want our program to follow. It takes in a string
# write is a function inside of the file library in Python a
# to close the file off. So I'm going to say file_builder.close() and then we're going to call the close function.
# string literal interpolation I'll say {i + 1}.
# right after the curly braces pass in \n,
# syntax where you are opening a file and then you're just calling right on it, it is not going to care whatsoever about
# the contents of the file previously.
# This is what you would do if you want to have almost like a temp type of logger
# truly remember from this guide is that if you use this syntax, where you're opening a file and you're simply
# calling right you will overwrite all of the content in that file.
file_builder = open("logger.txt", "w+")
for i in range(100):
file_builder.write(f"I'm on line {i + 1}\n")
# file_builder.write("Hey, I'm in a file!")
file_builder.close()
| true |
0ae57c234dc5a9daa688426e8c4953980f510f65 | erinnlebaron3/python | /Slice2StoreSlice.py | 2,968 | 4.78125 | 5 | # here are times where you may not know or you may not want to hard code in this slice range.
# And so in cases like that Python actually has a special class called slice which we can call and store whatever these ranges we want
# biggest reasons why you'd ever use this slice class over using just this explicit version slice(1, 4, 2) is whenever you want to define
# your ranges and your steps and those kinds of elements and you want to store them in a variable and then simply call them later on and or
# also another opportunity where this would be a very good fit is if you're maybe calling this on different datasets.
# SLICE
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
# print(tags[:2])
slice_obj = slice(2)
print(tags[slice_obj])
answer = ['python', 'development']
# similar when working with explicet slice
# working with an explicit slice and when we passed in a range the only difference is that
print(tags[:2])
# the key differences here is we can call store this method inside of another object inside
# of a variable and then we can call that anywhere in the program.
# so this is a very nice way of being able to store your slice so that you can reuse it on any other kinds of lists.
print(tags[slice_obj])
# with slice, you can see there are three potential arguments inside of this object and the first one is our start point. So we're going to have a start.
# going to have an end and then we're going to have a step which if you remember exactly with what we had with ranges and with these explicit type of
# slices we could pass in say [2:4:2]. And then this is going to bring us every other element because the last 2 is our step. This first 2 is our start
# and this 4 is our stop or this is our endpoint.
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
# print(tags[2:4:2])
slice_obj = slice(2)
print(slice_obj)
print(tags[slice_obj])
answer = slice(None, 2, None)['python', 'development']
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(tags[slice_obj])
answer = ['development', 'code']['development', 'code']
# working on a machine learning algorithm and you want to know in some other part of the program where the range started where it stopped and what
# the step interval was.
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(slice_obj.start)
print(slice_obj.stop)
print(slice_obj.step)
print(tags[slice_obj])
answer =
['development', 'code']
14
2
['development', 'code']
tags = [
'python',
'development',
'tutorials',
'code',
'programming',
]
print(tags[1:4:2])
slice_obj = slice(1, 4, 2)
print(slice_obj.start)
print(slice_obj.stop)
print(slice_obj.step)
print(tags[slice_obj])
answer =
['development', 'code']
14
2
['development', 'code'] | true |
987adf3d6c77ee903e0cf74b398c8cfdcb2d54f3 | jibinsamreji/Python | /MIni_Projects/carGameBody.py | 964 | 4.15625 | 4 | print("Welcome player! Type 'help' for more options..!")
user_input = input(">")
i = 0
start = False
stop = False
while user_input.upper() == "HELP":
if i < 1:
print("""
start - to start the car
stop - to stop the car
quit - to exit""")
i += 1
game_option = input(">").upper()
if game_option == 'START':
if not start:
print("Car started....Ready to go!")
start = True
stop = False
else:
print("Car already started....!")
elif game_option == 'STOP':
if not stop:
print("Car stopping...Car stopped!")
stop = True
start = False
else:
print("Car already stopped....!")
elif game_option == 'QUIT':
print("Quitting.....")
break
else:
print("Not a valid choice..! Please select an option from the above!")
else:
print("I don't understand that..")
| true |
3d8b2938eed4cd2d299218d4dd787d80518e8154 | victorsibanda/python-basics | /102_python_data_types.py | 1,696 | 4.59375 | 5 | #Strings
#Text and Characters
#Syntax
#"" and ''
#Define a string
#Anything that is text is a string
my_string = 'Hey I am a cool string B)'
print(my_string)
type(my_string)
#Concatenation
joint_string = 'Hey I am another' + ' cool string, ' + my_string
print (joint_string)
#example two of concatenation
name = 'Mohamed'
welcome_text = 'Welcome to SPARRRRRRRRRRRTTTTTTTAAAAAAAAA'
print (welcome_text+' '+name)
print (welcome_text,name) #overloading the sprint
#Interpolation
#inserting a sting inside another string
#or running python inside a string
print (f'Welcome {name} to class 54, we are Contested Terrain ')
#print (f'Welcome {input("What is your name")} to class 54, we are Contested Terrain ')
print ('Welcome to class 54 , we are Contested Terrain'.format(name))
#Useful methods
# A method is a funtion that belongs to a specific data type.
#e.g it would not make sense to capitalize integers
example_long_str = ' Hello , This is a badly formated test?'
print (example_long_str)
#Remove trailling white spaces
print (example_long_str.strip())
#Make it lowr case
print(example_long_str.lower())
#Make it upper case
print(example_long_str.upper())
#First character capitalised
print(example_long_str.strip().capitalize())
print(example_long_str.strip().title())
#Change the question mark into an exclamation mark
print(example_long_str.strip().replace('?','!') )
#chainsome methods and :
# Remove trailing white spaces
#make it nicely formatted with only first letter capitalised
#print(example_long_str.strip().replace('?','!').capitalize().replace('badly','well')
#create a list with individual words
print(example_long_str.strip().split())
| true |
faa0ffceb30031674446ed24efdb4e6085fa9873 | victorsibanda/python-basics | /101_python_variables_print_type.py | 531 | 4.1875 | 4 | # Variables
# it is like a box, you give it a name, and put stuff inside
book = 'Rich dad poor dad'
## Print function
#Outputs content to the terminal (makes it visible)
print(book)
# Type function
#Allows us to check data types
data_type_of_book = type(book)
print (data_type_of_book)
#input() - prompt for user input and you can add a string to the arguement so it prints before capturing the input
input ('this gets printed before capturing your input')
##Conventions
# lower case for variable naming with under score | true |
d6320818cdbf2b26bcffb410c1cad8e27ef9477f | devionb/MIM_Software_code_sample | /Part_A.py | 642 | 4.375 | 4 | # Devion Buchynsky
# Part A - Reverse the string if its length is a multiple of 4.
# multiples of 4: 4,8,12,16......
multiple_of_4_string_letter = 'abcd'
multiple_of_5_string_letter = 'abcde'
print('Before function is ran.')
print(multiple_of_4_string_letter)
print(multiple_of_5_string_letter)
def reverse_string(string_1):
if len(string_1) % 4 == 0: # if the string is a % of 4 then it will reverse the string, if not it will not do anything.
return ''.join(reversed(string_1))
return string_1
print('After function is ran.')
print(reverse_string(multiple_of_4_string_letter))
print(reverse_string(multiple_of_5_string_letter))
| true |
064a088d379dc1010eaa365e9857615bcd8f4d56 | diallog/PY4E | /assignment5.2/assignment5.2_noIntTest.py | 1,133 | 4.1875 | 4 | # Assignment 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
# Initialize variables
smallest = None # variable holds current smallest value
largest = None # variable holds current largest value
newNumber = 0 # variable holds new input for testing
intNewNumber = 0 # new input converted to integer
request = True
# Main program - build the list from user input
while request is True:
newNumber = input('Give a number or "done": ')
if newNumber == 'done':
request = False
else:
try:
intNewNumber = int(newNumber)
except:
print('''Invalid input''')
continue
if largest is None or intNewNumber > largest:
largest = intNewNumber
elif smallest is None or intNewNumber < smallest:
smallest = intNewNumber
continue
# Output
print('Maximum is', largest)
print('Minimum is', smallest)
| true |
4b0ec224525c1b9e584710cbe2456aa7c2f9000d | diallog/PY4E | /assignment2.3/assignment2.3.py | 606 | 4.21875 | 4 | # This assignment will obtain two pieces of data from the user and perform a calculation.
# This script begins with a hint from the course...but lets do a little over-achievement.
print("Alright, let's do our first calculation in Python using information obtained from the user.\r")
# This first line is provided for you
hrs = input("Please enter the number of hours worked: ")
# hrs = float(hrs)
rate = input("Thank you. Now enter the rate ($/hr): ")
# rate = float(rate)
# calculation...
pay = float(hrs) * float(rate)
# output
# print("Pay: " + str(pay))
# alternative approach
print("Pay:", pay)
| true |
7c023a7743c6f76a6f4c5b2bd46535ccae3d2efe | priyanshu3666/my-lab-practice-codes | /if_else_1.py | 237 | 4.21875 | 4 | #Program started
num = int(input("Enter a number")) #input taking from user
if (num%2) == 0 : #logic start
print("The inputted muber",num," is Even")
else :
print("The inputted muber",num," is Odd") #logic ends
#Program Ends
| true |
1f3007154c8734dce197638aae123261f4fd3eca | iamdoublewei/Leetcode | /Python3/125. Valid Palindrome.py | 983 | 4.28125 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
#Original
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.replace(" ", "")
if not s: return True
res = ''
s = list(s.lower())
for cur in s:
if cur >='a' and cur <= 'z' or cur >= '0' and cur <= '9':
res += cur
return res == ''.join(reversed(res))
#Improved:
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
res = ''
for cur in s.lower():
if cur.isalnum():
res += cur
return res == ''.join(reversed(res))
| true |
336f4764f1208ed1e8cea45946a6e097187ec098 | iamdoublewei/Leetcode | /Python3/1507. Reformat Date.py | 1,545 | 4.375 | 4 | '''
Given a date string in the form Day Month Year, where:
Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
Year is in the range [1900, 2100].
Convert the date string to the format YYYY-MM-DD, where:
YYYY denotes the 4 digit year.
MM denotes the 2 digit month.
DD denotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
The given dates are guaranteed to be valid, so no error handling is necessary.
'''
class Solution:
def reformatDate(self, date: str) -> str:
dic = {'1st':'01', '2nd':'02', '3rd':'03', '4th':'04', '5th':'05', '6th':'06', '7th':'07',
'8th':'08', '9th':'09', '10th':'10', '11th':'11', '12th':'12', '13th':'13', '14th':'14',
'15th':'15', '16th':'16', '17th':'17', '18th':'18', '19th':'19', '20th':'20', '21st':'21',
'22nd':'22', '23rd':'23', '24th':'24', '25th':'25', '26th':'26', '27th':'27', '28th':'28',
'29th':'29', '30th':'30', '31st':'31', 'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04',
'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'}
date = date.split()
date[0] = dic[date[0]]
date[1] = dic[date[1]]
return '-'.join(date[::-1]) | true |
38e0976de0b8376345610a411550df8ca5639293 | iamdoublewei/Leetcode | /Python3/680. Valid Palindrome II.py | 1,005 | 4.15625 | 4 | '''
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class Solution:
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def isPalindrome(s, i, j):
while j >= i:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
if len(s) <= 1:
return True
i, j = 0, len(s) - 1
while j >= i:
if i == j:
break
if s[i] != s[j]:
return isPalindrome(s, i + 1, j) or isPalindrome(s, i, j - 1)
i += 1
j -= 1
return True
| true |
84a99ce38f0a9fa7e7456be2ec28f70c54b8d41d | iamdoublewei/Leetcode | /Python3/849. Maximize Distance to Closest Person.py | 1,464 | 4.25 | 4 | '''
In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return that maximum distance to closest person.
Example 1:
Input: [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
Example 2:
Input: [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat, the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
Note:
1 <= seats.length <= 20000
seats contains only 0s or 1s, at least one 0, and at least one 1.
'''
class Solution:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
zeros, mx = 0, 0
for i, v in enumerate(seats):
if not v:
zeros += 1
if not i:
mx = -1
else:
if mx == -1:
mx = zeros
else:
mx = max(mx, (zeros + 1) // 2)
zeros = 0
if zeros:
mx = max(mx, zeros)
return mx
| true |
98ceacd32d0924643b4f6caa745e67c3f754951e | iamdoublewei/Leetcode | /Python3/417. Pacific Atlantic Water Flow.py | 2,184 | 4.40625 | 4 | '''
There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
Return a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.
Example 1:
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Example 2:
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
Constraints:
m == heights.length
n == heights[r].length
1 <= m, n <= 200
0 <= heights[r][c] <= 105
'''
class Solution:
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
row = len(heights)
col = len(heights[0])
pac = set()
alt = set()
res = []
def search(r, c, h, ocean):
if r < 0 or c < 0 or r >= row or c >= col or (r, c) in ocean or heights[r][c] < h:
return
ocean.add((r, c))
search(r + 1, c, heights[r][c], ocean)
search(r - 1, c, heights[r][c], ocean)
search(r, c + 1, heights[r][c], ocean)
search(r, c - 1, heights[r][c], ocean)
for i in range(col):
search(0, i, 0, pac)
search(row - 1, i, 0, alt)
for i in range(0, row):
search(i, 0, 0, pac)
search(i, col - 1, 0, alt)
for i in pac:
if i in alt:
res.append(list(i))
return res
| true |
06603409c216e418a50c655532a82a17429f040c | iamdoublewei/Leetcode | /Python3/2000. Reverse Prefix of Word.py | 1,366 | 4.40625 | 4 | '''
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".
Return the resulting string.
Example 1:
Input: word = "abcdefd", ch = "d"
Output: "dcbaefd"
Explanation: The first occurrence of "d" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
Example 2:
Input: word = "xyxzxe", ch = "z"
Output: "zxyxxe"
Explanation: The first and only occurrence of "z" is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
Example 3:
Input: word = "abcd", ch = "z"
Output: "abcd"
Explanation: "z" does not exist in word.
You should not do any reverse operation, the resulting string is "abcd".
Constraints:
1 <= word.length <= 250
word consists of lowercase English letters.
ch is a lowercase English letter.
'''
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
for i in range(len(word)):
if word[i] == ch:
return word[:i + 1][::-1] + word[i + 1:]
return word | true |
e3b81970fb6473a49d9a480991999a110605927d | kirakrishnan/krishnan_aravind_coding_challenge | /TLS/turtle_simulator.py | 2,218 | 4.125 | 4 | import turtle
import time
def setup_simulator_window():
"""
set up a window with default settings to draw Traffic Lights
:param:
:return t: turtle object
"""
t = turtle.Turtle()
t.speed(0)
t.hideturtle()
screen = turtle.Screen()
screen.screensize()
screen.setup(width = 1.0, height = 1.0)
return t
def draw_circle(t):
"""
Draws a Traffic Light circle
:param:
:return:
"""
t.begin_fill()
t.circle(100)
t.end_fill()
def set_pos(x, y, t):
"""
Set up the position for next circle
:param x: x axis position
:param y: y axis position
:param t: turtle object
:return:
"""
t.setpos(x,y)
def fill_circle(x,y,current_light, light, t):
"""
Set up the position for Traffic Light and fills it
:param x: x axis position
:param y: y axis position
:param current_light: current light that should be displayed
:param light: corresponding light for this circle
:param t: turtle object
:return:
"""
set_pos(x,y,t)
if(current_light == light):
t.fillcolor(current_light)
else:
t.fillcolor('white')
draw_circle(t)
def switch_light(current_light):
"""
Generates the next light in sequence that should be displayed
:param current_light: current light that should be displayed
:return next_light: next light that should be displayed
"""
if(current_light == "green"):
next_light = "yellow"
elif(current_light == "yellow"):
next_light = "red"
elif(current_light == "red"):
next_light = "green"
return next_light
def open_simulator(times):
"""
Generates a simulator window to display traffic lights and
iterates thru each light as per the given transition times
:param times: corresponding transition times for each lights
"""
t = setup_simulator_window()
current_light = "green"
while(True):
fill_circle(0, 220, current_light, "red", t)
fill_circle(0, 0, current_light, "yellow", t)
fill_circle(0, -220, current_light, "green", t)
time.sleep(times[current_light])
current_light = switch_light(current_light)
| true |
91c081afcb0ca54068bd1a38049c3da5ddd73c6a | evantarrell/AdventOfCode | /2020/Day 2/day2.py | 1,622 | 4.21875 | 4 | # Advent of Code 2020 - Day 2: Password Philosophy
# Part 1, read input file with each line containing the password policy and password. Find how many passwords are valid based on their policies
# Ex: 1-3 a: abcde is valid as there is 1 a in abcde
# but 3-7 l: ablleiso is not valid as there are only 2 l's in ablleiso
import re
regexPattern = '(\\d+)-(\\d+) (\\w): (\\w+)'
validPasswordCount = 0
with open('input.txt', 'r') as input:
for line in input:
match = re.search(regexPattern, line)
if match is not None:
lowerLimit = int(match.group(1))
upperLimit = int(match.group(2))
letter = match.group(3)
password = match.group(4)
letterCount = password.count(letter)
if letterCount >= lowerLimit and letterCount <= upperLimit:
validPasswordCount += 1
print('Part 1: There were ' + str(validPasswordCount) + ' valid passwords')
# Part 2, same but the password policy meaning is different.
# Instead of counts it denotes two positions for the given letter to occur in, base 1 indexing. The letter must occur in exactly one of the two positions, other occurrences don't matter
validPasswordCount = 0
with open('input.txt', 'r') as input:
for line in input:
match = re.search(regexPattern, line)
if match is not None:
pos1 = int(match.group(1)) - 1
pos2 = int(match.group(2)) - 1
letter = match.group(3)
password = match.group(4)
if len(password) > pos2 and (password[pos1] == letter or password[pos2] == letter) and not (password[pos1] == password[pos2]):
validPasswordCount += 1
print('Part 2: There were ' + str(validPasswordCount) + ' valid passwords')
| true |
684f9a65b6c72684f2355958751ae8d4b1de97a5 | kaushikram29/python1 | /character.py | 220 | 4.21875 | 4 | X=input("Enter your character")
if((X>="a" and X<="z) or (X>="A" and X<="Z")):
print(X, "it is an alphabet")
elif ((X>=0 and Z<=9)):
print(X ,"it is a number or digit")
else:
print(X,"it is not alphabet or digit")
| true |
14a4ed8730578aa3a1fcf7bf32b3096835ac221c | Clearymac/Integer-division-and-list | /task 2.py | 864 | 4.28125 | 4 | #LIST RETARRD
list = ['Evi', 'Madeleine', 'Cool guy', 'Kelsey', 'Cayden', 'Hayley', 'Darian']
#sorts and prints the list
list.sort()
print('Sorted list:', list)
#asks the user to input their name
name = input("What is your name? ")
name = name.title()
#checks if name is in list and gives option to add to list
if name in list:
print("Oh senpai! that name is already in the list asdahasdhahkshldgakshd uwu")
bruh = input("would you like to add your name or replace your name in the list or nothing? ")
bruh = bruh.lower()
if bruh == "add":
list.append(name)
print(list)
elif bruh == "replace":
replace_name = input("What of the following names would you like to replace?\n{}\n".format(list))
list = list.replace(replace_name, name)
print(list)
elif bruh == "nothing":
print("poopoo stinker")
else:
print("what are you on?")
| true |
451af1ea328f3331078e6271fb0a7dcb24e8c2fd | mentalclear/autobots-fastapi-class | /typing_playground/funcs/random_stuff.py | 485 | 4.1875 | 4 | def greeting(name: str) -> str:
""" This function expects to have argument name of type string"""
return 'Hello ' + name
print(greeting('Tester'))
# A type alias is defined by assigning the type to the alias. In this example,
# Vector and list[float] will be treated as interchangeable synonyms
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector) | true |
609b61bab4602df7434e12d207ae1ff5862534cb | ChristyLeung/Python_Green | /Green/5.3.1-2 voting.py | 487 | 4.1875 | 4 | # 5.3
# 5.3.1
if conditional_test:
do something
age = 19
if age >= 18:
print("You are old enough to vote!")
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
# 5.3.2
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote!")
print("Please register to vote as soon as you turn 18!")
| true |
1f8acbbc0af62fdf18d8408eade076fce2d59931 | KShaz/Machine-Learning-Basics | /python code/ANN 3-1 Supervised Simoid training.py | 1,725 | 4.125 | 4 | # https://iamtrask.github.io/2015/07/12/basic-python-network/
#X Input dataset matrix where each row is a training example
#y Output dataset matrix where each row is a training example
#l0 First Layer of the Network, specified by the input data
#l1 Second Layer of the Network, otherwise known as the hidden layer
#Syn0 First layer of weights, Synapse 0, connecting l0 to l1.
# 3 inputs, 1 output
# SUPERVISED neural network using non linear Sigmoid feedback
import numpy as np
# sigmoid function
# this nonlinearity maps a function called a "sigmoid"
# If the sigmoid's output is a variable "out", then the derivative is simply out * (1-out)
def nonlin(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
# input dataset
X = np.array([ [0,0,1],
[0,1,1],
[1,0,1],
[1,1,1] ]) # np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
# output dataset
y = np.array([[0,0,1,1]]).T #T is for mattrix transpose
# seed random numbers to make calculation deterministic. (1) is the sequence used for random
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1 # random=[0,1], we want weight=[-1,1], random(line,column), syn0 is vertical
for iter in range(10000):
# forward propagation
l0 = X
l1 = nonlin(np.dot(l0,syn0)) #l1 = nonlin (l0 x syn0), matrix-matrix multiplication
# how much did we miss?
l1_error = y - l1
# multiply how much we missed by the
# slope of the sigmoid at the values in l1
l1_delta = l1_error * nonlin(l1,True)
# update weights
syn0 += np.dot(l0.T,l1_delta)
print ("Output After Training:")
print (l1)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.