blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9e9a035528e322e167ada1adb567c8052fc35b4e | tony-andreev94/Python-Fundamentals | /01. Functions/04. Odd and Even Sum.py | 676 | 4.1875 | 4 | # You will receive a single number. You have to write a function that returns the sum of all even and all odd digits
# from that number as a single string like in the examples below.
#
# Input Output
# 1000435 Odd sum = 9, Even sum = 4
# 3495892137259234 Odd sum = 54, Even sum = 22
def odd_even_sum_func(input_str):
odd_sum = 0
even_sum = 0
for each_char in input_str:
if int(each_char) % 2 == 0:
even_sum += int(each_char)
else:
odd_sum += int(each_char)
print(f"Odd sum = {odd_sum}, Even sum = {even_sum}")
num = int(input())
num_as_str = str(num)
odd_even_sum_func(num_as_str)
|
e6036913f6445e433aa539a106c0193c871922d5 | philips-ni/ecfs | /leetcode/083_remove_duplicates_linklist/python/remove_duplicates_linklist.py | 1,039 | 3.515625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def initList(list):
if len(list) == 0:
return None
head = ListNode(list[0])
prevNode = head
for i in list[1:]:
currentNode = ListNode(i)
prevNode.next = currentNode
prevNode = currentNode
return head
def dump(head):
if head == None:
print "None"
return
iter = head
while iter.next:
print "%s ->" % iter.val
iter = iter.next
print "%s" % iter.val
class Solution(object):
def deleteDuplicates(self, head):
if head == None:
return head
if head.next == None:
return head
prevNode = head
currNode = head.next
while currNode != None:
if currNode.val == prevNode.val:
currNode = currNode.next
prevNode.next = currNode
else:
prevNode = currNode
currNode = currNode.next
return head
|
e0b76f270ed551ad06e1eec383aaada7600213a5 | davidalejandro1223/Introduccion-ciencia-datos | /Numpy/Taller 1 - Intro python/taller1-Ciencias.py | 503 | 3.71875 | 4 | import random
num = (random.randrange(0,99))
print (num)
intents = 0
while intents<10:
inp = int(input('Ingrese tu numero\n'))
if inp == num:
print('Has adivinado el numero')
print('Tu puntaje fue: ' + str((10-intents)))
break
elif inp < num:
print('El numero a adivinar es mayor')
intents+=1
elif inp > num:
print('El numero a adivinar es menor')
intents+=1
else:
print('no has adivinado, el numero es:' + str(num))
|
064cf4d753e9def732842f472231e1d3a4567431 | dineshkumar12004/Interview-Experience | /Accenture/PermutationCount.py | 188 | 3.890625 | 4 | # permutation count of a string
def permute(string):
if len(string) == 1:
return 1
else:
return len(string) * permute(string[1:])
ans = permute('abc')
print(ans)
|
c62ce11a1b4b6bf036b2f6279b6798f45947e0c6 | YuLili-git/leetcode_offer | /剑指 Offer 07. 重建二叉树.py | 1,088 | 3.796875 | 4 | #输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
#假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
#示例 1:
#Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
#Output: [3,9,20,null,null,15,7]
#示例 2:
#Input: preorder = [-1], inorder = [-1]
#Output: [-1]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def recur(root, left, right):
if left > right:
return
node = TreeNode(preorder[root])
i = dic[preorder[root]]
node.left = recur(root + 1, left, i - 1)
node.right = recur(i - left + root + 1, i + 1, right)
return node
dic = {}
preorder = preorder
for i in range(len(inorder)):
dic[inorder[i]] = i
return recur(0, 0, len(inorder) - 1)
|
68db601ad5ab20fa79e87dfadc8fe20d912e1387 | iaevan/Pybook1-solutions | /page 114.py | 234 | 3.796875 | 4 | import turtle
x = 0
y = 1
z = 0
n = 12
for i in range(n):
z = x + y
x = y
y = z
print(x)
for i in range(4):
turtle.forward(x*10)
turtle.left(90)
turtle.circle(x * 10 , 90) |
7ade29789a1dae0b128cc1120d1dfdf225ee6ae7 | Leo428/CS61A | /cats/typing.py | 10,016 | 3.78125 | 4 | """Typing test implementation"""
from utils import *
from ucb import main, interact, trace
from datetime import datetime
###########
# Phase 1 #
###########
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
index = 0
for p in paragraphs:
if select(p):
if index != k:
index += 1
else:
return p
return ''
# END PROBLEM 1
def about(topic):
"""Return a select function that returns whether a paragraph contains one
of the words in TOPIC.
>>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
'Cute Dog!'
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
'Nice pup.'
"""
assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
# BEGIN PROBLEM 2
def checker(p):
p = split(remove_punctuation(lower(p)))
for w in p:
if w in topic:
return True
return False
return checker
# END PROBLEM 2
def accuracy(typed, reference):
"""Return the accuracy (percentage of words typed correctly) of TYPED
when compared to the prefix of REFERENCE that was typed.
>>> accuracy('Cute Dog!', 'Cute Dog.')
50.0
>>> accuracy('A Cute Dog!', 'Cute Dog.')
0.0
>>> accuracy('cute Dog.', 'Cute Dog.')
50.0
>>> accuracy('Cute Dog. I say!', 'Cute Dog.')
50.0
>>> accuracy('Cute', 'Cute Dog.')
100.0
>>> accuracy('', 'Cute Dog.')
0.0
"""
typed_words = split(typed)
reference_words = split(reference)
# BEGIN PROBLEM 3
if len(typed_words) == 0:
return 0.0
else:
percent = 100.0
# index, percent = 0, 100.0
for i in range(len(typed_words)):
if i < len(reference_words):
if typed_words[i] != reference_words[i]:
percent -= (1/len(typed_words)) * 100
else:
percent -= (1/len(typed_words)) * 100
return round(percent, 2)
# END PROBLEM 3
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string."""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
return len(typed) / 5 * 60 / elapsed
# END PROBLEM 4
def autocorrect(user_word, valid_words, diff_function, limit):
"""Returns the element of VALID_WORDS that has the smallest difference
from USER_WORD. Instead returns USER_WORD if that difference is greater
than or equal to LIMIT.
"""
# BEGIN PROBLEM 5
best_fit_word, diff = user_word, -1
for candidate in valid_words:
if candidate == user_word:
return user_word
else:
current_diff = diff_function(user_word, candidate, limit)
if diff < 0 and current_diff <= limit or current_diff < diff:
best_fit_word, diff = candidate, current_diff
return best_fit_word
# END PROBLEM 5
def swap_diff(start, goal, limit):
"""A diff function for autocorrect that determines how many letters
in START need to be substituted to create GOAL, then adds the difference in
their lengths.
"""
# BEGIN PROBLEM 6
total_diff = 0
if limit < 0:
return 1
if len(start) == 0 or len(goal) == 0:
total_diff += abs(len(start) - len(goal))
else:
if start[0] == goal[0]:
if len(start) > 1 and len(goal) > 1:
total_diff += swap_diff(start[1:], goal[1:], limit)
elif len(start) == 1 and len(goal) == 1:
total_diff += 0
elif len(start) == 1:
total_diff += swap_diff("",goal[1:],limit)
elif len(goal) == 1:
total_diff += swap_diff(start[1:],"",limit)
else:
if len(start) > 1 and len(goal) > 1:
total_diff += 1 + swap_diff(start[1:], goal[1:], limit-1)
elif len(start) == 1 and len(goal) == 1:
total_diff += 1
elif len(start) == 1:
total_diff += 1 + swap_diff("",goal[1:],limit)
elif len(goal) == 1:
total_diff += 1 + swap_diff(start[1:],"",limit)
return limit + 1 if total_diff > limit else total_diff
# END PROBLEM 6
# @trace
def edit_diff(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL."""
# @trace
def add_diff(s):
index = 0
for g in goal:
if index < len(s):
if g != s[index]:
s.insert(index,g)
return 1 + edit_diff(s, goal, limit-1)
else:
s.insert(index+1, g)
return 1 + edit_diff(s, goal, limit-1)
index += 1
return 0
# @trace
def remove_diff(s):
index = 0
for g in goal: # when len(goal) >= len(start)
if index < len(s):
if g != s[index]:
s.pop(index)
return 1 + edit_diff(s, goal, limit-1)
index += 1
if len(s):
s.pop()
return 1 + edit_diff(s, goal, limit-1)
return 0
# @trace
def substitute_diff(s):
index = 0
for g in goal: # when len(goal) >= len(start)
if index < len(s):
if g != s[index]:
s[index] = g
return 1 + edit_diff(s, goal, limit-1)
index += 1
return 0
start = list(start)
goal = list(goal)
if start == goal:
return 0
if limit > len(start) + len(goal):
return edit_diff(start, goal, len(start) + len(goal))
if limit == 0:
return limit + 1
else:
diff = [d for d in [add_diff(start[:]), substitute_diff(start[:]), remove_diff(start[:])] if d != 0]
return min(diff)
def final_diff(start, goal, limit):
"""A diff function. If you implement this function, it will be used."""
assert False, 'Remove this line to use your final_diff function'
###########
# Phase 3 #
###########
def report_progress(typed, prompt, id, send):
"""Send a report of your id and progress so far to the multiplayer server."""
# BEGIN PROBLEM 8
num_correct, index = 0, 0
for t in typed:
if t == prompt[index]:
num_correct += 1
else:
break
index += 1
percent = num_correct/len(prompt)
send({'id': id, 'progress': percent})
return percent
# END PROBLEM 8
def fastest_words_report(word_times):
"""Return a text description of the fastest words typed by each player."""
fastest = fastest_words(word_times)
report = ''
for i in range(len(fastest)):
words = ','.join(fastest[i])
report += 'Player {} typed these fastest: {}\n'.format(i + 1, words)
return report
def fastest_words(word_times, margin=1e-5):
"""A list of which words each player typed fastest."""
n_players = len(word_times)
n_words = len(word_times[0]) - 1
assert all(len(times) == n_words + 1 for times in word_times)
assert margin > 0
# BEGIN PROBLEM 9
giant_list = [[] for w in word_times]
temp_list = []
# print(word_times)
for w in range(n_words+1):
for p in range(n_players):
if word(word_times[p][w]) != 'START':
temp_list += [elapsed_time(word_times[p][w])-elapsed_time(word_times[p][w-1])]
if word(word_times[p][w]) != 'START':
for t in range(n_players):
if abs(temp_list[t] - min(temp_list)) <= margin:
giant_list[t] += [word(word_times[p][w])]
temp_list = []
return giant_list
# END PROBLEM 9
def word_time(word, elapsed_time):
"""A data abstrction for the elapsed time that a player finished a word."""
return [word, elapsed_time]
def word(word_time):
"""An accessor function for the word of a word_time."""
return word_time[0]
def elapsed_time(word_time):
"""An accessor function for the elapsed time of a word_time."""
return word_time[1]
enable_multiplayer = False # Change to True when you
##########################
# Command Line Interface #
##########################
def run_typing_test(topics):
"""Measure typing speed and accuracy on the command line."""
paragraphs = lines_from_file('data/sample_paragraphs.txt')
select = lambda p: True
if topics:
select = about(topics)
i = 0
while True:
reference = choose(paragraphs, select, i)
if not reference:
print('No more paragraphs about', topics, 'are available.')
return
print('Type the following paragraph and then press enter/return.')
print('If you only type part of it, you will be scored only on that part.\n')
print(reference)
print()
start = datetime.now()
typed = input()
if not typed:
print('Goodbye.')
return
print()
elapsed = (datetime.now() - start).total_seconds()
print("Nice work!")
print('Words per minute:', wpm(typed, elapsed))
print('Accuracy: ', accuracy(typed, reference))
print('\nPress enter/return for the next paragraph or type q to quit.')
if input().strip() == 'q':
return
i += 1
@main
def run(*args):
"""Read in the command-line argument and calls corresponding functions."""
import argparse
parser = argparse.ArgumentParser(description="Typing Test")
parser.add_argument('topic', help="Topic word", nargs='*')
parser.add_argument('-t', help="Run typing test", action='store_true')
args = parser.parse_args()
if args.t:
run_typing_test(args.topic) |
6d410a16cb59af71c659766eaa78ff555e4fa09b | kozhakhmetov/PythonTasks | /Hackerrank/Easy/py-hello-world/test_main.py | 514 | 3.546875 | 4 | import main
class TestClass:
def test_1(self):
# main.input = lambda: 'some_input'
output = main.main()
assert output == 'Hello world'
def test_2(self):
# main.input = lambda: 'some_other_input'
output = main.main()
assert output == 'Hello world'
def test_3(self):
# main.input = lambda: 'some_other_input'
output = main.main()
assert output == 'Hello world'
def teardown_method(self, method):
main.input = input
|
b17957c35abbaacab1ca68e910e83e870c37491b | Deepak-Rai-1027/Probability_Python_Codes | /Conditional_Probability.py | 1,816 | 4.0625 | 4 | # Probability of an event A given another event B has already occured.
# In this case the new universe is event B (the new sample space omega)
# Main objective is to calculate the portion of A in event B.
# Example
# Calculate the probability a student gets an A (80% +) in math, given they miss 10 or more classes.
import pandas as pd
import numpy as np
df = pd.read_csv('student-alcohol-consumption/student-mat.csv')
print(df.head(3))
print(len(df))
# We are only concerned with the columns, 'absences' (number of absences) and 'G3' (final grade from 0 to 20)
# Let's create a couple of dummy variables.
# Adding a column 'grade_A' for students with 80% or higher final score.
df['grade_A'] = np.where(df['G3']*5 >= 80, 1, 0)
# Adding a column 'high_absenses' for students which missed 10 or more classes.
df['high_absenses'] = np.where(df['absences'] >= 10, 1, 0)
# Adding one more column for making a pivot table.
df['count'] = 1
# Drop all columns which won't be use in this example.
df = df[['grade_A', 'high_absenses', 'count']]
print(df.head())
# Create a pivot table
pv_table = pd.pivot_table(df, values='count', index=['grade_A'], columns=['high_absenses'], aggfunc=np.size, fill_value=0)
print(pv_table)
# Let's calculate some probabilities:
# P(A) : probability of a grade of 80% or higher
prob_A = (35+5) / len(df)
print('Probability - P(A):', prob_A)
# P(B) - probability of missing 10 or more math classes
prob_B = (78+5) / len(df)
print('Probability - P(B):', prob_B)
# Join Probability P(A,B) or P(A and B)
prob_A_and_B = 5 / len(df)
print('Probability - P(A,B):', prob_A_and_B)
# Conditional Probability: Probability P(A|B) - Students getting higher grade (80% +) given they missed 10 or more classes.
cond_prob = prob_A_and_B / prob_B
print('Probability - P(A|B):', cond_prob) |
0b5741b74c6fe0e14d24ab22fe232512b1d7b84f | A7xSV/Algorithms-and-DS | /Codes/Py Docs/fibo.py | 577 | 3.765625 | 4 | # Fibonacci numbers module
def fib(n):
"""Print fibonacci series upto n."""
a, b = 0, 1
while a < n:
print a,
a, b = b, a + b
print
def fibr(n):
"""Return fibonacci series upto n."""
a, b = 0, 1
result = []
while a < n:
result.append(a)
a, b = b, a + b
return result
# Make the file usable as a script as well as an importable module,
# because the code that parses the command line only runs if the module is executed as the "main" file
if __name__ == "__main__":
import sys
fib(int(sys.argv[1])) |
6ad62ed3f692d4fc78dec59b2a7aa5867d775571 | daftstar/learn_python | /01_MIT_Learning/00_final_exam/final_problem4.py | 997 | 4.0625 | 4 | # Implement a function that meets the specifications below.
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t
e.g. find the largest integer in the entire t """
# https://stackoverflow.com/questions/10823877/what-is-the-fastest-way-to-flatten-arbitrarily-nested-lists-in-python
def flatten_helper(obj_to_review):
for i in obj_to_review:
if isinstance(i, (list, tuple)):
for j in flatten_helper(i):
# https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
yield j
else:
yield i
flat_list = (list(flatten_helper(t)))
return max(flat_list)
# t = [99, 1, 800, (55, 98, 57), 100, [300, 400, 500], 101, 18, 601]
# t = (5, (1, 2), [[1], [2]])
t = (5, (1, 2), [[1], [9]])
print (max_val(t))
|
2cb6b0d2a77e4128654b2af5b9834d2a04ad2031 | CompassMentis/CheckIO | /triangle_angles.py | 941 | 4.1875 | 4 | """ Solution for http://www.checkio.org/mission/triangle-angles/ in Python 2.7 """
import math
def calculate_angle(a, b, c):
cos = (b*b + c*c - a*a) / (2.0 * b * c)
result = math.acos(cos)/math.pi * 180
result = int(round(result))
if result >= 180:
result -= 180
return result
def checkio(a, b, c):
all = [a, b, c]
all.sort()
if all[0] + all[1] < all[2]:
return [0, 0, 0]
angle_a = calculate_angle(a, b, c)
angle_b = calculate_angle(b, c, a)
angle_c = calculate_angle(c, a, b)
result = [angle_a, angle_b, angle_c]
result.sort()
return result
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(4, 4, 4) == [60, 60, 60], "All sides are equal"
assert checkio(3, 4, 5) == [37, 53, 90], "Egyptian triangle"
assert checkio(2, 2, 5) == [0, 0, 0], "It's can not be a triangle"
|
7c12c89b9006986af6513ecbdb33a4ba8c623c29 | edevaldolopes/learning | /08 - object1.py | 836 | 3.703125 | 4 | class Car:
def __init__(self, brand, color, year, tank, wheel):
self.brand = brand
self.wheel = wheel
self.color = color
self.year = year
self.tank = tank
def fuel(self, liter):
self.tank += liter
class Motorcycle(Car):
def __init__(self, brand, color, year, tank, wheel):
Car.__init__(self, brand, color, year, tank, wheel)
def fuel(self, liter):
if self.tank + liter > 35:
print('Fail fuel')
else:
self.tank += liter
car1 = Car('uno', 'green', 1994, 45, 4)
car1.fuel(10)
print(car1.brand)
print(car1.wheel)
print(car1.color)
print(car1.year)
print(car1.tank)
moto1 = Motorcycle('honda', 'red', 2021, 25, 2)
moto1.fuel(50)
print(moto1.brand)
print(moto1.wheel)
print(moto1.color)
print(moto1.year)
print(moto1.tank)
|
36794b3e99fe00868c14111f2bf297702be699a4 | Loksta8/FlipCoin | /flipcoinClass.py | 2,234 | 4.375 | 4 | """
@Author: Logan Herrera
@Date: 3/19/2020
@Python Version 3.5.3
The functionality of this class is to generate a montecarlo run of a flipped
coin on a case by case basis. It returns the results to the user.
"""
#Add needed libraries
import random
from fractions import *
#Class definition that takes user input
class FlipCoin:
#Instance class variables
def __init__(self, cases, number):
self.cases = cases
self.number = number
#Print results of each case to the user
@classmethod
def giveResults(self, cases, number):
for i in range(cases):
answer = self.cointoss(number)
print ("Case: ", i+1)
print ("Coin flipped ", number, " times.")
print ("Heads:Tails " , answer)
if 0 in answer:
print("Congratulations!! You got the ", self.probability(number), " chance of getting this!")
if answer[0] == 0:
print("Lucky Coin all flips landed on Tails!")
elif answer[1] == 0:
print("Lucky Coin all flips landed on Heads!")
else:
print("\n")
print ("\n")
#Simulate the coin Flip and record results in a list
@classmethod
def cointoss(self, number):
recordList = []
for i in range(number):
flip_coin = random.choice(['H', 'T'])
if flip_coin == 'H':
recordList.append('H')
else:
recordList.append('T')
return (recordList.count('H'), recordList.count('T'))
#Calculate the probability of getting the same flip everytime
@classmethod
def probability(self, number):
chance = Fraction(1/2)
prob = chance
for i in range(number):
if number == 1:
break
else:
prob *= chance
return prob
#Main function to take input from user to start monte-carlo run
def main():
random.seed()
cases = int(input("How many cases? "))
number = int(input("How many times do we flip the coin?"))
fC = FlipCoin(cases, number)
fC.giveResults(cases, number)
#Creating modularity independence
if __name__== "__main__":
main()
|
389f570ef9a71a645a91ae84b4d75a5c98a31284 | Chalex0/PythonOOP | /lesson_5_1_1.py | 296 | 4 | 4 | """
5.1 Исключения в Python
"""
print('Hello1')
print('Hello2')
try:
int('hello')
except ValueError:
print('wrong type')
print('Hello3')
try:
print('hello'[9])
except IndexError:
print('wrong index')
print('Hello3')
print('Hello4')
print('Hello5')
print('Hello6')
|
2e3962263444738d5386df5f2e0d03d03cb6629f | pramodith/DL1 | /1_cs231n/cs231n/layers.py | 12,633 | 3.703125 | 4 | import numpy as np
def affine_forward(x, w, b):
"""
Computes the forward pass for an affine (fully-connected) layer.
The input x has shape (N, d_1, ..., d_k) where x[i] is the ith input.
We multiply this against a weight matrix of shape (D, M) where
D = \prod_i d_i
Inputs:
x - Input data, of shape (N, d_1, ..., d_k)
w - Weights, of shape (D, M)
b - Biases, of shape (M,)
Returns a tuple of:
- out: output, of shape (N, M)
- cache: (x, w, b)
"""
out = None
#############################################################################
# TODO: Implement the affine forward pass. Store the result in out. You #
# will need to reshape the input into rows. #
#############################################################################
pass
out=np.dot(x.reshape(-1,w.shape[0]),w)+b
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = (x, w, b)
return out, cache
def affine_backward(dout, cache):
"""
Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Gradient with respect to w, of shape (D, M)
- db: Gradient with respect to b, of shape (M,)
"""
x, w, b = cache
dx, dw, db = None, None, None
db=np.sum(dout,axis=0)
dw=np.dot(dout.T,cache[0].reshape(-1,cache[1].shape[0]))
dx=np.dot(dout,cache[1].T).reshape(cache[0].shape)
#############################################################################
# TODO: Implement the affine backward pass. #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx, dw.T, db
def relu_forward(x):
"""
Computes the forward pass for a layer of rectified linear units (ReLUs).
Input:
- x: Inputs, of any shape
Returns a tuple of:
- out: Output, of the same shape as x
- cache: x
"""
out = x.copy()
out[out<0]=0
#############################################################################
# TODO: Implement the ReLU forward pass. #
#############################################################################
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = x
return out, cache
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
dx, x = None, cache
#############################################################################
# TODO: Implement the ReLU backward pass. #
#############################################################################
grads=np.copy(x)
grads[x<0]=0
grads[x>0]=1
dx=dout*grads
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx
def conv_forward_naive(x, w, b, conv_param):
"""
A naive implementation of the forward pass for a convolutional layer.
The input consists of N data points, each with C channels, height H and width
W. We convolve each input with F different filters, where each filter spans
all C channels and has height HH and width HH.
Input:
- x: Input data of shape (N, C, H, W)
- w: Filter weights of shape (F, C, HH, WW)
- b: Biases, of shape (F,)
- conv_param: A dictionary with the following keys:
- 'stride': The number of pixels between adjacent receptive fields in the
horizontal and vertical directions.
- 'pad': The number of pixels that will be used to zero-pad the input.
Returns a tuple of:
- out: Output data, of shape (N, F, H', W') where H' and W' are given by
H' = 1 + (H + 2 * pad - HH) / stride
W' = 1 + (W + 2 * pad - WW) / stride
- cache: (x, w, b, conv_param)
"""
out = None
#############################################################################
# TODO: Implement the convolutional forward pass. #
# Hint: you can use the function np.pad for padding. #
#############################################################################
x_padded=np.pad(x,((0,0),(0,0),(conv_param['pad'],conv_param['pad']),(conv_param['pad'],conv_param['pad'])),mode='constant',constant_values=0)
output_image = np.zeros((x_padded.shape[0],w.shape[0],1+(x.shape[2]+2*conv_param['pad']-w.shape[2])//conv_param['stride'],1+(x.shape[3]+2*conv_param['pad']-w.shape[3])//conv_param['stride']))
### END OF STUDENT CODE ####
############################
for n in range(0,x.shape[0]):
for k in range(0,w.shape[0]):
for out_i,i in enumerate(range(w.shape[2] // 2, x.shape[2] + w.shape[2] // 2,conv_param['stride'])):
for inp_i,j in enumerate(range(w.shape[3] // 2, x.shape[3] + w.shape[3] // 2,conv_param['stride'])):
try:
output_image[n,k,out_i,inp_i]= np.sum(x_padded[n,:,i - w.shape[2] // 2:i + int(np.ceil(w.shape[2]/ 2)),j - w.shape[3] // 2:j + int(np.ceil(w.shape[3]/2))]*w[k,:,:,:])+b[k]
except Exception as e:
print(e)
#############################################################################
# END OF YOUR CODE #
#############################################################################
cache = (x, w, b, conv_param)
out=output_image
return out, cache
def conv_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a convolutional layer.
Inputs:
- dout: Upstream derivatives.
- cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive
Returns a tuple of:
- dx: Gradient with respect to x
- dw: Gradient with respect to w
- db: Gradient with respect to b
"""
dx, dw, db = None, None, None
#############################################################################
# TODO: Implement the convolutional backward pass. #
#############################################################################
padded_x=np.pad(cache[0],((0,0),(0,0),(cache[3]['pad'],cache[3]['pad']),(cache[3]['pad'],cache[3]['pad'])),'constant',constant_values=0)
dw=np.zeros(cache[1].shape)
dx=np.zeros(padded_x.shape)
db=np.zeros(cache[1].shape[0])
for n in range(cache[0].shape[0]):
for k in range(cache[1].shape[0]):
db[k] += np.sum(dout[n][k])
for c in range(cache[1].shape[1]):
for cnt_i,i in enumerate(range(0,padded_x.shape[2]-int(np.ceil(cache[1].shape[2]/2)),cache[3]['stride'])):
for cnt_j,j in enumerate(range(0,padded_x.shape[3]-int(np.ceil(cache[1].shape[3]/2)),cache[3]['stride'])):
dw[k][c]+=padded_x[n,c,i:i+cache[1].shape[2],j:j+cache[1].shape[3]]*dout[n][k][cnt_i][cnt_j]
dx[n,c,i:i+cache[1].shape[2],j:j+cache[1].shape[3]]+=cache[1][k][c]*dout[n][k][cnt_i][cnt_j]
#############################################################################
# END OF YOUR CODE #
#############################################################################
dx=dx[:,:,cache[3]['pad']:dx.shape[2]-cache[3]['pad'],cache[3]['pad']:dx.shape[3]-cache[3]['pad']]
return dx, dw, db
def max_pool_forward_naive(x, pool_param):
"""
A naive implementation of the forward pass for a max pooling layer.
Inputs:
- x: Input data, of shape (N, C, H, W)
- pool_param: dictionary with the following keys:
- 'pool_height': The height of each pooling region
- 'pool_width': The width of each pooling region
- 'stride': The distance between adjacent pooling regions
Returns a tuple of:
- out: Output data
- cache: (x, pool_param)
"""
out = None
#############################################################################
# TODO: Implement the max pooling forward pass #
#############################################################################
output=np.zeros((x.shape[0],x.shape[1],1+(x.shape[2]-pool_param['pool_height'])//pool_param['stride'],1+(x.shape[3]-pool_param['pool_width'])//pool_param['stride']))
for n in range(0,x.shape[0]):
for c in range(0,x.shape[1]):
for cnt_i,i in enumerate(range(0,x.shape[2]-pool_param['pool_height']+1,pool_param['stride'])):
for cnt_j,j in enumerate(range(0,x.shape[3]-pool_param['pool_width']+1,pool_param['stride'])):
output[n][c][cnt_i][cnt_j]=np.max(x[n,c,i:i+pool_param['pool_height'],j:j+pool_param['pool_width']])
#############################################################################
# END OF YOUR CODE #
#############################################################################
out=output.copy()
cache = (x, pool_param)
return out, cache
def max_pool_backward_naive(dout, cache):
"""
A naive implementation of the backward pass for a max pooling layer.
Inputs:
- dout: Upstream derivatives
- cache: A tuple of (x, pool_param) as in the forward pass.
Returns:
- dx: Gradient with respect to x
"""
x=cache[0]
dx = np.zeros(x.shape)
pool_param=cache[1]
for n in range(0,x.shape[0]):
for c in range(0,x.shape[1]):
for cnt_i,i in enumerate(range(0,x.shape[2]-pool_param['pool_height']+1,pool_param['stride'])):
for cnt_j,j in enumerate(range(0,x.shape[3]-pool_param['pool_width']+1,pool_param['stride'])):
loc=np.unravel_index(np.argmax(np.ravel(x[n,c,i:i+pool_param['pool_height'],j:j+pool_param['pool_width']])),(pool_param['pool_height'],pool_param['pool_width']))
loc=list(loc)
loc[0]+=i
loc[1]+=j
dx[n][c][loc[0]][loc[1]]+=dout[n,c,cnt_i,cnt_j]
#############################################################################
# TODO: Implement the max pooling backward pass #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return dx
def svm_loss(x, y):
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
N = x.shape[0]
correct_class_scores = x[np.arange(N), y]
margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)
margins[np.arange(N), y] = 0
loss = np.sum(margins) / N
num_pos = np.sum(margins > 0, axis=1)
dx = np.zeros_like(x)
dx[margins > 0] = 1
dx[np.arange(N), y] -= num_pos
dx /= N
return loss, dx
def softmax_loss(x, y):
"""
Computes the loss and gradient for softmax classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and
0 <= y[i] < C
Returns a tuple of:
- loss: Scalar giving the loss
- dx: Gradient of the loss with respect to x
"""
probs = np.exp(x - np.max(x, axis=1, keepdims=True))
probs /= np.sum(probs, axis=1, keepdims=True)
N = x.shape[0]
loss = -np.sum(np.log(probs[np.arange(N), y])) / N
dx = probs.copy()
dx[np.arange(N), y] -= 1
dx /= N
return loss, dx
|
1d94f5978380afe65e4c2d3c39fdc8ad96e0bad7 | krish001/MyPhython | /MatPlotlib.py | 781 | 3.921875 | 4 | # The program evaluates your performance of typing speed
# The program will plot a graph.
import matplotlib.pyplot as plt
import time as t
times = []
mistakes = 0
print("this program will validate your typing speed")
input("press to continue")
while len(times) <5:
start = t.time()
word = input("Type the word: ")
end = t.time()
time_elapsed = end - start
times.append(time_elapsed)
if (word.lower()!="programming"):
mistakes +=1
print("you have made " + str(mistakes) + "mistake(s).")
t.sleep(3)
x = [1,2,3,4,5]
y = times
legend = ["1","2","3","4","5"]
plt.xticks(x,legend)
plt.ylabel("time in seconds")
plt.xlabel("Attempts")
plt.title("word evolution")
plt.plot(x,y)
plt.show()
x= [1,2,3,4]
y= [100,200,1100,1800]
plt.plot(x,y)
plt.show()
|
fcb6320b1b0a2d1e1f3fc2ee9eaeab8fed89005c | badFarmer/PythonJumpstart_GuessTheNumber | /program.py | 834 | 4.0625 | 4 | #import random
import random
print('--------------------------------------------')
print(' HELLO WORLD')
print('--------------------------------------------')
print()
the_number = random.randint(0, 100)
name = input ('What is your name?')
#print (the_number, type(the_number))
#print (guess, type(guess))
#print (guess_text, type(guess_text))
guess = 101
while guess != the_number:
guess_text = input('Guess a number between 0 and 100: ')
guess = int(guess_text)
if guess < the_number:
print('{0} is too low, sucka. I mean {1}.'.format(guess, name))
elif guess > the_number:
print('{0}. Too damn high. {1}.'.format(guess, name))
elif guess == the_number:
print('Yay {0]. You win goodbye.'.format(name))
else:
'WTF kinda guess is that?'
print ('done.')
exit()
|
c343c1660481f25e2c6ef61a3d77692933458ee5 | djiang-ucc/image-viewer | /image.py | 1,853 | 3.703125 | 4 | from tkinter import*
from PIL import ImageTk,Image
root= Tk()
root.title('view an image')
#create a image viewer
#images
my_img1 = ImageTk.PhotoImage(Image.open("6ix.jpg"))
my_img2 = ImageTk.PhotoImage(Image.open("eastyork.gif"))
my_img3 = ImageTk.PhotoImage(Image.open("west.jpg"))
#my_img4 = ImageTk.PhotoImage(Image.open("dt.jpg"))
#image list
image_list = [my_img1, my_img2, my_img3]
my_label = Label(image=my_img1)
my_label.grid(row=0, column=0, columnspan=3)
#this tells the program which photo to go to after you click a button
def forward(image_number):
global my_label
global button_forward
global button_back
my_label.grid_forget()
my_label = Label(image=image_list[image_number-1])
button_forward = Button(root, text=">>", command=lambda: forward(image_number+1))
button_back = Button(root, text="<<", command=lambda: back(image_number-1))
if image_number == 3:
button_forward = Button(root, text=">>", state=DISABLED)
my_label.grid(row=0, column=0, columnspan=3)
button_back.grid(row=1, column=0)
button_forward.grid(row=1, column=2)
def back(image_number):
global my_label
global button_forward
global button_back
my_label.grid_forget()
my_label = Label(image=image_list[image_number-1])
button_forward = Button(root, text=">>", command=lambda: forward(image_number+1))
button_back = Button(root, text="<<", command=lambda: back(image_number-1))
my_label.grid(row=0, column=0, columnspan=3)
button_back.grid(row=1, column=0)
button_forward.grid(row=1, column=2)
button_back = Button(root, text="<<", command=back, state=DISABLED)
button_exit = Button(root, text="Exit Program", command=root.quit)
button_forward = Button(root, text=">>", command=lambda: forward(2))
button_back.grid(row=1, column=0)
button_exit.grid(row=1, column=1)
button_forward.grid(row=1, column=2)
root.mainloop() |
d95ac7222d52a30b2fa4caab90c56f5fb9f30c27 | Kontowicz/Daily-Interview-Pro | /solutions/day_125.py | 313 | 3.859375 | 4 | def find_anagrams(s, t):
to_return = []
t = sorted(t)
for i in range(0, len(s) - len(t) + 1):
if sorted(s[i:i+len(t)]) == t:
to_return.append(i)
return to_return
assert find_anagrams('acdbacdacb', 'abc') == [3, 7]
print(find_anagrams('acdbacdacb', 'abc'))
print('Test pass.') |
bfcc97e6188981b238b0cfff751cf8f73c27979a | randell/Project-Euler | /0022-name_scores.py | 2,067 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Project Euler Problem N
Title:
Name scores
Description:
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into alphabetical
order. Then working out the alphabetical value for each name, multiply this
value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is
worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file
Solution:
Answer: 871198282
I'm the 79,213th person to solve this problem.
"""
with open('assets/p022_names.txt', 'r') as f:
read_data = f.read()
f.closed
names = [x.strip('"') for x in read_data.split(",")]
names.sort()
alphabetical_value = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
'F': 6,
'G': 7,
'H': 8,
'I': 9,
'J': 10,
'K': 11,
'L': 12,
'M': 13,
'N': 14,
'O': 15,
'P': 16,
'Q': 17,
'R': 18,
'S': 19,
'T': 20,
'U': 21,
'V': 22,
'W': 23,
'X': 24,
'Y': 25,
'Z': 26
}
def get_name_score(str):
name_score = 0
for x in str:
name_score += alphabetical_value[x]
return name_score
total_name_score = 0;
for i, name in enumerate(names):
name_score = get_name_score(name)
multiplier = (i+1)
total_name_score += (get_name_score(name) * (i+1))
print total_name_score |
8d5861aa9738ea91c567eaeede25284ea13f2bb1 | Sushmitha26/Pong_Game | /Pong game/pong.py | 4,928 | 4.5625 | 5 | #turtle module is used to do some basic graphics,for games,Using Turtle, we can easily draw in a drawing board.
import turtle
import winsound
wn=turtle.Screen()
wn.title("Pong by Sushmitha")
wn.bgcolor("black")
wn.setup(width=800, height=600)
#tracer stops window from updating so we have to manually update it,it basically speeds up game
wn.tracer(0)
#Paddle A
paddle_a=turtle.Turtle() #creates and retruns a new turtle object
paddle_a.speed(0) #speed of animation,sets the speed to maximum,3-for slow
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(stretch_wid=5,stretch_len=1)
paddle_a.penup() #,picks the turtle pen, draw a line when moving.
paddle_a.goto(-350,0) #set positions x,y y=0 => vertically centered
#Paddle B
paddle_b=turtle.Turtle() #creates and retruns a new turtle object
paddle_b.speed(0) #speed of animation,not movement speed,sets the speed to maximum,3-for slow
paddle_b.shape('square')
paddle_b.color('white')
paddle_b.shapesize(stretch_wid=5,stretch_len=1) #20px wide,100px tall
paddle_b.penup() #,picks the turtle pen, will not draw a line when moving.
paddle_b.goto(350,0)
#Ball
ball=turtle.Turtle() #creates and retruns a new turtle object
ball.speed(0) #speed of animation,sets the speed to maximum,3-for slow
ball.shape('square')
ball.color('white')
ball.penup() #,picks the turtle pen, draw a line when moving.
ball.goto(0,0)
#movement of ball
ball.dx = 0.2 #every time the ball moves by 0.1px right(coz positive)
ball.dy = 0.2 #0.1px up
#score
score_a = 0
score_b = 0
#Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle() #we just want to see text,not pen
pen.goto(0,260)
pen.write("Player A: 0 Player B: 0",align="center", font=("Courier",24,"normal"))
#Function up 'a'
def paddle_a_up():
y=paddle_a.ycor() #ycor is from turtle module,returns the y-coordinate
y += 20
paddle_a.sety(y) #sets y to the new y
#Function down 'a'
def paddle_a_down():
y=paddle_a.ycor() #ycor is from turtle module,returns the y-coordinate
y -= 20
paddle_a.sety(y)
#Function up 'b'
def paddle_b_up():
y=paddle_b.ycor() #ycor is from turtle module,returns the y-coordinate
y += 20
paddle_b.sety(y) #sets y to the new y
#Function down 'b'
def paddle_b_down():
y=paddle_b.ycor() #ycor is from turtle module,returns the y-coordinate
y -= 20
paddle_b.sety(y)
#keyboard binding
wn.listen() #tells to listen for keyboard input
wn.onkeypress(paddle_a_up, 'w') #when u press lowercase w,calls the function
wn.onkeypress(paddle_a_down, 's')
wn.onkeypress(paddle_b_up, 'Up') #when u press lowercase w,calls the function
wn.onkeypress(paddle_b_down, 'Down')
#Main game loop
while True:
#every time the loop runs,it updates the screen
wn.update()
#Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
#border check
#height is 600,so +300 is y-coordinate at the top,and -300 at the bottom,and ball size is 20*20,so half is 10,300-10=290
if(ball.ycor() > 290): #top
ball.sety(290)
ball.dy *= -1 #reverses the direction i.e. 0.1*-1 = -0.1
#winsound.PlaySound("pong.wav", winsound.SND_ASYNC)
elif(ball.ycor() < -290): #bottom
ball.sety(-290)
ball.dy *= -1
#winsound.PlaySound("pong.wav", winsound.SND_ASYNC)
if(ball.xcor() > 350): #right
ball.goto(0,0)
ball.dx *= -1
score_a += 1
pen.clear() #Delete turtle's drawings from the screen.State and position of turtle as well as drawings of other turtles are not affected.
pen.write("Player A: {} Player B: {}".format(score_a,score_b),align="center", font=("Courier",24,"normal"))
elif(ball.xcor() < -350): #left
ball.goto(0,0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.write("Player A: {} Player B: {}".format(score_a,score_b),align="center", font=("Courier",24,"normal"))
#paddle and ball collisions
#ycor -> top of paddle and bottom of paddle
if(ball.xcor() > 340 and ball.xcor() < 350 and ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):
ball.setx(340)
ball.dx *= -1
#winsound.PlaySound("pong.wav", winsound.SND_ASYNC)
elif(ball.xcor() < -340 and ball.xcor() > -350 and ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):
ball.setx(-340)
ball.dx *= -1
#for linux, os.system("aplay bounce.wav&")
#for mac, os.system("afplay bounce.wav&")
#winsound.PlaySound("pong.wav", winsound.SND_ASYNC) #PlaySound is a wrapper around the Windows PlaySound API, SND_ASYNC ,similar to &, if the file is not async, program will stop,else it will play the sound in bg.
|
bb6e433e4d0ac5adf12febda1a16a226988f169c | jpark527/Fall2018 | /Python/HarvaidX/week2_4.py | 1,506 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 19:46:36 2018
@author: j
"""
''' Simulating Randomness & Clock '''
import random
import numpy as np
import matplotlib.pyplot as plt
for i in range(10):
print(random.choice(['head', 'tail']))
''' case 1: '''
n = 10000
data = []
#print('\nRolling dice', str(n), 'times..')
#
#for i in range(n):
# data.append(random.choice(range(1,7)))
#plt.hist(data, normed=True, bins=np.linspace(.5, 6.5, 7))
''' case 2: '''
dice = 10
#print('\nRolling', str(dice), 'dice', str(n), 'times..')
#for i in range(n):
# mySum = np.sum(np.random.randint(1,7,dice))
# data.append(mySum)
#
#plt.hist(data)
X = np.random.randint(1,7,(n, dice))
Y = np.sum(X, axis=1)
#plt.hist(Y)
''' Numpy Random Module '''
''' Generating random numpy array '''
a = np.random.random(5) # 1D-array
b = np.random.random((3,5)) # 2D-array
c = np.random.normal(0,1,5) # (mean, standardDeviation, arrayLen)
d = np.random.normal(0,1,(5,3))
''' Generating random int array in numpy '''
e = np.random.randint(1,7,10)
f = np.random.randint(1,7,(5,3))
''' Measuring Time '''
import time
startTime = time.clock()
endTime = time.clock()
endTime - startTime
''' Random Walk Demo '''
print('Random Walk Demo..')
numOfWalk = 7
X0 = np.array([[0], [0]])
deltaX = np.random.normal(0, 1, (2,numOfWalk))
X = np.concatenate( (X0, np.cumsum(deltaX, axis = 1)), axis = 1 )
plt.plot(X[0], X[1], 'go-')
#plt.savefig('randomWalkDemo.pdf')
|
f2e5246b8bc030d1d744e0a2fc29177cdb84152c | jadenpadua/Data-Structures-and-Algorithms | /trees/RecoverBST.py | 1,036 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
self.findSegments(root);
temp = firstStartPoint.val
firstStartPoint.val = lastEndPoint.val
lastEndPoint.val = temp
return root
def findSegments(self,root):
firstStartPoint = None
lastEndPoint = None
prevNode = None
if node == None:
return None
self.findSegments(node.left)
if prevNode != None:
if prevNode.val > node.val
if firstStartPoint == None:
firstStartPoint = prevNode
lastEndPoint = node
prevNode = node
self.findSegments(root.right)
|
20db6364532d0a67b888a86cc249ff51acf40d53 | jaredjamieson/personal | /python/SolarSystem/Star.py | 1,045 | 3.921875 | 4 | ####Star.py####
#Lab 12 Jamieson & Cardaropoli
#Imports
class Star:
#Constructor
def __init__(self, name, type1, mass):
self.__name = name
self.__type1 = type1
self.__mass = mass
#Returns "'name' Star"
def __str__(self):
return self.__name + 'Star'
#Returns the name of the star
def get_name(self):
return self.__name
#Returns the type of the star
def get_type(self):
return self.__type1
#Returns the mass of the star
def get_mass(self):
return self.__mass
#Sets the name of the star
def set_name(self):
newname = str(input('Enter a new star name: '))
self.__name = newname
#Sets the type of star
def set_type(self):
newtype = str(input('Enter a new star type: '))
self.__type1 = newtype
#Sets the mass of the star
def set_mass(self):
newmass = float(input('Enter a new star mass: '))
self.__mass = newmass
|
2f4a30bac02a360e92ea7babee91cb2e11c5fbb4 | MollyJ04/python | /classProject.py | 15,576 | 3.84375 | 4 | # Molly Jain
# classProject.py
import random
# variable that decides if the game is still running
gameOver = False
class Computer:
def __init__(self, name):
self.name = name
self.health = 100
def attack(self, opponent):
# one of the options when dueling
print(f"The {self.name} attacked you! -10 to your health")
opponent.health = opponent.health - 10
def bigAttack(self, opponent):
# another option when dueling
print(f"The {self.name} used its special attack against you! -15 to your health")
opponent.health = opponent.health - 15
def heal(self):
# another another options when dueling
print(f"The {self.name} stopped to catch its breath. +5 to {self.name}'s health")
self.health += 5
def computer_move(self):
# returns a random number that decides which option is used in the duel
choice = random.randint(1, 4)
return choice
# ---------------------------------------------- end of computer class -------------------------------------------------
class Character:
characterNames = []
def __init__(self, name, school):
self.myName = name
self.mySchool = school
# spells that you can use in a duel
self.mySpells = ["expelliarmus", "protego", "stupefy", "episkey"]
self.health = 100
Character.characterNames.append(self.myName)
# methods that are called to lower opponent's health during duels
def expelliarmus(self, opponent):
opponent.health = opponent.health - 10
print(f"You used expelliarmus! -10 to the {opponent.name}'s health")
def stupefy(self, opponent):
opponent.health = opponent.health - 15
print(f"You used stupefy! -15 to the {opponent.name}'s health")
def confundo(self, opponent):
if "confundo" in self.mySpells:
opponent.health = opponent.health - 10
print(f"You used confundo! -10 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
def episkey(self):
self.health += 10
print("You used episkey! +10 to your health")
def aguamenti(self, opponent):
if "aguamenti" in self.mySpells:
opponent.health = opponent.health - 10
print(f"You used aguamenti! -10 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
def petrificus(self, opponent):
if "petrificus totalus" in self.mySpells:
opponent.health = opponent.health - 15
print(f"You used petrificus totalus! -15 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
def levicorpus(self, opponent):
if "levicorpus" in self.mySpells:
opponent.health = opponent.health - 10
print(f"You used levicorpus! -10 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
def reducto(self, opponent):
if "reducto" in self.mySpells:
opponent.health = opponent.health - 10
print(f"You used reducto! -10 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
def incendio(self, opponent):
if "incendio" in self.mySpells:
opponent.health = opponent.health - 15
print(f"You used incendio! -15 to the {opponent.name}'s health")
else:
print("You don't know that spell yet!")
# takes a parameter and checks what it's equal to, then calls the matching method
def player_move(self, choice, opponent):
if choice == "expelliarmus":
self.expelliarmus(opponent)
elif choice == "stupefy":
self.stupefy(opponent)
elif choice == "confundo":
self.confundo(opponent)
elif choice == "aguamenti":
self.aguamenti(opponent)
elif choice == "petrificus totalus":
self.petrificus(opponent)
elif choice == "levicorpus":
self.levicorpus(opponent)
elif choice == "reducto":
self.reducto(opponent)
elif choice == "incendio":
self.incendio(opponent)
elif choice == "episkey":
self.episkey()
elif choice == "quit":
global gameOver
gameOver = True
else:
print("That's not one of the spells you can use!")
# --------------------------------------------- end of character class -------------------------------------------------
def computerAttack(player, computer):
print(f"\nEnter spells to fight the {computer.name}!")
while player.health > 0 and computer.health > 0:
print()
print(player.mySpells)
playerMove = input("What spell would you like to use?")
computerMove = computer.computer_move()
# let's the player to quit at anytime during the duel
if playerMove == "quit":
global gameOver
gameOver = True
break
# checks spells that block the computer and moves back to the top of the while loop if they are entered
if playerMove == "protego" or playerMove == "impedimenta":
print(f"You blocked the {computer.name}! Neither of you were hurt.")
# checks if the computer blocked the player
elif computerMove == 1:
print("You were blocked! No damage done.")
else:
# calls the method that calls the appropriate spell method, then calls the computer's method depending on what number its choice is
player.player_move(playerMove, computer)
if computerMove == 2:
computer.attack(player)
elif computerMove == 3:
computer.bigAttack(player)
elif computerMove == 4:
computer.heal()
print(f"Your health: {player.health}")
print(f"Opponent's health: {computer.health}")
else:
# prints appropriate statement for who won, ends game if you lost
if player.health < 1:
print("You lost!")
gameOver = True
elif computer.health < 1:
print("Congratulations! You won!")
player.health = 100
# characters and computers used
harry = Character("Harry Potter", "Hogwarts")
cedric = Character("Cedric Diggory", "Hogwarts")
fleur = Character("Fleur Delacour", "Beauxbatons")
viktor = Character("Viktor Krum", "Durmstrang")
dragon = Computer("dragon")
mermaid = Computer("mermaid")
while gameOver == False:
print("Welcome to Triwizard Adventures!")
for name in Character.characterNames:
print(name)
# choose your character
playerChoice = input("Which character would you like to be?")
# makes sure an available player is chosen, then sets player variable to that
while (playerChoice != "Harry Potter" and playerChoice != "Cedric Diggory" and playerChoice != "Fleur Delacour"
and playerChoice != "Viktor Krum" and playerChoice != "quit"):
playerChoice = input("Sorry, you can't choose that character! Please choose another character.")
if playerChoice == ("Harry Potter"):
player = harry
elif playerChoice == "Cedric Diggory":
player = cedric
elif playerChoice == "Fleur Delacour":
player = fleur
elif playerChoice == "Viktor Krum":
player = viktor
elif playerChoice == "quit":
gameOver = True
break
# asks players whether or not to join the tournament
print("The Triwizard Tournament is beginning again this year!")
join = input("Would you like to enter your name for the Triwizard Tournament? yes/no")
if join == "yes":
print("\nYour name was picked! Get ready to join the competition!")
elif join == "no":
print("\nYou decided not to enter, but your name just got picked! Someone must have entered your name...")
elif join == "quit":
gameOver = True
break
# decides what to do about the first challenge, learns spells based on choices. prints texts
print("\nLevel 1: The First Task")
print("\nIt's time for the first challenge! But no one will tell you what it is...")
print("Your friend offers to study with you so that you can prepare for whatever is coming.")
print("But another friend tells you that they think they know what the challenge might be.")
firstChallengeStudy = input("What do you want to do? \nStudy \nFind out what the challenge is \nDo nothing")
if firstChallengeStudy == "Study":
print(
"\nAfter studying for a while, you learn impedimenta, the blocking spell. Hopefully it will help in the first challenge!")
# um what's that mean? fix that
player.mySpells.append("impedimenta")
print("\nCongratualations! You can now use impedimenta in duels!")
print(
"\nIt's the day of the first challenge! And they want you to... fight a dragon? You have to get past it and grab that golden egg. Here goes nothing...")
elif firstChallengeStudy == "Find out what the challenge is":
print("\nThere are dragons at Hogwarts! The first challenge must have something to do with dragons...")
print(
"You decide to learn aguamenti, the water spell. Water has to help against a fire-breathing dragon, right?")
player.mySpells.append("aguamenti")
print("\nCongratulations! You can now use aguamenti in duels!")
print(
"\nYou were right! The first challenge is to get past one of those dragons and grab a golden egg. How hard could it be?")
elif firstChallengeStudy == "Do nothing":
print("\nHow bad could the first challenge be? You should be fine with the spells you already know.")
print("\nThe first challenge is fighting a DRAGON?! Maybe you should have studied some of those spells...")
elif firstChallengeStudy == "quit":
gameOver = True
break
# first fight
computerAttack(player, dragon)
if gameOver == True:
break
print("\nLevel 2: The Golden Egg")
# introduces second level
print(
"You got through the first challenge! (And you only got a few dragon burns...) The next challenge has something to do with this golden egg - but what?")
print(
"\nEvery time you open the egg, it make some terrible screaming noise. You guess it's some kind of hint, but what could it be?")
print("They told you you're only supposed to work it out on your own, but it's rather tempting to ask a friend.")
print(
"But you also heard that one of the other competitors already figured it out. You're sure that you could convince them to tell you if you really tried, but isn't that cheating?")
print(
"Maybe it's just better to figure it out on your own. It can't be too hard, otherwise they wouldn't have given a hint.")
# asks what the player wants to do, learn a spell based on your choice (adds to spell list)
eggChoice = input("\nWhat do you want to do?\nAsk a friend\nBribe the other competitor\nFigure it out alone")
if eggChoice == "Ask a friend":
print(
"\nYou decided to ask your friend what to do.\n\"Well, dragons use fire, which you fight with water. What if you bring it underwater?\"")
print("That night, you try bringing the egg underwater and... it works! You can hear a song, with these lyrics:"
"\nCome seek us where our voices sound,"
"\nWe cannot sing above the ground"
"\nAnd while you're searching ponder this;"
"\nWe've taken what you'll sorely miss,"
"\nAn hour long you'll have to look,"
"\nAnd to recover what we took,"
"\nBut past an hour, the prospect's black,"
"\nToo late, it's gone, it won't come back.")
print(
"\n\"We cannot sing above the ground\"...that must mean mermaids! And it sounds like you'll have to fight them to get something back. Better start practicing!")
player.mySpells.append("petrificus totalus")
print("\nCongratulations! You can now use petrificus totalus in duels!")
elif eggChoice == "Bribe the other competitor":
print(
"\nIt turns out that competitor is very willing to share in exchange for 100 galleons in Honeydukes candy. But they would only tell you the general idea of the next challenge.")
print(
"They said that it has something to do with water, and that you have an hour to get back what someone took. It's not much to work with, but it's a start.")
print(
"If the first challenge was fighting dragons, maybe this one wants you to fight water with fire? Maybe you should learn the spell for fire...")
player.mySpells.append("incendio")
print("\nCongratulations! You can now use incendio in duels!")
elif eggChoice == "Figure it out alone":
print(
"\nYou're trying to figure out the egg's clue next to the Great Lake when it rolls into the Great Lake. You lunge after it, but before you pull it out, you realize something. It's not making that awful noise anymore!")
print(
"That night you put the egg in a bucket of water. It's not making the noise, but something else is coming out of it now. You put your head under the water and hear a song!")
print("The lyrics say this:"
"\nCome seek us where our voices sound,"
"\nWe cannot sing above the ground"
"\nAnd while you're searching ponder this;"
"\nWe've taken what you'll sorely miss,"
"\nAn hour long you'll have to look,"
"\nAnd to recover what we took,"
"\nBut past an hour, the prospect's black,"
"\nToo late, it's gone, it won't come back.")
print(
"\n\"We cannot sing above the ground\"...that must mean mermaids! And it sounds like you'll have to fight them to get something back. Better start practicing!")
player.mySpells.append("reducto")
print("\nCongratulations! You can now use reducto in duels.")
elif eggChoice == "quit":
gameOver = True
break
print(
"\nIt's the day of the second task, but you haven't found anything missing that's valuable. You wonder what's been taken, but the task is about to start.")
print(
"\"Welcome to the second task!\" the announcer booms. \"Today, your competitors will have exactly one hour to find a person they value the most at the bottom of the Great Lake! Go!\"")
print(
"Of course! You haven't seen your friend all day. You must have to find them in the Great Lake! Talk about pressure...")
print(
"You leap in, using a spell to help you breathe under the water. You make it all the way to the bottom of the lake without encountering anyone.")
print(
"Just as the bottom comes into sight, a mermaid stops you! Looks like you'll have to fight to get your friend back!")
# starts another fight
computerAttack(player, mermaid)
if gameOver == True:
break
print("Thanks for playing Triwizard Adventures")
gameOver = True
break
|
40d8c113ea24b812e0710ae75b4821399ede9954 | Asano-H/Hana | /list2.py | 437 | 3.625 | 4 | datalist=[1,2,3]
complist=[[10,20,30],1000,["red","blue"]]
print(datalist)
datalist[2]="three" #datalistの3つ目の要素をthreeに置き換える
print(datalist)
print(complist[2][0]) #complistの3つ目のリストの1つ目の要素を出力
"""
2次元配列、3次元配列のような複数の階層をもたせることが可能。
数値や文字列を同じリストにまとめることができる。
""" |
ec4e5ab4b65c2cb1830aa68dd98ad6a8dc2085c8 | Nidhi-Chourasiya/Credit_Card | /Credit_Card.py | 1,390 | 3.875 | 4 | import datetime
import random
while True:
card_no = str(input('enter a credit card : '))
if len(card_no)==16:
print('valid no. ')
else:
print('invalid length')
user_name = input('enter user name FN MN LN ').split()
date=datetime.datetime.now()
yyyy=int(input('please enter the year on your credit card'))
yy=str(yyyy)
if len(yy)==4:
print('length of the year is valid')
else:
print('invalid length try again')
if yyyy <date.year:
print('your card not exist')
else:
print('year is valid')
mm=int(input('please enter the month on your credit card'))
if mm >12:
print('invalid month, plz try again')
else:
print('valid month')
if mm < date.month:
print('month is not valid')
else:
print('valid month')
CVV=str(input('enter your CVV'))
if len(CVV)==4:
print('valid CVV ')
cvv_list=[]
cvv_list.append(CVV)
else:
print('invalid cvv')
mob_no=str(input('enter your valid mobile no. '))
if len(mob_no)==10:
print('valid no')
mob=[]
mob.append(mob_no)
else:
print('invalid no.')
otp=[]
a=random.randint(1000,9999)
otp.append(a)
print('OTP', a)
details = {mob_no:{card_no:{CVV:user_name}}}
print(details)
pw=int(input(''))
|
6d31230b44dd7593e195e726ab21b834a341c188 | BryceGetzHub/Ch.03_Input_Output | /Practice.py | 1,002 | 3.859375 | 4 | # for i in range(10,0,-1):
# print(i)
# print("blast off")
#
# total=0
# for i in range (5):
# new_number = int(input("enter a number"))
# if new_number ==0:
# total += 1
# print("you entered a total of", total, "zeros")
#
#
# a=0
# for i in range(10):
# a += 1
# print(a)
#
#
# a = 0
# for i in range(10):
# a += 1
# for j in range(10):
# a +=1
# print(a)
#
#
# for i in range(10):
# print(i)
#
# i=0
# while i<10:
# print(i)
# i+=1
#
#
# i=1
# c=0
# while i <= 2 ** 32:
# print(c,i)
# i *= 2
# c+=1
#
#
# dont do this
# while range (10) #
#
#
# done=False
# while not done:
# quit=input("do you want to quit? type y: ")
# if quit.lower()=="y":
# done=True
#
#
# import random
# for i in range(5):
# my_num=random.random()
# print(my_num*5+10)
#
#
# var = 10
# while var > 0:
# print('current variable value :', var)
# var=-1
# if var == 5:
# break
# print("sorry, the death star shot early")
|
813ce907c0b6019d37cc6204e8568a5ac5572fb9 | pisaia01/EPANETinp | /createDBTables.py | 4,662 | 3.578125 | 4 | #!/usr/bin/python
import psycopg2
from config import config
def delete_table_values(tables):
""" create tables in the PostgreSQL database"""
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
for value in tables:
query = 'DELETE FROM '+str(value)+';'
cur.execute(query)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
def create_tables(tables):
""" create tables in the PostgreSQL database"""
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
for value in tables:
cur.execute(value)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
tables=['CREATE TABLE IF NOT EXISTS JUNCTIONS (ID VARCHAR, Elev FLOAT, Demand FLOAT, Pattern VARCHAR);',
'CREATE TABLE IF NOT EXISTS RESERVOIRS (ID VARCHAR, Head FLOAT, Pattern VARCHAR);',
'CREATE TABLE IF NOT EXISTS TANKS (ID VARCHAR, Elevation FLOAT, InitLevel FLOAT, MinLevel FLOAT, MaxLevel FLOAT, Diameter FLOAT, MinVol FLOAT, VolCurve VARCHAR);',
'CREATE TABLE IF NOT EXISTS PIPES (ID VARCHAR, Node1 VARCHAR, Node2 VARCHAR, Length FLOAT, Diameter FLOAT, Roughness FLOAT, MinorLoss FLOAT, Status VARCHAR);',
'CREATE TABLE IF NOT EXISTS PUMPS (ID VARCHAR, Node1 VARCHAR, Node2 VARCHAR, Parameters VARCHAR);',
'CREATE TABLE IF NOT EXISTS VALVES (ID VARCHAR, Node1 VARCHAR, Node2 VARCHAR, Diameter FLOAT, Type VARCHAR, Setting FLOAT, MinorLoss FLOAT);',
'CREATE TABLE IF NOT EXISTS DEMANDS (Junction VARCHAR, Demand FLOAT, Pattern VARCHAR, Category VARCHAR);',
'CREATE TABLE IF NOT EXISTS STATUS (ID VARCHAR, StatusSetting VARCHAR);',
'CREATE TABLE IF NOT EXISTS PATTERNS (ID VARCHAR, Multipliers VARCHAR);',
'CREATE TABLE IF NOT EXISTS CURVES (ID VARCHAR, XValue FLOAT, YValue FLOAT);',
'CREATE TABLE IF NOT EXISTS ENERGY (field VARCHAR, value VARCHAR);',
'CREATE TABLE IF NOT EXISTS TIMES (field VARCHAR, value VARCHAR);',
'CREATE TABLE IF NOT EXISTS REPORT (field VARCHAR, value VARCHAR);',
'CREATE TABLE IF NOT EXISTS OPTIONS (field VARCHAR, value VARCHAR);',
'CREATE TABLE IF NOT EXISTS EMITTERS (Junction VARCHAR, Coefficient FLOAT);',
'CREATE TABLE IF NOT EXISTS QUALITY (Node VARCHAR, InitQual FLOAT);',
'CREATE TABLE IF NOT EXISTS SOURCES (Node VARCHAR, Type VARCHAR, Quality FLOAT, Pattern VARCHAR);',
'CREATE TABLE IF NOT EXISTS REACTIONS (Type VARCHAR, Coefficient FLOAT);',
'CREATE TABLE IF NOT EXISTS MIXING (Tank VARCHAR, Model VARCHAR, Volume FLOAT);',
'CREATE TABLE IF NOT EXISTS COORDINATES (Node VARCHAR, XCoord FLOAT, YCoord FLOAT);',
'CREATE TABLE IF NOT EXISTS VERTICES (Link VARCHAR, XCoord FLOAT, YCoord FLOAT);',
'CREATE TABLE IF NOT EXISTS LABELS (XCoord FLOAT, YCoord FLOAT, Label VARCHAR, Anchor VARCHAR);',
'CREATE TABLE IF NOT EXISTS CONTROLS (control VARCHAR);',
'CREATE TABLE IF NOT EXISTS RULES (ruleID VARCHAR, Rule VARCHAR);',
'CREATE TABLE IF NOT EXISTS BACKDROP (field VARCHAR, value VARCHAR);',
'CREATE TABLE IF NOT EXISTS TAGS (Object VARCHAR, ID VARCHAR, Tag VARCHAR);']
epanet_keywords = ['JUNCTIONS', 'RESERVOIRS', 'TANKS', 'PIPES', 'PUMPS', 'VALVES',
'EMITTERS',
'CURVES', 'PATTERNS', 'ENERGY', 'STATUS', 'DEMANDS',
'QUALITY', 'REACTIONS', 'SOURCES', 'MIXING',
'OPTIONS', 'TIMES', 'REPORT',
'COORDINATES', 'VERTICES', 'LABELS', 'CONTROLS', 'RULES', 'BACKDROP', 'TAGS']
create_tables(tables)
delete_table_values(epanet_keywords)
|
100118bf105bd5ea946dca16d728dab10b43cd6d | andrew-oxenburgh/python-bowling | /src/test/test_bowling.py | 391 | 3.640625 | 4 |
balls = []
def score():
out = ""
for ball in balls:
out += ball
return out
def bowl(cnt):
balls.append(cnt)
return cnt
def _test_frame_1_ball_1():
expected = '0'
bowl('0')
actual = score()
assert actual == expected
def test_frame_1_ball_2():
expected = '00'
bowl('0')
bowl('0')
actual = score()
assert actual == expected
|
dd6c434319031ddc0a68c0684db6e8127e0bc438 | CodeupClassroom/curie-natural-language-processing | /acquire_walkthrough.py | 4,874 | 3.671875 | 4 | import pandas as pd
import numpy as np
from requests import get
import os
from bs4 import BeautifulSoup
def get_all_urls():
'''
This function scrapes all of the Codeup blog urls from
the main Codeup blog page and returns a list of urls.
'''
# The main Codeup blog page with all the urls
url = 'https://codeup.com/resources/#blog'
headers = {'User-Agent': 'Codeup Data Science'}
# Send request to main page and get response
response = get(url, headers=headers)
# Create soup object using response
soup = BeautifulSoup(response.text, 'html.parser')
# Create empty list to hold the urls for all blogs
urls = []
# Create a list of the element tags that hold the href/links
link_list = soup.find_all('a', class_='jet-listing-dynamic-link__link')
# get the href/link from each element tag in my list
for link in link_list:
# Add the link to my urls list
urls.append(link['href'])
return urls
def get_blog_articles(urls, cache=False):
'''
This function takes in a list of Codeup Blog urls and a parameter
with default cache == False which returns a df from a csv file.
If cache == True, the function scrapes the title and text for each url, creates a list of dictionaries
with the title and text for each blog, converts list to df, and returns df.
'''
if cache == False:
df = pd.read_csv('big_blogs.csv', index_col=0)
else:
headers = {'User-Agent': 'Codeup Data Science'}
# Create an empty list to hold dictionaries
articles = []
# Loop through each url in our list of urls
for url in urls:
# get request to each url saved in response
response = get(url, headers=headers)
# Create soup object from response text and parse
soup = BeautifulSoup(response.text, 'html.parser')
# Save the title of each blog in variable title
title = soup.find('h1', itemprop='headline' ).text
# Save the text in each blog to variable text
text = soup.find('div', itemprop='text').text
# Create a dictionary holding the title and text for each blog
article = {'title': title, 'content': text}
# Add each dictionary to the articles list of dictionaries
articles.append(article)
# convert our list of dictionaries to a df
df = pd.DataFrame(articles)
# Write df to csv file for faster access
df.to_csv('big_blogs.csv')
return df
def get_news_articles(cache=False):
'''
This function uses a cache parameter with default cache == False to give the option of
returning in a df of inshorts topics and info by reading a csv file or
of doing a fresh scrape of inshort pages with topics business, sports, technology,
and entertainment and writing the returned df to a csv file.
'''
# default to read in a csv instead of scrape for df
if cache == False:
df = pd.read_csv('articles.csv', index_col=0)
# cache == True completes a fresh scrape for df
else:
# Set base_url and headers that will be used in get request
base_url = 'https://inshorts.com/en/read/'
headers = {'User-Agent': 'Codeup Data Science'}
# List of topics to scrape
topics = ['business', 'sports', 'technology', 'entertainment']
# Create an empty list, articles, to hold our dictionaries
articles = []
for topic in topics:
# Get a response object from the main inshorts page
response = get(base_url + topic, headers=headers)
# Create soup object using response from inshort
soup = BeautifulSoup(response.text, 'html.parser')
# Scrape a ResultSet of all the news cards on the page
cards = soup.find_all('div', class_='news-card')
# Loop through each news card on the page and get what we want
for card in cards:
title = card.find('span', itemprop='headline' ).text
author = card.find('span', class_='author').text
content = card.find('div', itemprop='articleBody').text
# Create a dictionary, article, for each news card
article = ({'topic': topic,
'title': title,
'author': author,
'content': content})
# Add the dictionary, article, to our list of dictionaries, articles.
articles.append(article)
# Why not return it as a DataFrame?!
df = pd.DataFrame(articles)
# Write df to csv for future use
df.to_csv('articles.csv')
return df |
89b454bac0f9b5c3aa0d34b33bea71560962d04d | priyankakl/Pro-Python-Accelerator | /assignment_7.4.py | 981 | 4.03125 | 4 | dict1 = {}
list1 = []
list2 =[]
dict2 = {}
sentence = input("Enter the sentence:")
# To split the sentence into words and form a list
list_of_words = sentence.split(" ")
for word in list_of_words:
# if word has more than one occurance in the sentence, increase its count by 1 each time
if(word in dict1.keys()):
dict1[word] = dict1[word] + int(1)
# if its the first occurance of a word, then keep the count as 1
else:
dict1[word] = int(1)
# separate out numbers, special characters, and alphabets to make sorting easy
for i in dict1.keys():
if ((i.isnumeric() )or (not i.isalpha())):
list1.append(i)
else:
list2.append(i)
# sort both the lists
list1.sort()
list2.sort()
# add both the list1 and list2 data into new dictionary and print
for j in list1:
dict2[j] = dict1[j]
for k in list2:
dict2[k] = dict1[k]
for p, q in dict2.items():
print(p + ":" + str(q))
|
ee9c8db9091ef1d5c47a8839deae5e040ea830ef | osama1998H/standerdLearnd-string | /q68.py | 333 | 3.59375 | 4 | from typing import Counter
string = input('enter some text : ')
a = Counter(string)
d = []
nd = []
for key, value in a.items():
# print(key, value)
if value > 1:
d.append(key)
else:
nd.append(key)
text1 = ''
text2 = ''
for i in d:
text1 += i
for i in nd:
text2 += i
print(text1)
print(text2)
|
e662e9ed381085a602b663970eb6019f09f08039 | michelepeixoto/TextEditor | /TextEditor/TextEditor.py | 3,559 | 4.28125 | 4 | # Notepad style application that can open, edit, and save text documents.
# Optional: Add syntax highlighting and other features.
import os
def open_file():
while True:
try:
path = input("Where is your file located?\n")
os.chdir(path)
name = input("What is the file called?\n")
file = open(name, "w+")
print("File opened successfully.")
break
except:
print("Try again.")
continue
return file
def new_file():
while True:
try:
path = input("Where would you like to create your file?\n")
os.chdir(path)
name = input("What would you like to name it?\n")
file = open(name, "w+")
print("File created successfully.")
break
except:
print("Try again.")
continue
return file
def read_file(file):
print("Opening file in view mode...\n")
file.seek(0)
for lines in file:
print(lines)
pass
pass
def edit_file(file):
print("Opening file in edit mode...\n")
while True:
choice = input("Would add your changes to the beginning (1) or end (2) of the file or replace all text (3)?\n")
if choice == "1":
file.seek(0)
break
elif choice == "2":
file.seek(2)
break
elif choice == "3":
file.seek(0)
file.truncate()
break
else:
print("Invalid input.")
continue
print("Type $quit to end edit mode.\n")
text = ""
while text != "$quit":
text = input()
if text == "$quit":
print("File saved. Exiting edit mode...")
break
else:
file.write(text + "\n")
continue
pass
def delete_file(file):
choice = input("This action is permanent, are you sure you want to delete {}? Enter y/n\n".format(file.name))
if choice == "y":
os.remove(file.name)
print("File deleted.")
main()
pass
else:
print("File was not deleted.")
pass
pass
def rename_file(file):
name = input("What would you like it to be named?\n")
os.rename(file.name, name)
print("File renamed to " + name)
pass
def main():
print("MyTextEditor")
# Get a file:
while True:
choice = input("What would you like to do?\n(1) Open a file\n(2) Create a file\n(3) Quit\n")
if choice == "1":
file = open_file()
break
elif choice == "2":
file = new_file()
break
elif choice == "3":
print("Goodbye!")
file.close()
quit()
break
else:
print("Invalid input.")
continue
pass
# Choose what to do with file:
while choice != "5":
choice = input("(1) Read file\n(2) Edit file\n(3) Rename file\n(4) Delete file\n(5) Quit\n")
if choice == "1":
read_file(file)
pass
elif choice == "2":
edit_file(file)
pass
elif choice == "3":
rename_file(file)
pass
elif choice == "4":
delete_file(file)
pass
elif choice == "5":
print("Goodbye!")
file.close()
quit()
break
else:
print("Invalid input.")
continue
pass
file.close()
pass
main()
|
05366b7f6a9a45e7c48ea892a45455fe8b46747c | Tansiya/tansiya-training-prgm | /sample_question/puzzle.py | 545 | 3.6875 | 4 | """Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?"""
#create a function
def solve(numheads,numlegs):
ns='No solutions!'
#access the for loop
for i in range(numheads+1):
j=numheads-i
#using if condition
if 2*i+4*j==numlegs:
return i,j
return ns,ns
#assigned the num of heads and legs
numheads=35
numlegs=94
solutions=solve(numheads,numlegs)
print (solutions)
|
3a1c605a0c097d525b73d344eb2d514c764e6c12 | csxeba/wiw | /kata/megoldasok/fvdef.py | 1,294 | 3.5625 | 4 | def rendez(*szamok):
"""
Írj egy függvényt, amely sorba rendezi a neki átadott
számokat és visszatér a rendezett számokkal!
"""
return sorted(szamok) # :)
def legnagyobb(*szamok, hanyadik):
"""
Írj egy függvényt, amely visszaadja a neki átadott
számok közül a "hányadik" legnagyobbat.
"""
sorba = sorted(szamok)
return sorba[-hanyadik]
def egyseg_matrix(meret):
"""
Írj egy függvényt, amely adott méretű egységmátrixszal
tér vissza!
A mátrix ebben az esetben egy tuple, amelynek az elemei
is tuple-ök.
Az egységmátrix egy NxN-es számnégyzet, melynek minden
eleme nulla, kivéve a bal felső sarokból a jobb alsó
sarokba futó átlóját.
Például, ha meret=3,
((1, 0, 0),
(0, 1, 0),
(0, 0, 1))
az egységmátrix.
"""
matrix = []
for sor in range(meret):
vektor = []
for oszlop in range(meret):
ertek = 1 if sor == oszlop else 0
vektor += [ertek]
matrix += [vektor]
return matrix
def main():
for vektor in egyseg_matrix(5):
print(vektor)
print(legnagyobb(10, 2, 5, 3, 6, 2, 8, hanyadik=3))
print(rendez(10, 3, 5, 23, 4, 6, 3, 2))
if __name__ == '__main__':
main()
|
2450a802c65e8319b97f86ab861d542295f37c1b | adam-berlak/REL-Studios-Music-Robot | /theory/i_pitched_object.py | 1,615 | 3.5625 | 4 | import abc
class IPitchedObject(abc.ABC):
@abc.abstractmethod
def __eq__(self): pass
@abc.abstractmethod
def __str__(self): pass
@abc.abstractmethod
def __repr__(self): pass
@abc.abstractmethod
def __add__(self, p_object):
'''
Must handle Cases:
isinstance(p_object, Interval): return type(self)
>>> Tone("C", 0) + M3
"E"
'''
pass
@abc.abstractmethod
def __sub__(self, p_object):
'''
Must handle Cases:
Case: isinstance(p_object, Interval)
Return: type(self) Object
>>> Tone("C", 0) - m3
"A"
Case: isinstance(p_object, type(self))
Return: Interval Object
>>> Tone("C", 0) - Tone("A", 0)
"b3"
'''
pass
@abc.abstractmethod
def build(self):
'''
Allows you to build a complex MusicObject off of a PitchedObject
>>> Tone("C", 0).build(Scale, major)
"<Scale I=C, ii=D, iii=E, IV=F, V=G, vi=A, vii=B>"
'''
pass
@abc.abstractmethod
def simplify(self):
'''
Allows for normalization of PitchedObject, used in comparison
>>> Tone("C", -3).simplify()
"A"
>>> Tone("C", -4).simplify()
["A#", "Bb"]
'''
pass
@abc.abstractmethod
def get_tone(self):
'''
Used for getting Tone componant of PitchedObject
>>> Key(Tone("C", 0), 4).getTone()
"C"
>>> Key(Tone("C", 0), 4).getTone() == Key(Tone("C", 0), 5).getTone()
True
'''
pass |
58e389f33f2c1550599fe86979b34cb9b2b94e66 | dmitri-mamrukov/coursera-data-structures-and-algorithms | /course2-data-structures/assignments/assignment_002_make_heap/build_heap.py | 5,356 | 3.703125 | 4 | #!/usr/bin/python3
class MinBinHeap:
def __init__(self):
self._size = 0
self._heap_list = []
def __str__(self):
return str(self._heap_list)
def __repr__(self):
return ('[size=' + str(self.size) +
', list=' + str(self._heap_list) + ']')
@property
def size(self):
return self._size
@property
def elements(self):
return self._heap_list
def _parent(self, i):
return (i - 1) // 2
def _left_child(self, i):
return 2 * i + 1
def _right_child(self, i):
return 2 * i + 2
def _min_child(self, i):
if self._right_child(i) >= self.size:
return self._left_child(i)
else:
left_child = self._left_child(i)
right_child = self._right_child(i)
if self._heap_list[left_child] < self._heap_list[right_child]:
return left_child
else:
return right_child
def _sift_down(self, i):
while self._left_child(i) < self.size:
min_child = self._min_child(i)
if self._heap_list[i] > self._heap_list[min_child]:
self._heap_list[i], self._heap_list[min_child] = \
self._heap_list[min_child], self._heap_list[i]
i = min_child
def _sift_down_and_gen_swaps(self, i, swaps):
while self._left_child(i) < self.size:
min_child = self._min_child(i)
if self._heap_list[i] > self._heap_list[min_child]:
self._heap_list[i], self._heap_list[min_child] = \
self._heap_list[min_child], self._heap_list[i]
swaps.append((i, min_child))
i = min_child
def _sift_up(self, i):
while self._parent(i) >= 0:
parent = self._parent(i)
if self._heap_list[i] < self._heap_list[parent]:
self._heap_list[i], self._heap_list[parent] = \
self._heap_list[parent], self._heap_list[i]
i = parent
def build(self, list):
self._size = len(list)
self._heap_list = list
i = self._parent(self.size - 1)
while i >= 0:
self._sift_down(i)
i -= 1
def build_and_gen_swaps(self, list):
self._size = len(list)
self._heap_list = list
swaps = []
i = self._parent(self.size - 1)
while i >= 0:
self._sift_down_and_gen_swaps(i, swaps)
i -= 1
return swaps
def extract(self):
min_element = self._heap_list[0]
self._heap_list[0] = self._heap_list[self.size - 1]
self._size = self.size - 1
self._heap_list.pop()
self._sift_down(0)
return min_element
def insert(self, i):
self._heap_list.append(i)
self._size = self.size + 1
self._sift_up(self.size - 1)
def change_priority(self, i, p):
if i < 0 or i > self.size:
raise IndexError()
old_priority = self._heap_list[i]
self._heap_list[i] = p
if p > old_priority:
self._sift_down(i)
else:
self._sift_up(i)
class HeapBuilder:
def __init__(self):
self._swaps = []
self._data = []
def read_data(self):
n = int(input())
self._data = [ int(s) for s in input().split() ]
assert n == len(self._data)
def write_response(self):
print(len(self._swaps))
for swap in self._swaps:
print(swap[0], swap[1])
def generate_swaps(self):
"""
The first step of the HeapSort algorithm is to create a heap from the
array you want to sort. By the way, did you know that algorithms
based on Heaps are widely used for external sort, when you need to
sort huge files that dont fit into memory of a computer?
Your task is to implement this first step and convert a given array
of integers into a heap. You will do that by applying a certain number
of swaps to the array. Swap is an operation which exchanges elements
ai and aj of the array a for some i and j. You will need to convert
the array into a heap using only O(n) swaps, as was described in the
lectures. Note that you will need to use a min-heap instead of a
max-heap in this problem.
"""
heap = MinBinHeap()
self._swaps = heap.build_and_gen_swaps(self._data)
def generate_swaps_slow(self):
# The following naive implementation just sorts
# the given sequence using the selection sort algorithm
# and saves the resulting sequence of swaps.
#
# This turns the given array into a heap,
# but in the worst case gives a quadratic number of swaps.
#
# TODO: Replace by a more efficient implementation.
for i in range(len(self._data)):
for j in range(i + 1, len(self._data)):
if self._data[i] > self._data[j]:
self._swaps.append((i, j))
self._data[i], self._data[j] = self._data[j], self._data[i]
def solve(self):
self.read_data()
self.generate_swaps()
self.write_response()
if __name__ == '__main__':
heap_builder = HeapBuilder()
heap_builder.solve()
|
84dc064420786e8143e69afb639a2fb597e78f59 | TUlicai/shark | /screen.py | 536 | 3.609375 | 4 | # -*- encoding: utf-8 -*-
import pygame
from pygame.locals import *
pygame.init()
class Screen:
@staticmethod
def init():
"""
A static method to use the SAME rect all the time.
Like this, it is way easier to change it when the user resize the screen
"""
Screen.screen = pygame.display.get_surface()
Screen.rect = Screen.screen.get_rect()
def __str__(self):
return '<Screen width={} height={}>'.format(
Screen.rect.width, Screen.rect.height)
|
e2ef301b4e3939c57d3ab402ddc57512ed2aed34 | lschnellmann/LPTHW | /ex4.py | 1,852 | 4.09375 | 4 | # number of cars total
cars = 100
# number of people who can fit in each car
space_in_a_car = 4
#available drivers
drivers = 30
# available passengers
passengers = 90
# cars idle.. since there are 100 cars, and only 30 drivers, 70 idle cars
cars_not_driven = cars - drivers
# it follows that with 30 drivers only 30 cars will be driven
cars_driven = drivers
# total number of people that can be transported (including drivers)
carpool_capacity = cars_driven * space_in_a_car
#some more.. some less.. may be a floating point number of passengers per car driven
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
# Traceback (most recent call last): an exception error most recent call in file ex4.py, in line 8
# in the module (program).. 'car_pool_capacity' was not defined with a variable values
#study drills if you use just 4 instead of 4.0 then it turns into integers instead of
# floating point numbers.
#I used 4.0 for space_in_a_car, but is that necessary? What happens if it's just 4?
#Remember that 4.0 is a floating point number. It's just a number with a decimal point, and you need 4.0 instead of just 4 so that it is floating point.
#Write comments above each of the variable assignments.
#Make sure you know what = is called (equals) and that it's making names for things.
#Remember that _ is an underscore character.
#Try running python from the Terminal as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j.
|
3b9082bdfdc5673a40a7dd33b107cc17bda9ead6 | AP-MI-2021/lab-2-SiminaPop | /main.py | 2,788 | 3.6875 | 4 | #pb3
def is_prime(n):
"""
:param n: numar natural
:return: True daca numarul n este prim si False daca numarul n nu este prim
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for d in range(3, n // 2, 2):
if n % d == 0:
return False
return True
def test():
assert is_prime(3)==True
def get_goldbach(n):
"""
:param n: n numar natural
:return: scrierea numarului n ca suma de 2 numere prime
"""
for i in range(2, n):
if is_prime(i):
if is_prime(n - i):
return i, n - i
return False
def test_get_goldbach():
assert get_goldbach(16) == (3, 13)
assert get_goldbach(15) == (2, 13)
#pb12
def pp(n):
'''Verifica daca un nr este patrat perfect
:param: n
:return: 1 daca nr este pp, 0 daca nu'''
for i in range(1, n//2+1):
if n==i*i:
return 1
return 0
def testpp():
assert pp(4)==1
assert pp(3)==0
def get_perfect_squares(start,stop):
'''Adauga in lista elementele de tip pp
:param: start (lista)
:return: list (alta lista)'''
list=[]
for x in range(start,stop):
if pp(x)==1:
list.append(x)
return list
def test_get_perfect_squares():
assert get_perfect_squares(2,5)==[4]
assert get_perfect_squares(3,17)==[4,9,16]
#Pb5
def is_palindrome(n):
'''Verifica daca un numar este palindrom
:param: n: un numar intreg
:return: true daca numarul este palindrom si false in rest '''
aux=n
pal=0
while n>0:
ultima_cifra=n%10
pal=pal*10+ultima_cifra
n=n//10
if aux==pal:
return True
return False
def test_is_palindrome():
assert is_palindrome(12321)==True
assert is_palindrome(1123) == False
assert is_palindrome(232) == True
def meniu():
print('''
1.Pb3
2.Pb12
3.Pb5
4.Afara''')
def main():
# interfata de tip consola aici
test()
test_get_goldbach()
testpp()
test_get_perfect_squares()
test_is_palindrome()
while True:
meniu()
cmd = input("Comanda:")
if cmd == '1':
n = int(input("introduceti un numar intreg n"))
print(get_goldbach(n))
elif cmd == '2':
elem1= int(input("introduceti capatul inferior al intervalului inchis"))
elem2=int(input("introduceti capatul superior al intervalului inchis"))
print(get_perfect_squares(elem1,elem2))
elif cmd == '3':
n = int(input("introduceti un numar posibil palindrom "))
print(is_palindrome(n))
elif cmd == '4':
break
else:
print('comanda invalida')
if __name__ == '__main__':
main()
|
fe30b9fa0940e6f9e1e624885b53c9869b862d79 | YuLili-git/leetcode_offer | /剑指 Offer 63. 股票的最大利润.py | 763 | 3.578125 | 4 | #假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
#示例 1:
#输入: [7,1,5,3,6,4]
3输出: 5
#解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
# 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
#示例 2:
#输入: [7,6,4,3,1]
#输出: 0
#解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
cost = float("inf")
profit = 0
for i in prices:
cost = min(cost, i)
profit = max(profit, i - cost)
return profit
|
516cab1e6a5ea3e7fa178c33e049d0536fb51767 | lugia493/Leet-Code | /Binary Trees/n_ary_max_depth.py | 768 | 3.65625 | 4 |
def max_depth(root):
# If we have a None root, return 0
if not root:
return 0
# if the children of a root is None, return 1 for that rot
if not root.childen:
return 1
# We need the two condtions if we run into a tree that has some
# valid nodes and some None nodes.
# i.e. 5 (3 children) -> 1,2,None
return max(max_depth(child) for child in root.children) + 1
# Iterative solution
def dfs(self, d, node):
if len(node.children) == 0:
if d > maxDepth.mDepth:
maxDepth.mDepth = d
return
for child in node.children:
self.dfs(d+1, child)
def maxDepth(self, root):
if root == None:
return 0
dfs(1, root)
return maxDepth.mDepth
maxDepth.mDepth = 0
|
725c5de6688287c88421464ef331858e4496d585 | susunini/leetcode | /169_Majority_Element.py | 1,793 | 3.859375 | 4 | class Solution(object):
""" Hash Table. Time O(n) Space O(n)"""
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dic = collections.Counter(nums)
for key, val in dic.items():
if val > n/2:
return key
class Solution(object):
""" Kth Largest Element. """
def findKthLargest(self, nums, k):
"""
Divide and Conquer (Quick Select). Best Case O(n) Worst Case O(n^2) Average Case O(n)
:type nums: List[int]
:type k: int
:rtype: int
"""
if k > len(nums):
return None
if k == 1:
return max(nums)
if len(nums) == k:
return min(nums)
pivot = nums[0]
left = [num for num in nums if num < pivot]
equal = [num for num in nums if num == pivot]
right = [num for num in nums if num > pivot]
if len(right) >= k:
return self.findKthLargest(right, k)
elif len(right)+len(equal) >= k:
return pivot
else:
return self.findKthLargest(left, k-len(right)-len(equal))
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return self.findKthLargest(nums, len(nums)/2+1)
class Solution(object):
""" Moore's Voting. Time O(n) Space O(1). """
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = nums[0]; cnt = 1
for num in nums[1:]:
if num == res:
cnt += 1
elif cnt > 1:
cnt -= 1
else:
res = num; cnt = 1
return res
|
8bc1524c67af607e6a23e798996516f8dca88079 | kmgaurav2611/GFG_Solutions | /extra/sol.py | 504 | 3.796875 | 4 | def printArray(arr, size):
for i in range(size):
print(arr[i], end = " ")
print()
return
def getSuccessor(arr, k, n):
p = k - 1
while (arr[p] == n and 0 <= p < k):
p -= 1
if (p < 0):
return 0
arr[p] = arr[p] + 1
i = p + 1
while(i < k):
arr[i] = 1
i += 1
return 1
def printSequences(n, k):
arr = [0] * k
for i in range(k):
arr[i] = 1
while(1):
printArray(arr, k)
if(getSuccessor(arr, k, n) == 0):
break
return
n = 5
k = 2
printSequences(n, k)
|
3c408ac15657a3c40796d15fe84477cfe170181f | MelvilQ/stacksrs-web | /importMemriseCourse.py | 2,172 | 3.5 | 4 | import csv
import sys
import requests
from bs4 import BeautifulSoup
courseId = sys.argv[1]
invertColumns = sys.argv[2] == 'i' if len(sys.argv) > 2 else False
# load course overview page
courseUrl = 'https://www.memrise.com/course/' + courseId
response = requests.get(courseUrl)
if response.status_code != 200:
print('Could not load course from Memrise...')
exit()
courseUrl = response.url
# load chapter pages
print('Loading chapters...')
pages = []
chapter = 1
hasNextChapter = True
while hasNextChapter:
chapterUrl = courseUrl + str(chapter) + '/'
response = requests.get(chapterUrl)
if response.status_code != 200 or response.url == courseUrl:
hasNextChapter = False
break
html = response.text
pages.append(html)
print(chapter)
chapter += 1
print('This course has ' + str(len(pages)) + ' chapters')
# prompt some data from user
fileName = input('Please enter a filename for the deck to be generated (without ending): ')
deckName = input('Please enter a name for the deck: ')
front = input('Please enter the two-letter language code for the front language: ')
back = input('Please enter the two-letter language code for the back language: ')
# parse chapters
rows = [[deckName], [front, back, 'Thema']]
for html in pages:
soup = BeautifulSoup(html, 'html.parser')
headings = soup.findAll('h3')
if len(headings) > 0:
chapterName = headings[0].text.strip()
else:
chapterName = str(soup.title.string).strip()
divs = soup.findAll('div', {'class':'text'})
words = [div.text.strip() for div in divs if 'col text"' not in str(div)]
for i in range(0, len(words)):
if i % 2 == 1 or i == len(words) - 1:
continue
if invertColumns:
front = words[i]
back = words[i+1]
else:
front = words[i+1]
back = words[i]
front = front.replace('‹', '').replace('›', '')
back = back.replace('‹', '').replace('›', '')
if i == 0:
rows.append([front, back, chapterName])
else:
rows.append([front, back])
# write csv file
with open(fileName + '.csv', 'w') as csvfile:
writer = csv.writer(csvfile, dialect = csv.excel_tab)
writer.writerows(rows)
print('Successfully generated CSV file with ' + str(len(rows)) + ' lines')
|
4c8384392349801c4dd704e2af762707d2340fa6 | pauleclifton/GP_Python210B_Winter_2019 | /students/daniel_carrasco/session03/list_lab.py | 948 | 3.953125 | 4 | #!/usr/bin/env python3
#task1
list1 = ['Apples','Pears','Oranges','Peaches']
print(list1)
response = input(" name another fruit ")
list1.append(response)
print(list1)
response2 = input(" name a number ")
print(f'the {response2}rd item in the list is {list1[int(response2)-1]}')
list1 = ['Cherry']+list1
print(list1)
list1.insert(0,'Kiwi')
for value in list1:
if 'P' in value[0]:
print(value)
#task 2
print(list1)
list1.pop()
print(list1)
response3 = input(" name a fruit to delete ")
for num,value in enumerate(list1):
if response3 in value:
list1.pop(num)
print(list1)
#task 3
for num,value in enumerate(list1):
response4 = ''
while response4 != 'yes' and response4 != 'no':
response4 = input(f'Do you like {value.lower()}?')
print(response4)
if response4 =='no':
list1.pop(num)
print(list1)
#task 4
list2 = [value[::-1] for value in list1]
print(list2)
list1.pop()
print(list1,list2)
|
8475a0c56b3f72a9f367e191c90b97b6c04158a8 | mani-9642/mani-9642 | /armstrong loop.py | 336 | 3.9375 | 4 | ch="y"
while ch=="y":
n = int(input("Enter the Number : "))
s = 0
t = n
while t>0:
r=t%10
s+=r**3
t//=10
if n==s:
print(n,"is Armstrong Number")
else:
print(n,"is not a Armstrong Number")
ch=input("Do you want to check again (Y/N) : ")
print("Thank You") |
3b5e1cd67f36e17db8c7bb2a29982fc1a85ba176 | XMK233/Information-Security-Experiment | /14061075_修闽珂_实验二/Greatest_Common_Divisor.py | 2,480 | 3.703125 | 4 | '''hui dai fa'''
import time
a = int( input ( "the a is: " ) )
b = int( input ( "the b is: " ) )
s = [ 0 ]
t = [ 0 ]
i = 0
'''do some change if a is larger than b'''
convertA = convertB = 1
if a < 0 and b >= 0:
a = abs( a )
convertA = -1
elif b < 0 and a >= 0:
b = abs( b )
convertB = -1
elif a < 0 and b < 0:
a = abs( a )
b = abs( b )
convertA = -1
convertB = -1
'''if the number is minus'''
changePlace = 0
if a > b:
r0 = largerOne = a
convertL = convertA
r1 = smallerOne = b
convertS = convertB
else:
r0 = largerOne = b
convertL = convertB
r1 = smallerOne = a
convertS = convertA
changePlace = 1
'''the essence of the algorithm'''
strTime = time.time()
while True:
'''if the 0 is one of the two number'''
if a == 0 and b > 0:
sFin = 0
tFin = 1
gcd = b
print ( "the s, t and gcd( a,b ) is: ", sFin , tFin , gcd)
break
elif b == 0 and a > 0:
sFin = 1
tFin = 0
gcd = a
print ( "the s, t and gcd( a,b ) is: ", sFin , tFin , gcd)
break
elif b == a == 0:
sFin = 0
tFin = 0
gcd = 0
print ( "the s, t and gcd( a,b ) is: ", sFin , tFin , gcd)
break
'''the other situation'''
r2 = r0 % r1
q = int( r0 / r1 )
'''the smaller one is the gcd'''
if r0 % r1 == 0 and i == 0:
sFin = 0
tFin = convertS
gcd = r1
if a > b:
print ( "the s, t and gcd( a,b ) is: ", sFin ,",", tFin ,",", gcd)
else:
print ( "the s, t and gcd( a,b ) is: ", tFin , sFin , gcd)
break
'''if the gcd need to do the hui dai iteration'''
if r0 % r1 :
if i == 0:
s[ i ] = 1
t[ i ] = -1 * q
elif i == 1:
s.append( -1 * q )
t.append( -1 * q * t[ 0 ] + 1 )
else:
s.append( s[ i - 2 ] - q * s[ i - 1])
t.append( t[ i - 2 ] - q * t[ i - 1])
i += 1
r0 = r1
r1 = r2
else:
sFin = convertL * s[ len(s) - 1 ]
tFin = convertS * t[ len(t) - 1 ]
gcd = r1
if a > b:
print ( "the s, t and gcd( a,b ) is: ", sFin , tFin , gcd)
else:
print ( "the s, t and gcd( a,b ) is: ", tFin , sFin , gcd)
break
'''get the time'''
endTime = time.time()
print ( "the time is: ", endTime - strTime, "s")
|
cde78c98307415e2311bca0f6d13c09802d416bc | bbjy/MachineLearningHomework | /ml2018-hw3/code/Multiboosting.py | 6,817 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
This is an implementation of <MultiBoosting: A Technique for Combining
Boosting and Wagging>, GEOFFREY I. WEBB, 2000.
"""
# @author: WangBei
# 2018-12-09
import math
from math import e, log,exp
import numpy as np
from numpy import *
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import time
from sklearn.model_selection import train_test_split
import os
import processdata
from sklearn.model_selection import cross_val_score
class Adaboost(object):
"""
Adaboost(X, y, estimator = DecisionTreeClassifier, itern = 20, mode = "sign")
Basic Adaboost to solve two-class problem
Parameters
----------
X: numpy 2d array (m samples * n features)
y: numpy 1d array (m samples' label)
estimator: base_estimator of boosting
itern: number of iterations
mode: sign mode output label directly, while num mode output a confidence
rate x. The more positive x is ,the more likely the label is Adaboost.cls0;
the more negative x is, the more likely the label is not Adaboost.cls0
"""
def __init__(self, X, y, estimator = DecisionTreeClassifier, itern = 20):
self.X = X
self.y = y.copy()
self.estimator = estimator
self.itern = itern
self.estimators = [] # estimators produced by boosting algorithm
self.betas = np.array([]) # weights of each boost estimator
self.m = self.X.shape[0] # number of samples
self.w = np.ones((self.m )) # weights of samples
# self.max_depth = max_depth
self.bootstrap = range(0,self.m)
@staticmethod
def bootstrap_sample(data_num):
idx = np.random.randint(0,data_num,size=(data_num))
return idx
def train(self):
m = self.m
# print "round number: ",self.itern
for k in range(self.itern):
clf = self.estimator()
clf.fit(self.X[self.bootstrap], self.y[self.bootstrap])
y_predict = clf.predict(self.X[self.bootstrap])
error = 0 # number of wrong prediction
for i in range(m):
if y_predict[i] != self.y[i]:
error += self.w[i]
error = 1.0* error/m
if error > 0.5:
self.bootstrap = self.bootstrap_sample(m)
self.w = np.ones((m))
continue
elif error == 0:
self.betas = np.append(self.betas, 1e-10)
self.bootstrap = self.bootstrap_sample(m)
self.w = np.ones((m))
else:
beta = float(log((1.0 - error) / error)) # estimator weight
self.betas = np.append(self.betas, beta)
for i in range(m): # update sample weights
if y_predict[i] != self.y[i]:
self.w[i] /= (2.0*error)
else:
self.w[i] /= (2.0*(1-error))
if self.w[i] < 1e-8:
self.w[i] = 1e-8
self.estimators.append(clf)
def test(self, X_test, y_test):
"""return precision of trained estimator on x_test and y_test"""
result = []
# y_test = list(y_test)
for i in range(X_test.shape[0]):
result.append([])
for index, estimator in enumerate(self.estimators):
y_test_result = estimator.predict(X_test)
for index2, res in enumerate(result):
res.append([y_test_result[index2], np.log(1/self.betas[index])])
final_result = []
# vote
for res in result:
dic = {}
for r in res:
dic[r[0]] = r[1] if not dic.has_key(r[0]) else dic.get(r[0]) + r[1]
final_result.append(sorted(dic, key=lambda x:dic[x])[-1])
# print (float(np.sum(final_result == y_test)) / len(y_test))
test_score = float(np.sum(final_result == y_test)) / len(y_test)
return final_result,test_score
class MultiBoosting(Adaboost):
# def __init__(self, X, y,estimator = DecisionTreeClassifier, itern = 100):
# super(MultiBoosting, self).__init__(X,y,estimator,itern)
def __init__(self, X, y,estimator = DecisionTreeClassifier, itern = 100):
super(MultiBoosting, self).__init__(X,y,estimator,itern)
self.iterations = []
self.current_iteration = 0
self.set_iterations()
# sample from poisson
@staticmethod
def poisson_sample(data_num):
bootstrap = []
for i in range(data_num):
tmp = data_num+1
while tmp >= data_num:
tmp = np.random.poisson(i, 1)
bootstrap.append(tmp[0])
return bootstrap
# Table 3. Determining sub-committee termination indexes.
def set_iterations(self):
n = int(float(self.itern)**0.5)
for i in range(n):
self.iterations.append(math.ceil((i+1)*self.itern *1.0/n))
for i in range(self.itern):
self.iterations.append(self.itern)
def train(self):
m = self.m
w = self.w
# print "round number: ",self.itern
for t in range(self.itern):
if self.iterations[self.current_iteration] == t:
self.bootstrap = self.poisson_sample(m)
self.w = np.ones((m))
self.current_iteration+=1
clf = self.estimator()
clf.fit(self.X[self.bootstrap], self.y[self.bootstrap])
y_predict = clf.predict(self.X[self.bootstrap])
error = 0 # number of wrong prediction
for i in range(m):
if y_predict[i] != self.y[i]:
error += self.w[i]
error = error/m
if error > 0.5:
self.bootstrap = self.poisson_sample(m)
self.w = np.ones((m))
self.current_iteration+=1
continue
elif error == 0:
self.betas = np.append(self.betas, 1e-10)
self.bootstrap = self.poisson_sample(m)
self.w = np.ones((m))
self.current_iteration+=1
else:
beta = float(log((1.0 - error) / error)) # estimator weight
self.betas = np.append(self.betas, beta)
for i in range(m): # update sample weights
if y_predict[i] != self.y[i]:
self.w[i] /= (2*error)
else:
self.w[i] /= (2*(1-error))
for i in range(m):
if self.w[i] < 1e-8:
self.w[i] = 1e-8
self.estimators.append(clf)
|
32d213205f737069a2f84bda3a333bcfb2b2aa81 | AronIS98/Basic | /Forritun/Aron_verkefni/Prof_2019.py | 1,567 | 4.09375 | 4 | def get_input():
"""gets the input from the user"""
user_input = input("Enter an ISBN: ")
return user_input
def input_to_list(the_input):
word_as_list = [item for item in the_input]
return word_as_list
def is_valid(input_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION):
if len(input_as_list) == LENGTH_OF_ISBN:#checks desired length
for index in PLACEHOLDER_POSITION:
if input_as_list[index] != "-":#checks if the placeholde ("-") is at the right place
return False
for number in range(LENGTH_OF_ISBN-1):
#Checks if the numbers are at the right places
if number not in PLACEHOLDER_POSITION:
try:
int(input_as_list[number])
except ValueError:
return False
return True
return False
def main():
LENGTH_OF_ISBN = 13 #A constant to change the desired length of ISBN with ease
PLACEHOLDER_POSITION = [1,5,11] #List to change the positions of placeholders with ease.
QUIT = "q"
valid = False
user_input = ""
"""the main function"""
while user_input != QUIT:
user_input = get_input()
word_as_list = input_to_list(user_input)
valid = is_valid(word_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION)
if valid:
print("Valid format!")
elif user_input != QUIT:
print("Invalid format!")
#The main function is executed.
main() |
b4a242ef9c3c2ada77992889bcbb1280620f0639 | materdd/python_tutorial | /tutorial_5.py | 5,774 | 3.75 | 4 | ###### Pythonの基礎 #####
# GOAL: Numpy、Scipy、Pandas、Matplotlibのライブラリを
# 読み込みそれらの基本的な役割を知る
""" 便利ライブラリ(関数群)
Numpy: 多次元配列処理
Pandas: 表計算やデータベースのようなデータ操作
Matplotlib: データ可視化(プロット)
"""
#----- numpy -----#
# %% numpy module import
"""
多次元配列を処理することができます。
実際に扱うデータは多次元であることが多く、
その処理をするためにNumpyを使うと便利です。
また、NumpyはCで実装されており、処理が高速です。
"""
# numpyライブラリの読み込み
import numpy as np
# %% initialize
sample_numpy_data = np.array([9,2,3,4,10,6,7,8,1,5])
print(sample_numpy_data)
# %% list -> numpy
temp = [0,1,2,3,565,3]
temp = np.array(temp)
print(type(temp))
# %%
# 型の表示
print("型の表示", sample_numpy_data.dtype)
# 次元数
print("次元数:", sample_numpy_data.ndim)
# 要素数
print("要素数:", sample_numpy_data.size)
# %%
# それぞれの要素同士での演算
print("掛け算:",np.array([1,2,3,4,5,6,7,8,9,10]) * np.array([10,9,8,7,6,5,4,3,2,1]))
print("累乗:",np.array([1,2,3,4,5,6,7,8,9,10]) **2)
print("割り算:",np.array([1,2,3,4,5,6,7,8,9,10]) / np.array([10,9,8,7,6,5,4,3,2,1]))
# %%
# 0や1の初期化データ
# (2,3)は2行3列の行列データを作っています。
zero_data = np.zeros((2,3), dtype=np.int32)
one_data = np.ones((2,3), dtype=np.float32)
print("0でint型 \n", zero_data)
print("1でfloat型 \n", one_data)
# %%
# 値が大きい順に並び替える
print("そのまま:",sample_numpy_data)
# sorting
sample_numpy_data.sort()
print("ソート後:",sample_numpy_data)
# 最小値
print("Min:",sample_numpy_data.min())
# 最大値
print("Max:",sample_numpy_data.max())
# 合計
print("Sum:",sample_numpy_data.sum())
# %%
# データ準備
sample_multi_array_data = np.arange(9)
print("initialize: \n", sample_multi_array_data)
sample_multi_array_data = sample_multi_array_data.reshape(3,3)
print("reshape: \n", sample_multi_array_data)
# 行の抜き出し
print("行の抜き出し: \n", sample_multi_array_data[0,:])
# 列の抜き出し
print("列の抜き出し: \n", sample_multi_array_data[:,0])
#----- pandas -----#
# %%
"""
Pandasを使うと、データの様々なハンドリングをスムーズに柔軟に実施することができ、
表計算や後ほど学ぶデータベースのようなデータ操作が可能となります。
"""
# import
from pandas import Series,DataFrame
import pandas as pd
# %%
# series(配列のようなオブジェクト)
sample_pandas_data = pd.Series([10,11,12,13,14,15,16,17,18,19])
print(sample_pandas_data)
# プロパティを表示
print("データの値:",sample_pandas_data.values)
print("インデックスの値:",sample_pandas_data.index)
# %% インデックスのラベル指定
sample_pandas_index_data = pd.Series([10,11,12,13,14,15,16,17,18,19]
,index=['a','b','c','d','e','f','g','h','i','j'])
print(sample_pandas_index_data)
print("データの値:",sample_pandas_index_data.values)
print("インデックスの値:",sample_pandas_index_data.index)
# %% DataFrame(各々の列で異なる型を持たせることが可能)
attri_data1 = {'ID':['100','101','102','103','104']
,'city':['Tokyo','Osaka','Kyoto','Hokkaidao','Tokyo']
,'birth_year':[1990,1989,1992,1997,1982]
,'name':['Hiroshi','Akiko','Yuki','Satoru','Steeve']}
attri_data_frame1 = DataFrame(attri_data1)
print(attri_data_frame1)
# %%
# 列の抜き取り(一つ)
print(attri_data_frame1.birth_year)
# 列の抜き取り(複数)
attri_data_frame1[["ID","birth_year"]]
# %%
# 条件(フィルター)
attri_data_frame1[attri_data_frame1['city']=='Tokyo']
# 条件(フィルター、複数の値)
attri_data_frame1[attri_data_frame1['city'].isin(['Tokyo','Osaka'])]
# %% データの列の削除
attri_data_frame1.drop(['birth_year'],axis=1)
"""
その他、Dataframe同士の統合、ソーティング等の様々な機能が存在。
excelと同じような利便性で利用可能
"""
# %% excel dataの読み込み
df = pd.read_excel("data/tutorial_4_1.xlsx")
print(df)
# %% excelに保存
attri_data_frame1.to_excel("data/tutorial_4_pandas_to_excel.xlsx", sheet_name="test")
#----- matplotlib -----#
# %%
"""
データを可視化する
https://matplotlib.org/
"""
# import
# matplotlib と seabornの読み込み
# seabornはきれいに図示できる
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
# ここで表示させるために必要なマジックコマンド
%matplotlib inline
# %% 散布図
import numpy.random as random
import numpy as np
# シード値の固定
random.seed(0)
# x軸のデータ
x = np.random.randn(30)
# y軸のデータ
y = np.sin(x) + np.random.randn(30)
# plot
plt.plot(x, y, "o")
#以下でも散布図が描ける
#plt.scatter(x, y)
# title
plt.title("Title Name")
# Xの座標名
plt.xlabel("X")
# Yの座標名
plt.ylabel("Y")
# gridの表示
plt.grid(True)
# %% 連続曲線
np.random.seed(0)
# データの範囲
numpy_data_x = np.arange(1000)
# 乱数の発生と積み上げ
numpy_random_data_y = np.random.randn(1000)
# label=とlegendでラベルをつけることが可能
plt.plot(numpy_data_x,numpy_random_data_y,label="Label")
plt.legend()
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
# %% sin関数
# 2行1列のグラフの1つ目
plt.subplot(2,1,1)
x = np.linspace(-10, 10, 100)
plt.plot(x, np.sin(x))
# 2行1列のグラフの2つ目
plt.subplot(2,1,2)
y = np.linspace(-10, 10, 100)
plt.plot(y, np.sin(2*y))
plt.grid(True)
|
24df668bdbf0ca9f1e9672cfe11e480a9f5af389 | blackplusy/python1119 | /例子-1120-05.列表的访问.py | 120 | 3.734375 | 4 | #coding=utf-8
l=['58','ganji','zhilian','51job']
print(l)
for a in l:
print(a)
if '58' in l:
print('58 is here!')
|
3c7fdcc0cccb84c1c8241c5fcf59a497c19e0f51 | NicholasTing/Competitive_Programming | /CodeForces_651/c.py | 908 | 3.90625 | 4 | from functools import lru_cache
t = int(input())
player_one = 'Ashishgup'
player_two = 'FastestFinger'
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
@lru_cache(maxsize=None)
def isWinning(n):
if int(n) == 1:
return False
elif int(n) == 2:
return True
if n % 2 == 0:
# print('greatest odd')
greatest_odd_divisor = n/2
# print(n/greatest_odd_divisor)
isWinning(n/greatest_odd_divisor)
else:
isWinning(n-1)
return True
while t != 0:
t -= 1
n = int(input())
if isWinning(n):
print(player_one)
else:
print(player_two)
|
4792bf1b27d0bdb3b8b61a9e42d389c572e504a2 | rishikeshpuri/Algorithms-and-Data-Structure | /tree/level order data in reverse order.py | 725 | 4.125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def reverseLevelOrder(root):
queue = []
stack = []
queue.append(root)
while len(queue)>0:
root = queue.pop(0)
stack.append(root)
if root.right:
queue.append(root.right)
if root.left:
queue.append(root.left)
while len(stack)>0:
root = stack.pop()
print (root.value, end=' ')
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.right.left = Node(6)
tree.right.right = Node(7)
print("Level Order traversal of binary tree is")
reverseLevelOrder(tree) |
124d9c7036622d334bcbdf06b6bac76659afaf89 | MichaelWoo-git/Apriori_Algorithm_from_Scratch | /Apriori_Algo.py | 10,634 | 3.5625 | 4 | # Imports
import numpy as np
import pandas as pd
import os
import time
from itertools import permutations, combinations
from IPython.display import display
# this will display the max column width so we can see the associations involved....
pd.set_option('display.max_colwidth', None)
pd.set_option('display.max_columns', None)
# Prompts to choose which store you want
print("Welcome to Apriori 2.0!")
store_num = input("Please select your store \n 1. Amazon \n 2. Nike \n 3. Best Buy \n 4. K-Mart \n 5. Walmart\n")
print(store_num)
support_percent = input("Please enter the percentage of Support you want?\n")
print(support_percent)
confidence_percent = input("Please enter the percentage of Confidence you want?\n")
print(confidence_percent)
# These are my dictionaries to choose which store to get based in Key-Value Pairs
def number_to_store(store_number):
switcher = {
1: "data/amazon_transactions.csv",
2: "data/nike_transaction.csv",
3: "data/best_buy_transaction.csv",
4: "data/k_mart_transaction.csv",
5: "data/walmart_transaction.csv"
}
return switcher.get(store_number)
def number_to_item_list_of_store(store_number):
switcher_dict = {
1: "data/amazon_item_names.csv",
2: "data/nike_item_names.csv",
3: "data/best_buy_item_names.csv",
4: "data/k_mart_item_names.csv",
5: "data/walmart_item_names.csv"
}
return switcher_dict.get(store_number)
def ns(store_number):
switcher_store = {
1: "Amazon",
2: "Nike",
3: "Best Buy",
4: "K-Mart",
5: "Walmart"
}
return switcher_store.get(store_number)
# We first have to read in the csv files and make sure that the inputs received from the user are valid
def a_priori_read(item_list, transaction, support_percentage, confidence_percentage):
# Create two different functions one that is solo for read in the file data and the other that is algorithmic with the data
if support_percentage > 100 or confidence_percentage > 100 or support_percentage < 0 or confidence_percentage < 0:
print("Support Percent or Confidence Percent is Invalid. \n Enter a valid number between 0 and 100.\n")
print("Restarting Apriori 2.0.....\n")
time.sleep(2)
os.system("python Aprior_Algo")
if support_percentage >= 0 and support_percentage <= 100 and confidence_percentage >= 0 and confidence_percentage <= 100:
df_item_list = pd.read_csv(item_list)
df_transactions = pd.read_csv(transaction)
print(df_transactions.head())
print(df_item_list.head())
trans = np.array(df_transactions["transaction"])
items_names = np.array(df_item_list["item_name"])
k_value = 1
return items_names, trans, support_percentage, confidence_percentage, k_value
# The first go around of the Apriori Algorithm we find the items that are most frequent when K=1
# This is so that we can find the most frequent items given the transactions
def ap_1(items_names, trans, support_percentage, confidence_percentage, k_value):
counter = np.zeros(len(items_names), dtype=int)
for i in trans:
i = list((map(str.strip, i.split(','))))
s1 = set(i)
nums = 0
for x in items_names:
s2 = set()
s2.add(x)
if s2.issubset(s1):
counter[nums] += 1
nums += 1
counter = list(map(lambda x: int((x / len(trans)) * 100), counter))
df3 = pd.DataFrame({"item_name": items_names, "support": counter, "k_val": np.full(len(items_names), k_value)})
rslt_df = df3[df3['support'] >= support_percentage]
print("When K = " + str(k_value))
print(rslt_df)
items = np.array(rslt_df["item_name"])
support_count = np.array(rslt_df["support"])
k_value += 1
return items, support_count, k_value, rslt_df
# Then we use this function below to find item sets that are most frequent when K > 1
def ap_2(item_comb, k_value, trans, support_percentage):
boo = True
comb = combinations(item_comb, k_value)
comb = list(comb)
counter = np.zeros(len(comb), dtype=int)
if k_value > 1:
for i in trans:
i = list((map(str.strip, i.split(','))))
s1 = set(i)
nums = 0
for x in comb:
s2 = set()
x = np.asarray(x)
for q in x:
s2.add(q)
if s2.issubset(s1):
counter[nums] += 1
nums += 1
counter = list(map(lambda x: int((x / len(trans)) * 100), counter))
df3 = pd.DataFrame({"item_name": comb, "support": counter, "k_val": np.full(len(comb), k_value)})
# Making sure that user parameters are met for support
rslt_df = df3[df3['support'] >= support_percentage]
print("When K = " + str(k_value))
print(rslt_df)
items = np.array(rslt_df["item_name"])
supp = np.array(rslt_df["support"])
if len(items) == 0:
boo = False
return rslt_df, boo
return rslt_df, boo
# Calls of functions and variable saving
frames = []
items_names, trans, support_percent, confidence_percent, k_value = a_priori_read(
str(number_to_item_list_of_store(int(store_num))), str(number_to_store(int(store_num))),
int(support_percent), int(confidence_percent))
items, supp, k_value, df = ap_1(items_names, trans, support_percent, confidence_percent, k_value)
frames.append(df)
boo = True
# Increasing K by 1 until we can longer support the support value
while boo:
df_1, boo = ap_2(items, k_value, trans, support_percent)
frames.append(df_1)
k_value += 1
# Combine the dataframes we have from when we increase K
print("results of item-sets that meet support are below")
display(pd.concat(frames))
df_supp = pd.concat(frames)
# df_supp.head()
# Reset the index just to organize it and the results after we find the most frequent sets in the list of transactions
df_supp = df_supp.reset_index().drop('index', axis=1)
df_supp
# This is the FUNCTION that generates the Associations (Permutations) and calculating the Confidence of the item sets
def confidence(val):
# Since we already have our support for our items what we need to worry about is the confidence levels
# item_set before the arrow
df_before = df_supp.loc[df_supp['k_val'] == val]
stuff_name_before = np.array(df_before["item_name"])
support_arr_before = np.array(df_before['support'])
# item_set of the overall set
df_overall = df_supp.loc[df_supp['k_val'] == val + 1]
df_ov = np.array(df_overall["item_name"])
suppport_ov = np.array(df_overall['support'])
# variables to save
sup_ov = list()
sup_sing = list()
perm_item = list()
# When the item set is k =1 and the comparison is k = 2
if val == 1:
for i_set in df_ov:
temp_list = list(df_ov)
# I want to select the support of that overall set
ov_sup = suppport_ov[temp_list.index(i_set)]
temp = set()
# This is where we generate our permutations
for indiv_item in i_set:
temp.add(indiv_item)
perm = permutations(temp)
perm_lst = list(perm)
# for each permutation in the perm_list
for perm_item_set in perm_lst:
perm_item.append(perm_item_set)
sup_ov.append(ov_sup)
sup_sing.append(int(support_arr_before[np.where(stuff_name_before == perm_item_set[0])]))
# When the item set is k > 1 and the comparison is k += k + 1
if val > 1:
for i_set in df_ov:
temp_list = list(df_ov)
ov_sup = suppport_ov[temp_list.index(i_set)]
temp = set()
for indiv_item in i_set:
temp.add(indiv_item)
perm = permutations(temp)
perm_lst = list(perm)
for perm_item_set in perm_lst:
try:
temp_set = []
for dex in range(0, val):
temp_set.append(perm_item_set[dex])
item_set_before = tuple(temp_set)
tp_lst = list(stuff_name_before)
ss = support_arr_before[tp_lst.index(item_set_before)]
sup_ov.append(ov_sup)
sup_sing.append(ss)
perm_item.append(perm_item_set)
except:
# print("itemset below does not exist...")
# print(y)
sup_ov.append(ov_sup)
sup_sing.append(0)
perm_item.append(perm_item_set)
df_main = pd.DataFrame({"association": perm_item, "support_ov": sup_ov, "support_sing": sup_sing})
df_main = df_main.assign(confidence=lambda x: round(((x.support_ov / x.support_sing) * 100), 0))
return df_main
# Finding the max k value in the given set
try:
max(df_supp["k_val"])
except:
print("No max was found...")
# This is where I iteratively call the confidence() function
df_frames = []
try:
if len(df_supp["k_val"]) != 0:
for lp in range(1, max(df_supp["k_val"]) + 1):
# print(lp)
#
df_0 = confidence(lp)
df_0 = df_0[df_0.support_sing != 0]
df_frames.append(df_0)
df_associations = pd.concat(df_frames)
print(df_associations.head())
except:
print("No items or transactions meet the user requirements!")
# Concat the Dataframes
try:
df_associations = pd.concat(df_frames)
print(df_associations)
except:
print("No items or transactions meet the user requirements!")
# Making sure that user parameters are met for confidence
try:
df_associations = df_associations[df_associations['confidence'] >= confidence_percent]
print(df_associations)
except:
print("No items or transactions meet the user requirements!")
# Formatting the Dataframe Final
try:
df_final = df_associations.reset_index().drop(['index', 'support_sing'], axis=1)
df_final.columns = ["Association", "Support", "Confidence"]
except:
print("No items or transactions meet the user requirements!")
# Final Associations
try:
print("Store Name: " + str(ns(int(store_num))))
print("\nFinal Associations that meet the user standards....")
print("Support: " + str(support_percent) + "%" + "\t" + "Confidence: " + str(confidence_percent) + '%')
print(df_final)
except:
print("\nNo Associations were generated based on the parameters set!")
|
917944d62a9978e15b21a2137fbca48cdab3d161 | Lilyfodata/ghio | /python/ex13.py | 792 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding : utf-8 -*-
from sys import argv
script, first, second, third, anthoer = argv
print "The script is called:", script
print "The first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
# -----------------------------------------------------------------------------
# Study Drills
# -----------------------------------------------------------------------------
# valueError: need more than 1 value to unpack
#
from sys import argv
script, first, second = argv
print "你好,我叫:", script
print "你给我的第一个词是:", first
print "还有第二个:", second
print "没玩够?在写一个..."
third = raw_input('> ')
print "可以了,最后一个是:", third
|
67047ed537ffef7b337aff6ab7045e9530d84b66 | thecomputerguy/full-speed-python | /lambdas/pairwithzerosum/PairWithZeroSum.py | 435 | 3.921875 | 4 | def pairWithZeroSum(elements):
for i in range(len(elements)):
for j in range(i+1,len(elements)):
sum_of_two_elements = elements[i] + elements[j]
if sum_of_two_elements == 0:
return True
j = j+1
return False
result = pairWithZeroSum([1,2,5,-5,6,-4,3,-8])
print("Pair exists?")
print(result)
result = pairWithZeroSum([1,2,5,6,8,9])
print("Pair exists?")
print(result) |
3aedc6cbc21851424c8d21e924dc56432486d891 | ajkumark/pyqt | /pyqt.py | 1,984 | 3.546875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
This example shows text which
is entered in a QtGui.QLineEdit
in a QtGui.QLabel widget.
author: Jan Bodnar
website: zetcode.com
last edited: August 2011
"""
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.emailLabel = QtGui.QLabel(self)
self.emailLabel.setText('email')
self.passWordLabel = QtGui.QLabel(self)
self.passWordLabel.setText('Password')
self.emailTextBox = QtGui.QLineEdit(self)
self.passwordTextBox = QtGui.QLineEdit(self)
self.loginBtn = QtGui.QPushButton('Login', self)
self.emailTextBox.move(140, 38)
self.passwordTextBox.move(140, 73)
self.emailLabel.move(60, 40)
self.passWordLabel.move(60, 75)
self.loginBtn.resize(self.loginBtn.sizeHint())
self.loginBtn.move(180, 120)
# qle.textChanged[str].connect(self.onChanged)
# emailTextBox.textEdited[str].connect(self.buttonClicked)
self.loginBtn.clicked.connect(self.buttonClicked)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('QtGui.QLineEdit')
self.show()
# def onChanged(self, text):
# self.lbl.setText(text)
# self.lbl.adjustSize()
def buttonClicked(self,text):
self.hide()
print self.emailTextBox.text()
print self.passwordTextBox.text()
self.ProjectDialog()
# email = text
# password = self.passwordTextBox.text()
# print email
def ProjectDialog(self):
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Choose your project')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main() |
9e1816ed505f61ed13c8893535afacaebf48596a | TayExp/pythonDemo | /05DataStructure/42希尔排序.py | 547 | 3.625 | 4 |
def shell_sort(alist,n):
"""希尔排序"""
# n = len(alist)
gap = n // 2
while gap > 0:
for j in range(gap,n):
# j = gap,gap+1,...n-1
i = j
while i>gap-1:
if alist[i]<alist[i-gap]:
alist[i],alist[i-gap] = alist[i-gap],alist[i]
i -= gap
else:
break
gap = gap // 2
if __name__ == '__main__':
alist=[56,43,23,4,3,2,10,9,8,7,6,5,1,3]
shell_sort(alist,len(alist))
print(alist) |
e058a50346e75cc017180d7205e5d935e1558b2d | katel85/pands-Problem-Sheet | /Week 5 Task/Weekday.py | 654 | 4.46875 | 4 | # Write a program that outputs whether or not today is a weekday
# Author Catherine Leddy
#ref : https://www.w3schools.com/python/python_datetime.asp
# ref : https://www.xspdf.com/resolution/58438157.html
import datetime
day= datetime.datetime.today().weekday()
if day<5 :
print("Yes, unfortunately today is a weekday.")
else:
print("It is the weekend, yay!")
#x=datetime.datetime.now()
#print(x)-this will tell the date but not the day name. Need to change the code
#so that program knows weekdays.The python weekday function of class date returns the day
#of the week as an integer. It starts from 0 for a Monday and ends at 6 for a Sunday
|
8ad6ff1ea21ea75e1eebf6b6c73246993f3b4cbe | DevShasa/code-challenges | /codewars/compare_triplets.py | 1,190 | 4.03125 | 4 | '''
Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.
The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]).
The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2].
If a[i] > b[i], then Alice is awarded 1 point.
If a[i] < b[i], then Bob is awarded 1 point.
If a[i] = b[i], then neither person receives a point.
Comparison points is the total points a person earned.
Given a and b, determine their respective comparison points.
Example
a = [1, 2, 3]
b = [3, 2, 1]
For elements *0*, Bob is awarded a point because a[0] .
For the equal elements a[1] and b[1], no points are earned.
Finally, for elements 2, a[2] > b[2] so Alice receives a point.
'''
def compareTriplets(a, b):
alice = 0
bob = 0
count = 0
for count in range(3):
if a[count] > b[count]:
alice += 1
elif b[count] > a[count]:
bob += 1
else:
continue
|
fcc4f48b33d211b41e4589a40962031f97910af1 | ridhim-art/practice_list2.py | /lambda_expresion_ex.py | 357 | 3.59375 | 4 | cir = lambda r: 2 * r * 3.14
cuboid = lambda l,b,h :l*b*h
print("circumference for radius 10 is",cir(10))
print("circumference for radius 10 is",cir(5))
print("circumference for radius 10 is",cir(6))
print("circumference for radius 10 is",cir(2))
print("circumference for radius 10 is",cuboid(3,4,3))
print("circumference for radius 10 is",cuboid(3,4,5)) |
c490fe9a58221b76284866d04efee81bdde9c74e | krishnanunni-pr/Pyrhon-Django | /Django/Functional programming/Lmabda fuction3.py | 266 | 3.9375 | 4 | # filter function
# print even numbers only
# filter function - filter(function,iterable) **has condition
lst=[1,2,3,4,5,6,7,8,9] #[2,4,6,8]
even=list(filter(lambda num:num%2==0,lst))# even number
odd=list(filter(lambda num:num%2!=0,lst))
print(even)
print(odd)
|
e3234656a5ccfae4d20543573d2b46d1afde1262 | devng/code-puzzles | /src/devng/codejam2018/whole_new_word.py | 1,276 | 4.28125 | 4 | #!/usr/bin/env python3
from itertools import product
def find_word(words, n, l):
words_set = set(words)
chars = []
# put all characters in sets per columns
for i in range(l):
chars.append({w[i] for w in words})
# print(chars)
"""
# generates all word prefixes
prefs = []
for n in range(l):
prefs.append({w[:n+1] for w in words})
print(prefs)
"""
# because Vincetn can provide only up to 2000 words, need to check not more than 2001 words
# to see if we can make a word or not, thus checkking all possibilities is feasible in this case.
# Note: that product() is a python generator so we don't generate all possibilities up front
# but only one at a time on each loop step.
for p in product(*chars):
w = "".join(p)
if w not in words_set:
return w
return "-"
if __name__ == "__main__":
# input() reads a string with a line of input, stripping the ' ' (newline) at the end.
num_cases = int(input())
for i in range(1, num_cases + 1):
n, l = list(map(int, input().split()))
words = []
for _ in range(n):
words.append(input())
result = find_word(words, n, l)
print("Case #{}: {}".format(i, result))
|
883e82b1cc2987d2009380cb3e53175d08b7d6b4 | shafirpl/InterView_Prep | /Basics/Colt_Data_structure/Sorting_Algorithms/Bubble_Sort/Bubble_Sort.py | 1,363 | 4.25 | 4 | def bubble_sort(arr):
length = len(arr)
if(length == 0): return arr
# it goes like this, after first loop, first highest number at the
# end of the loop, and so on, so if we have 5 numbers, after first loop
# 14 will be at the end of the array, afrer 2nd loop second highest number
# 10 will be at the second end of the array and so on, so after fourth loop,
# the fourth highest number will be at the end which means we don't need
# to run another loop, becuase after 4th loop all the 4 highest numbers
# are already sorted, which means the 5th number is sorted. So we need 4 loops,
# or loop from 0 to 3. So it is length - 2, since range exclude the last number
# for example range(5) will give us 0 to 4, we do range(length-1)
# https://www.udemy.com/course/js-algorithms-and-data-structures-masterclass/learn/lecture/11071950#questions
# watch this video for the swap thing
for i in range(length-1):
j = 0
noSwap = True
while (j< length - i):
if(j+1 < length and arr[j+1] <= arr[j]):
arr[j], arr[j+1] = arr[j+1], arr[j]
# temp = arr[j]
# arr[j] = arr[j+1]
# arr[j+1] = temp
noSwap = False
j += 1
if (noSwap): break
return arr
print(bubble_sort([14,5,8,2,10])) |
1fdc22811c1e383c476c7d4a06b1dc9257ab9a4d | csdms/standard_names | /standard_names/tests/test_standardname.py | 3,411 | 3.609375 | 4 | #!/usr/bin/env python
"""Unit tests for standard_names.StandardName"""
import pytest
from standard_names import BadNameError, StandardName
def test_create():
"""Test class creation."""
name = StandardName("air__temperature")
assert name.name == "air__temperature"
def test_bad_name():
"""Try to create an invalid name."""
with pytest.raises(BadNameError):
StandardName("air_temperature")
with pytest.raises(BadNameError):
StandardName("air___temperature")
with pytest.raises(BadNameError):
StandardName("Air__Temperature")
with pytest.raises(BadNameError):
StandardName("_air__temperature")
with pytest.raises(BadNameError):
StandardName("air__temperature_")
with pytest.raises(BadNameError):
StandardName("air__temperature__0")
with pytest.raises(BadNameError):
StandardName("0_air__temperature")
def test_get_object():
"""Retrieve an object from a standard name."""
name = StandardName("air__temperature")
assert name.object == "air"
def test_get_quantity():
"""Retrieve a quantity from a standard name."""
name = StandardName("air__temperature")
assert name.quantity == "temperature"
def test_get_empty_operator():
"""Retrieve an operator from a standard name."""
name = StandardName("air__temperature")
assert name.operators == ()
def test_get_one_operator():
"""Retrieve an operator from a standard name."""
name = StandardName("air__log_of_temperature")
assert name.operators == ("log",)
def test_get_multiple_operators():
"""Retrieve an operator from a standard name."""
name = StandardName("air__mean_of_log_of_temperature")
assert name.operators == ("mean", "log")
def test_compare_names():
"""Compare a names."""
name = StandardName("air__temperature")
assert name == StandardName("air__temperature")
assert name != StandardName("water__temperature")
def test_compare_name_to_str():
"""Compare a name to a string."""
name = StandardName("air__temperature")
assert name == "air__temperature"
assert name != "water__temperature"
assert not (name != "air__temperature")
assert not (name == "water__temperature")
def test_lt_name_to_str():
"""Names are ordered alphabetically."""
air = StandardName("air__temperature")
water = StandardName("water__temperature")
assert air < "water__temperature"
assert air < water
assert not ("water__temperature" < air)
assert not (water < air)
def test_gt_name_to_str():
"""Names are ordered alphabetically."""
air = StandardName("air__temperature")
water = StandardName("water__temperature")
assert not (air > "water__temperature")
assert not (air > water)
assert "water__temperature" > air
assert water > air
def test_hash():
"""Hash based on string."""
a_bunch_of_names = set()
a_bunch_of_names.add(StandardName("air__temperature"))
a_bunch_of_names.add(StandardName("water__temperature"))
assert len(a_bunch_of_names) == 2
a_bunch_of_names.add(StandardName("air__temperature"))
assert len(a_bunch_of_names) == 2
assert "air__temperature" in a_bunch_of_names
assert "water__temperature" in a_bunch_of_names
assert StandardName("air__temperature") in a_bunch_of_names
assert "surface__temperature" not in a_bunch_of_names
|
2615f01b7685be6a526f3d7e08f31f11d65d22d4 | ATinyBanana233/sudokuPY3 | /single_ll.py | 953 | 4.125 | 4 | #define the basic data structure node
class node(object):
def __init__(self, key, value):
self.data=value
self.key=key
self.next=None
#define the linked list structure
class ll(object):
def __init__(self):
self.head=None
def insert(self,key,node_value):
new_node=node(key,node_value)
new_node.next=self.head
self.head=new_node
def delete(self):
current=self.head
self.head=current.next
del current
def reverse(self):
prev=None
current=self.head
while(current is not None):
next=current.next
current.next=prev
prev=current
current=next
self.head=prev
#do not use keyword print
def print_ll(self):
current=self.head
while (current is not None):
print current.data,
current=current.next
def search(self,key):
current=self.head
while(current is not None):
if (key == current.key):
print current.data
return
else:
current = current.next
print "NOT FOUND"
return
|
460af1e6f01a502860246fd9612e5965617e4c2f | souvikb07/DS-Algo-and-CP | /data_structures/arrays/easy_6.py | 620 | 3.625 | 4 | def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
length = len(nums)
if length == 1:
return True
count = 0
for i in range(length - 1):
if i == 0:
if nums[i] > nums[i+1]:
nums[i] = nums[i+1]
count += 1
else:
if nums[i] > nums[i+1]:
if count == 1:
return False
if nums[i-1] > nums[i+1]:
nums[i+1] = nums[i]
else:
nums[i] = nums[i-1]
count += 1
return True |
066b9d1bfba1194200e3a503dd79922c92757301 | Mukul-Singhal/Bibliophile-Companion | /bibliophile/connecti.py | 1,613 | 3.71875 | 4 | import sqlite3
from PIL import ImageGrab
con = sqlite3.connect('example.db')
c = con.cursor()
c.execute(
'''CREATE TABLE IF NOT EXISTS History( timestamp TEXT PRIMARY KEY, TYPE NUMBER NOT NULL ,ID INTEGER NOT NULL)'''
'''CREATE TABLE IF NOT EXISTS Text(id INTEGER PRIMARY KEY AUTOINCREMENT , Text TEXT) '''
'''CREATE TABLE IF NOT EXISTS Photo(id INTEGER PRIMARY KEY AUTOINCREMENT , Photo TEXT , size INTEGER , mode TEXT) ''')
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def insertBLOB(empId):
try:
sqliteConnection = sqlite3.connect('example9.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_insert_blob_query = """ INSERT INTO new_employee
(id, photo) VALUES (?, ?)"""
# Convert data into tuple format
if (image_handler() == None):
raise("ERROR")
data_tuple = (empId, image_handler())
cursor.execute(sqlite_insert_blob_query, data_tuple)
sqliteConnection.commit()
print("Image and file inserted successfully as a BLOB into a table")
cursor.close()
except sqlite3.Error as error:
print("Failed to insert blob data into sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("the sqlite connection is closed")
def image_handler():
return ImageGrab.grabclipboard().tobytes()
|
9d50b98b1fd8afa4006994d51b4b0e7b0ac3b1b1 | mslshao/InterviewStreet | /insertsort.py | 837 | 3.90625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(raw_input())
for i in range(0,T): # Run through # of test cases
iterator = 0
N = int(raw_input())
# Read in N elements per line;... Crap, how to do?!
arr = []
arr = raw_input().split()
for j in range (0,N):
arr[j] = int(arr[j])
for j in range (1,N): # Insertion sort
k = j
#print "%d'th iteration of loop gives us k: " % j, k
while ((k > 0) and (arr[k] < arr[k-1])):
#print "compared: %d < %d" %(arr[k], arr[k-1])
temp = arr[k]
arr[k] = arr[k-1]
arr[k-1] = temp
k = k - 1
#print "Swap made! Iterator increased."
iterator += 1
# print "K: ", k
#print "J: ", j
#print "N: ", N
#print arr
print iterator # Should be T iterators, increment if sort operation performed
|
e1fd25434ed9c8087836a970306a8a7de57f09b9 | WuraolaS/Lesson3_HW | /lesson3.py | 1,635 | 4.5 | 4 | #This is Exercise 3.3.1
#inches->cm
cm = 2.54
def inches_to_cm(inches):
return cm * inches
inc=2
print(inches_to_cm(inc))
#feet to inches
#create a function that turns the an input which will be in feet to inches
#ft = 12in
inch = 12
def ft_to_inches(ft):
return ft * inch
feet = 5
print(f"{feet} feet is equal to {ft_to_inches(feet)} inches")
#yards to feet
#1 yard = 3ft
ft = 3
def yard_to_feet(y):
return y * ft
print(f"{yard_to_feet(5)} feet")
#rod to feet
#1 rod = 5.5 yards
yd = 5.5
def rods_to_yards(rod):
return rod * yd
#furlong to rods
rd = 40
def furlong_to_rods(furlong):
return furlong * rd
print(f"{furlong_to_rods(2)} rods")
#mile to furlong
#1 mile is equal to 8 furlong
fl = 8
def miles_to_furlong(mile):
return mile * fl
print(f"{miles_to_furlong(2)} furlongs")
#feet to centimeters
#test 12 * 2.54 = 30.48
# 2 * 12 * 2.54 = 60.96
def ft_to_centimeter(ft):
feet_converted_inches = ft_to_inches(ft)
return inches_to_cm(feet_converted_inches)
print(ft_to_centimeter(2))
#rods to inches
#test 5.5*3*12 = 198
def rod_to_inches(rods):
#first convert rod to yd and assign it a variable
converted_to_yards = rods_to_yards(rods)
#Then convert yards to feet
converted_to_feet = yard_to_feet(converted_to_yards)
#lastly convert feet to inches
return ft_to_inches(converted_to_feet)
print(rod_to_inches(1))
#def miles_to_feet
#Exercise 3.3.2.
#volume of a cylinder = 3.14r*r*h
pi = 3.14
def volume_cylinder(r,h):
return pi*r*r*h
print(f" the volume of this cylinder is {volume_cylinder(2,2)}")
#this is to see if the a change will happen
|
47ebe7899a3b8f78cffb7cee4c7628b2c1281d5d | liuyi-CSU/learn-python | /xiaosi/day001/test004.py | 408 | 3.734375 | 4 | """
题目描述
写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 )
输入描述:
输入一个十六进制的数值字符串。
输出描述:
输出该数值的十进制字符串。
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
print("请输入一个十六进制的数值字符串:")
inp = input()
print(int(inp, 16))
|
84fb7f63fdcd064e697644b08ffa210453d259e3 | coolsnake/JupyterNotebook | /new_algs/Number+theoretic+algorithms/Karatsuba+algorithm/compute_all_permutations_non_unique_chars.py | 1,475 | 4.125 | 4 | #!/usr/bin/python
# Date: 2018-08-04
#
# Description:
# Write a method to compute all permutations of a string whose characters are
# not necessarily unique. The list of permutations should not have duplicates.
#
# Approach:
# Not much clear, refer 8.6 from CTCI.
#
# Complexity:
# O(n * n!)
import collections
def computePermutationsNonUniqueChars(hashMap, prefix, rem, result):
"""Generates list of all permutations of a given string.
Args:
hashMap: Dictionary having characters as key and there count of occurrences
as value.
prefix: Prefix string used, initially empty.
rem: Length of string remaining.
result: List to store all permutations.
"""
if not rem:
result.append(prefix)
return;
for k in hashMap:
count = hashMap[k]
if count:
hashMap[k] = count - 1
computePermutationsNonUniqueChars(hashMap, prefix + k, rem - 1, result)
hashMap[k] = count
def getHashMap(string):
"""Creates a hash map from string.
Key as character, value as count of occurrences.
"""
m = collections.defaultdict(int)
for k in string:
m[k] += 1
return m
def main():
result = []
string = raw_input("Enter input string (having unique characters): ")
hashMap = getHashMap(string)
computePermutationsNonUniqueChars(hashMap, "", len(string), result)
for idx in range(len(result)):
print ('{idx}: {perm}'.format(idx=idx + 1, perm=result[idx]))
if __name__ == '__main__':
main()
|
2799d173bfc5f9bb8fbc7a5e5edf4d05820c764a | shahud1/thaiwseg | /Backstage/Real_GUI.py | 3,146 | 3.671875 | 4 | from Main import *
from tkinter import *
class Application(Frame):
"""A GUI with app button"""
def __init__(self,master):
""" init the frame"""
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create button,text,and Entry widgets"""
self.instruction = Label(self,text = "Enter the Word")
self.instruction.grid(row= 0 ,column=0,columnspan= 2,sticky=W)
self.word= Entry(self)
self.word.grid(row=1,column=0,sticky=W)
self.submit_button = Button(self,text ="Submit",command=self.output)
self.submit_button.grid(row=1, column =1 )
#Create Textbox1 for Translation output
self.translate = Label(self,text="Translate to English,Chinese")
self.translate.grid(row=2,column=0,sticky =W)
self.text1 = Text(self,width=35,height=5,wrap =WORD)
self.text1.grid(row=3,column=0,columnspan =2 ,sticky=W)
#Create TextBox2 for cutkum output
self.cutkum = Label(self,text="pythaize")
self.cutkum.grid(row=4,column=0,columnspan =2 ,sticky=W)
self.text2 = Text(self,width=35,height=2,wrap =WORD)
self.text2.grid(row=5,column=0,columnspan =2 ,sticky=W)
# Create TextBox3 for DeepCut output
self.deep = Label(self, text="Deepcut")
self.deep.grid(row=6, column=0, columnspan=2, sticky=W)
self.text3 = Text(self, width=35, height=2, wrap=WORD)
self.text3.grid(row=7, column=0, columnspan=2, sticky=W)
# Create TextBox4 for TAS output
self.ats = Label(self, text="Dictionary Method")
self.ats.grid(row=8, column=0, columnspan=2, sticky=W)
self.text4 = Text(self, width=35, height=2, wrap=WORD)
self.text4.grid(row=9, column=0, columnspan=2, sticky=W)
# Create TextBox5 for Comparison output
self.ats = Label(self, text="Comparison all language")
self.ats.grid(row=10, column=0, columnspan=2, sticky=W)
self.text5 = Text(self, width=35, height=5, wrap=WORD)
self.text5.grid(row=11, column=0, columnspan=2, sticky=W)
def output(self):
## Display message base on the pasword typed in
content = self.word.get()
if content:
#return trnaslation
self.text1.delete(0.0, END)
self.text1.insert(0.0,intro.translations(content))
#return pythize
self.text2.delete(0.0,END)
self.text2.insert(0.0,other.pythaize(content))
#return deepcut
self.text3.delete(0.0, END)
self.text3.insert(0.0, other.deepcutize(content))
#return TAS
self.text4.delete(0.0, END)
self.text4.insert(0.0, dictmethod.methodize(content))
# return all
self.text5.delete(0.0, END)
self.text5.insert(0.0, ending.flow(content))
else:
message = "Please insert the word"
self.text.delete(0.0,END)
self.text.insert(0.0,message)
root = Tk()
root.title("Thai Advance segmentator")
app = Application(root)
root.mainloop()
|
4be1ebf388ae123a8b7d4e13908ba954e636e161 | dshuhler/codility_lessons | /codility/4_counting_elements/frog_river_one.py | 1,147 | 3.75 | 4 | import unittest
def solution(X, A):
leaf_coverage = [False] * X
frog_position = -1
# iterate over leaf coverage array
for time, fallen_leaf_position in enumerate(A):
leaf_coverage[fallen_leaf_position - 1] = True
# move our frog across the river as far as we can
# this will never be more than N total spaces, so even though we have
# nested loops, this is still (O)N
for num in range(frog_position, X):
if leaf_coverage[frog_position + 1]:
frog_position += 1
# check if our frog has made it to the other side
if frog_position + 1 == X:
return time
else:
break
return -1
class TestPassingCars(unittest.TestCase):
def test_sample(self):
self.assertEqual(6, solution(5, [1, 3, 2, 4, 3, 3, 5, 2]))
def test_not_able_to_cross(self):
self.assertEqual(-1, solution(5, [1, 3, 2, 4, 3, 3, 4, 2]))
def test_big_river(self):
self.assertEqual(100000, solution(100001, list(range(0, 100001))))
if __name__ == '__main__':
unittest.main()
|
fdc6af7d4537a23993174875c0c98b2346325ce3 | rakshaharish/Basic-ML-Algorithms | /Find-S algorithm.py | 945 | 3.625 | 4 | import csv
with open('lab1.csv','r') as f:
read=csv.reader(f)
data=[]
print("given training example:")
for row in read:
print(row)
if(row[-1]=="yes" or row[-1]=="Yes" or row[-1]=="YES"):
data.append(row)
print('---------------------------------')
print("positive training example:")
for dat in data:
print(dat)
length=len(data[0])-1
h=['$']*(length)
print('---------------------------------')
val=1
for x in data:
print('instance',val,"is",h)
for i in range(0,len(x)-1):
if(h[i]=='?'):
continue
elif(h[i]=='$'):
h[i]=x[i]
elif(h[i]!=x[i]):
h[i]='?'
print('hypothesis',val,"is",h)
print('---------------------------------')
val=val+1
print('most specific hypothesis',h)
|
c9111ad908b4f0601b1233d9d53e61df9fc3305f | Lkik/test1 | /test.py | 152 | 3.6875 | 4 | a = input()
e = len(a)
for i in range(e//2):
if a[i] != a[-1-i]:
print("не полиндром")
quit()
print("полиндром") |
f83444e3f39b2047af2febdc31928c407c631ca0 | H4rsh4/Edureka_Python-Course | /Day 2/Case Study 1/q2.py | 478 | 4 | 4 | '''
Obj:
Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically.
Assuming the input is structured as : "A C B F"
'''
query = str(input('>'))
#->The following statement SPLITs the given string with the given seperator(' ') and returns a list of spliced blocks
#-> and then SORTs alphabetically -> Then the elements of the list are printed with space seperation
print(' '.join(sorted(query.split(' '))))
|
3bc341bf8ae8663c25a3fc39823532fcd4e29d33 | gsakkas/seq2parse | /src/tests/parsing_test_24.py | 332 | 3.5 | 4 | def friendsOfFriends(d):
for key1 in d:
for key2 in d:
if key1 == key2:
continue
else:
d[key1].update(d[key1]- d[key2])
return d
print(friendsOfFriends({"fred":
set(["wilma", "betty", "barney", "bam-bam"]),
"wilma": set(["fred", "betty", "dino"])}))
|
c07df7ad59b9583ddb2d7280fe575fe6f9abf50b | SehwanJeon2/ssafy1219 | /dict.py | 4,565 | 3.765625 | 4 | """
파이썬 dictionary 활용 기초!
"""
# 1. 평균을 구하세요.
iu_score = {
"수학": 80,
"국어": 90,
"음악": 100
}
# 답변 코드는 아래에 작성해주세요.
print("=====Q1=====")
score = 0
count = 0
for i in iu_score:
score = score + iu_score[i]
count = count+1
score=score/count
print(score)
#Teacher Answer
#iu_score라고 하는 dic 변수에서 value 값만 뽑아내보자.
total_score=0
count=0
#뽑아낸 값들의 총 합을 구한다
for score in iu_score:
print(iu_score[score])
total_score = total_score + iu_score[score]
count=count+1
print(total_score/count)
#scores = list(iu_score.values())
#print(sum(scores)/len(scores)) 이용하는 방법도 있다.
#------------------------------------------------------------------------------
# 2. 반 평균을 구하세요.
score = {
"iu": {
"수학": 80,
"국어": 90,
"음악": 100
},
"ui": {
"수학": 80,
"국어": 90,
"음악": 100
}
}
# 답변 코드는 아래에 작성해주세요.
print("=====Q2=====")
val=0
count=0
for key in score:
print(key)
for sub in score[key]:
print(sub)
val=val+score[key][sub]
count=count+1
val=val/count
print(val)
#Teacher Answer
# 각 반을 순회하는 반복문을 작성한다
for cl in score:
print(score[cl])
# 한 번 순회를 할 때 1번에서 작성한 코드를 활용한다.
tmp = list(score[cl].values)
# 출력한다.
print("{}: {}".format(cl, sum(tmp)/len(tmp)))
#------------------------------------------------------------------------------
# 3. 도시별 최근 3일의 온도 평균은?
"""
출력 예시)
서울 : 값
대전 : 값
광주 : 값
부산 : 값
"""
# 3-1. 도시 중에 최근 3일 중에 가장 추웠던 곳, 가장 더웠던 곳은?
city = {
"서울": [-6, -10, 5],
"대전": [-3, -5, 2],
"광주": [0, -2, 10],
"부산": [2, -2, 9],
}
# 답변 코드는 아래에 작성해주세요.
print("=====Q3=====")
totaltemp=0
count=0
for name in city:
for tem in city[name]:
totaltemp=totaltemp+tem
count=count+1
print(name,":", totaltemp/count)
totaltemp=0
count=0
#Teacher Answer
# 각 도시를 순회하는 반복문을 작성한다.
for ci in city:
print(city[ci])
temp = city[ci]
# 순회할 때마다 평균 값을 출력한다.
print("{}의 평균기온: {}".format(city, round(sum(temp)/len(temp), 1)))
print("{}의 평균기온: {:.1}".format(city, sum(temp)/len(temp)))
# python get round value (소수가 너무 길어서 반올림 찾아보자)
# 일단 2가지 찾았다.
#------------------------------------------------------------------------------
# 답변 코드는 아래에 작성해주세요.
print("=====Q3-1=====")
for name in city:
city[name].sort()
print(city)
coldcity=""
mintemp=300
for name in city:
if(mintemp>city[name][0]):
mintemp=city[name][0]
coldcity=name
print("coldest city: ",coldcity)
for name in city:
city[name].reverse()
print(city)
hotcity=""
maxtemp=-255
for name in city:
if(maxtemp<city[name][0]):
maxtemp=city[name][0]
hotcity=name
print("hottest city: ",hotcity)
#Teacher Answer
# 최저기온, 최고기온을 저장할 수 있는 변수를 선언한다. (반복문 밖에서 선언한다)
minimum = ["도시명", 1000]
maximum = ["도시명", -1000]
#
# 각 도시를 순회하는 반복문을 만든다.
for ci in city:
# 각 도시의 기온 정보를 순회하는 반보문을 만든다.
for temp in city[ci]:
# 순회하다가 최저기온의 경우에는 현재 저장된 값보다 작은값이,
# 최고 기온의 경우에는 현재 저장된 값보다 큰 값이 있는 경우
# 현재 저장되어 있는 값을 바꾼다.
#최저기온에 해당하는 조건문
if(maximum[1] < temp):
maximum[0] = city
maximum[1] = temp
#최고기온에 해당하는 조건문
if(minimum[1] > temp):
minimum[0] = city
minimum[1] = temp
print("최고 기온은 {}의 {}도이며, 최저 기온은 {}의 {}도 입니다.".format(maximum[0], maximum[1], minimum[0], minimum[1]))
#------------------------------------------------------------------------------
# 4. 위에서 서울은 영상 2도였던 적이 있나요?
# 답변 코드는 아래에 작성해주세요.
print("=====Q4=====")
seoultemp = False
for tem in city['서울']:
if(city['서울']==2):
seoultemp = True
if(seoultemp):
print("Yes Seoul had 2'C")
else:
print("No Seould hadn't 2'C")
#Finish |
00d738445a95413d6429f074aa207264d862439b | robbiemccorkell/martianrobots | /position.py | 1,062 | 3.578125 | 4 | class Position:
compass = ['N', 'E', 'S', 'W']
def __init__(self, xPos, yPos, bearing):
self.xPos = int(xPos)
self.yPos = int(yPos)
self.bearingIndex = self.compass.index(bearing)
def moveForward(self):
if self.compass[self.bearingIndex] == 'N':
self.translate([0,1])
elif self.compass[self.bearingIndex] == 'E':
self.translate([1,0])
elif self.compass[self.bearingIndex] == 'S':
self.translate([0,-1])
elif self.compass[self.bearingIndex] == 'W':
self.translate([-1,0])
def translate(self, vector):
self.xPos += vector[0]
self.yPos += vector[1]
def rotateClockwise(self):
self.bearingIndex += 1
self.bearingIndex = self.bearingIndex % len(self.compass)
def rotateAnticlockwise(self):
self.bearingIndex -= 1
self.bearingIndex = self.bearingIndex % len(self.compass)
def __str__(self):
return '{0} {1} {2}'.format(self.xPos, self.yPos, self.compass[self.bearingIndex])
def __eq__(self, other):
return self.xPos == other.xPos \
and self.yPos == other.yPos \
and self.bearingIndex == other.bearingIndex |
07b22e3bd73ea659f07799c051faf0b03a7f5b0f | murali-kotakonda/PythonProgs | /PythonBasics1/basics/functions/Ex19.py | 203 | 3.671875 | 4 | """
How to access global variables inside the function
"""
city = "Hyd"
def change():
global city # functn can acces global bvariable city
city ="bangaore"
print(city)
change()
print(city)
|
cd5078ba0097500c92c3dbf43c1a520774297e1e | rednikon/Python | /Raspberry-Pi/Blinking-LED/GPIO.py | 303 | 3.578125 | 4 | import RPi.GPIO as GPIO
import time
# Write a Raspberry Pi program that makes an LED on your breadboard blink on and off.
while True:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
GPIO.output(11,True)
time.sleep(2)
GPIO.output(11,False)
time.sleep(2)
GPIO.cleanup()
|
649c2ba963372ab2810d8d9aed099abbf9c9ac45 | pdubslax/hackerRankSolutions | /CTCI/ctci-bubble-sort.py | 590 | 4.03125 | 4 | def bubbleSort(numbers, values):
totalSwaps = 0
for i in range(numbers):
newSwaps = 0
for j in range(numbers-1):
if values[j] > values[j+1]:
values[j],values[j+1] = values[j+1],values[j]
totalSwaps += 1
newSwaps += 1
if newSwaps == 0:
break
print "Array is sorted in " + str(totalSwaps) + " swaps."
print "First Element: " + str(values[0])
print "Last Element: " + str(values[-1])
n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
bubbleSort(n,a)
|
89be93b937a6caa806f287c9c505e2ae26b4a50a | juanjoneri/Bazaar | /Interview/Quora/forming-teams-2.py | 2,624 | 3.59375 | 4 | # Find how many ways to arrange the students into teams, so that each team's skills summ up to a target value k
from sys import stdin
from collections import Counter
from math import factorial
def nck(n, k):
# n choose k: arangements of k elements from a set of n
return factorial(n) // (factorial(k) * factorial(n-k))
if __name__ == '__main__':
n = int(stdin.readline()) # numbr of students
skills = list(map(int, stdin.readline().split())) # skill of each student
skills_counts = Counter(skills) # how many students have a certain skill
k = int(stdin.readline()) # target skill of each team
possible_skills = list(filter(lambda x: 0 <= x <= k, skills))
possible_n = len(possible_skills)
unique_skills = list(set(possible_skills))
unique_n = len(unique_skills)
repeated_skills = list(filter(lambda x: skills_counts[x] >= 2, possible_skills))
# find all unique pairs of sutudents'skills
skills_pairs = dict() # n^2
for i in range(unique_n):
for j in range(i+1, unique_n):
pair = tuple(sorted((unique_skills[i], unique_skills[j])))
skill = sum(pair)
if skill not in skills_pairs:
skills_pairs[skill] = [pair]
elif pair not in skills_pairs[skill]:
skills_pairs[skill].append(pair)
for skill in repeated_skills:
pair = (skill, skill)
skill = 2*skill
if skill not in skills_pairs:
skills_pairs[skill] = [pair]
elif pair not in skills_pairs[skill]:
skills_pairs[skill].append(pair)
# find all unique trios of students's skills that add up to k
skills_trios = set()
for skill in unique_skills:
target_skill = k - skill
if target_skill in skills_pairs:
for pair in skills_pairs[target_skill]:
# check if we will not repeat a student in this trio
if skills_counts[skill] > pair.count(skill):
trio = tuple(sorted((skill, *pair)))
skills_trios.add(trio)
count = 0
for x, y, z in skills_trios:
# find how many ways this trio could have been formed
if x == y == z:
count += nck(skills_counts[x], 3)
elif x == y:
count += (nck(skills_counts[x], 2) * skills_counts[z])
elif y == z:
count += (skills_counts[x] * nck(skills_counts[y], 2))
elif x == z:
count += (nck(skills_counts[x], 2) * skills_counts[y])
else:
count += (skills_counts[x] * skills_counts[y] * skills_counts[z])
print(count)
|
997207fc08bbb3ab4c01550657111d4edf549c52 | rahulkuriyedath/Sudoku | /sudoku_test.py | 1,192 | 3.5625 | 4 | import numpy as np
grid = [[6,0,0,0,0,0,0,0,0],
[0,0,1,0,0,0,4,6,0],
[5,0,0,0,0,3,2,0,0],
[0,0,0,0,8,0,0,0,0],
[0,9,6,4,0,0,0,0,0],
[2,0,4,0,1,0,5,0,3],
[0,0,8,0,0,0,0,3,0],
[0,0,3,2,4,0,0,1,0],
[0,0,0,0,0,8,6,0,2]]
def possible(x, y, n):
for i in range(0, 9):
if grid[i][x] == n and i != y: # Checks for number (n) in X columns
return False
for i in range(0, 9):
if grid[y][i] == n and i != x: # Checks for number (n) in X columns
return False
x0 = (x // 3) * 3
y0 = (y // 3) * 3
for X in range(x0, x0 + 3):
for Y in range(y0, y0 + 3): # Checks for numbers in box(no matter the position, it finds the corner)
if grid[Y][X] == n:
return False
return True
def solve():
global grid
for y in range(9):
for x in range(9):
if grid[y][x] == 0:
for n in range(1, 10):
if possible(x, y, n):
grid[y][x] = n
solve()
grid[y][x] = 0
return
print(np.matrix(grid))
solve()
|
ec4cb58bc367bbbe6634dc7fdecf0d08c4061ca4 | Courage-GL/FileCode | /Python/month02/day03/exercise_2.py | 683 | 4 | 4 | """
练习1: 基于单词本完成
编写一个函数,传入一个单词,返回单词对应的解释
提示: 每行一个单词
单词与解释之前有空格
单词按顺序排列
split()
"""
def find_word(word):
file = open("dict.txt") # 读打开
# 查找单词
for line in file:
# 提取单词和解释
tmp = line.split(' ',1)
# 如果遍历到的单词已经比目标单词大,则结束查找
if tmp[0] > word:
file.close()
break
# 找到单词
if word == tmp[0]:
file.close()
return tmp[1].strip()
print(find_word("marry"))
|
b6b48fe8680039b442ede1abc86b24dab47300a5 | DominicSchiller/osmi-module-datascience | /assessment_03/cards/Shuffle.py | 1,308 | 3.671875 | 4 | import random
from .Card import Card
from .CardColor import CardColor
from .CardValue import CardValue
__author__ = 'Dominic Schiller'
__email__ = 'dominic.schiller@th-brandenburg.de'
__version__ = '1.0'
__license__ = 'MIT'
class Shuffle:
"""
Shuffle machine dedicated to generate and shuffle full card decks.
"""
_CARD_DECK_MULTIPLIER = 4
@staticmethod
def generate_card_deck() -> [Card]:
"""
Generate a complete and shuffled card deck.
:return: The generated card deck
"""
card_deck = []
for card_color in CardColor:
for card_value in CardValue:
card_deck.append(Card(card_color, card_value))
return Shuffle.__shuffle_card_deck(card_deck * Shuffle._CARD_DECK_MULTIPLIER)
@staticmethod
def __shuffle_card_deck(card_deck: [Card]) -> [Card]:
"""
Shuffle a given card deck.
:param card_deck: The card deck to shuffle
:return: The shuffled card deck.
"""
shuffled_card_deck = []
length = len(card_deck)
while len(shuffled_card_deck) != length:
r = random.SystemRandom()
random_card = r.choice(card_deck)
shuffled_card_deck.append(random_card)
card_deck.remove(random_card)
return shuffled_card_deck
|
0642ec788c8725f2fcded420ebae54204b8c65c3 | thiagofb84jp/python-exercises | /pythonBook/generalExercises/math/exercise10.py | 600 | 4.09375 | 4 | """
10. Write a Python program to calculate the discriminant value.
"""
def discriminant():
xValue = float(input("The 'x' value: "))
yValue = float(input("The 'y' value: "))
zValue = float(input("The 'z' value: "))
discriminant = (yValue ** 2) - (4 * xValue * zValue)
if discriminant > 0:
print("Two soluctions. Discriminant value is: ", discriminant)
elif discriminant == 0:
print("One soluction. Discriminant value is: ", discriminant)
elif discriminant < 0:
print("No Real soluction. Discriminant value is: ", discriminant)
discriminant()
|
cb1984660be3e0c5b995706900f805cca4a7f306 | bmoretz/Daily-Coding-Problem | /py/dcp/problems/stack_queue/n_stack.py | 3,677 | 4.21875 | 4 | """
Three in one.
Use a single array to implement three stacks.
"""
'''Approach #1.
This approach uses a single array with empty elements
to offset each individual stacks elements inside the single
backing array.
pros: simple, easily extendable relatively efficient.
cons: potentially lots of empty space unused.
'''
class nstack1():
def __init__(self, n = 3):
self.n_stacks = n
self.data = []
self.lengths = [0] * self.n_stacks
def pop(self, index):
self.__check_index_range(index)
if self.is_empty(index): return None
value = self.__top()[index]
self.data[index] = None
self.lengths[index] -= 1
if all(v is None for v in self.__top()):
self.data = self.data[self.n_stacks:]
return value
def push(self, index, item):
self.__check_index_range(index)
capacity = len(self.data) / self.n_stacks
if self.lengths[index] >= capacity:
values = [None] * self.n_stacks
values[index] = item
self.data = values + self.data
self.lengths[index] += 1
else:
offset = self.lengths[index] + index
self.data[offset] = item
self.lengths[index] += 1
def peek(self, index):
self.__check_index_range(index)
if self.lengths[index] <= 0:
return None
return self.__top()[index]
def is_empty(self, index):
self.__check_index_range(index)
return self.lengths[index] == 0
def __check_index_range(self, index):
if index < 0 or index > self.n_stacks:
raise IndexError(f'{index} is not a valid index.')
def __top(self):
return self.data[:self.n_stacks]
'''Approach #2.
This approach uses a single array to hold all the
elements of the substacks and lengths of each
individual substack to rotate the array for push and pop
operations, such that the currently modified substack
is always at the tail of the array.
pros: space efficient,
cons: rotate is
'''
class nstack2():
def __init__(self, n = 3):
self.n_stacks = n
self.data = []
self.lengths = [0] * self.n_stacks
self.current = 0
def pop(self, index):
self.__check_index_range(index)
if self.is_empty(index): return None
if index != self.current:
self.__rotate(index)
value = self.data[0]
self.data = self.data[1:]
self.lengths[index] -= 1
return value
def push(self, index, item):
self.__check_index_range(index)
if self.current != index and self.lengths[index] != 0:
self.__rotate(index)
self.current = index
self.data = [item] + self.data
self.lengths[index] += 1
def peek(self, index):
self.__check_index_range(index)
if self.lengths[index] == 0: return None
if self.current != index:
rotations = self.__get_rotations(index)
return self.data[rotations:][0]
else:
return self.data[0]
def is_empty(self, index):
self.__check_index_range(index)
return self.lengths[index] <= 0
def __check_index_range(self, index):
if index < 0 or index > self.n_stacks:
raise IndexError(f'{index} is not a valid index.')
def __get_rotations(self, index):
return sum([element for i, element in enumerate(self.lengths) if i != index])
def __rotate(self, index):
places = self.__get_rotations(index)
self.data = self.data[places:] + self.data[:places] |
a35f3dee7a67f05055fe3b10a8dcebff79da83dc | timpark0807/self-taught-swe | /Algorithms/Leetcode/261 - Valid Graph Tree.py | 1,513 | 3.6875 | 4 | import unittest
import collections
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
adj_list = self.get_adj_list(edges)
queue = [0]
seen = set([0])
while queue:
current = queue.pop(0)
for neighbor in adj_list[current]:
if neighbor not in seen:
queue.append(neighbor)
seen.add(neighbor)
elif neighbor in seen:
return False
return True
def get_adj_list(self, edges):
adj_list = collections.defaultdict(list)
for x, y in edges:
adj_list[x].append(y)
return adj_list
class TestSolution(unittest.TestCase):
def test_valid_tree(self):
n = 5
valid_edges = [[0,1],
[0,2],
[0,3],
[1,4]]
s = Solution()
valid_answer = s.validTree(n, valid_edges)
self.assertTrue(valid_answer)
def test_invalid_tree(self):
n = 5
invalid_edges = [
[0,1],
[1,2],
[2,3],
[1,3],
[1,4]]
s = Solution()
invalid_answer = s.validTree(n, invalid_edges)
self.assertFalse(invalid_answer)
if __name__ == '__main__':
unittest.main()
|
593fd71af2c42f19d502ea8c54525aacb4fea966 | mattlevan/Search_Control_Algorithms | /BreadthFirst.py | 5,081 | 3.921875 | 4 | '''
BreadthFirst search is a program that finds optimal solutions to games
(using the Game class) by iterating through all possible moves and
comparing to both the game goal state and all previous states visited.
'''
from EightPuzzle import EightPuzzle
from MissionaryCannibal import MissionaryCannibal
from SlidingTiles import SlidingTiles
class BreadthFirst:
def __init__(self, game):
self.game = game
self.goals = set()
print('bfs created')
'''
buildGraph generates states and stores them in the graph{}
dictionary until either the goal is reached, or a set number
of moves are performed.
'''
def buildGraph(self):
MAX_MOVES = 10 # The max number of iterations before restarting.
goalFound = False
while not goalFound: # Generate nodes until goal is reached.
start = self.game.gen_start()
for gameGoal in self.game.goals:
self.goals.add(tuple(gameGoal))
graph = {} # Stores visited states as (Parent, kids) pairs.
# Get the initial move information for dictionary.
parent, children = self.game.gen_moves(start)
print('Parent: ', parent, ' Child: ',children)
graph.update({parent: set(children)})
print(graph)
# For each key in the graph, add children to the dictionary
# and check if a goal state is reached
maxMoveCounter = 0
# The game restarts if no goal is found in MAX_MOVES
while maxMoveCounter < MAX_MOVES:
# Iterate through all keys and generate a dictionary
# of new move states.
tempGraph, goalFound = self.searchKeys(graph)
# Update graph with the new moves stored in tempGraph.
graph.update(tempGraph)
maxMoveCounter += 1
return self.game, graph
'''
searchKeys searches through all child states for each parent
key. Child states not present as keys in the dictionary are
added as new keys. If a goal state has not yet been reached,
child states are generated for the new keys. Otherwise they
are capped as and empty set().
'''
def searchKeys(self, searchGraph):
goalFound = False
graphKeys = searchGraph.keys()
tempDict = {}
# Iterate through every key in the graph.
for key in graphKeys:
# Check that each path is present as a graph key.
for vertex in searchGraph[key]:
# If child state is not in graph, add it.
if vertex not in searchGraph:
# If the goal isn't reached, add new states.
if not goalFound:
# Generate child states and add to the graph.
movestart, newstates = self.game.gen_moves(vertex)
tempDict.update({movestart: set(newstates)})
# If the goal was reached previously.
else:
# Set all child states as an empty set
tempDict.update({vertex: set()})
# Compare the present vertex to the goal state.
elif vertex in self.goals:
goalFound = True
return tempDict, goalFound
'''
bfs first calls buildGraph to generate a dictionary that
has reached the goal state. The method then searches each state
in the graph to find the shortest path to the goal.
'''
def bfs(self):
# Generate a game and graph containing the goal state.
legalGame, legalGraph = self.buildGraph()
goalState = tuple(legalGame.goals)
startState = legalGame.start
# Store the states not yet visited in queue.
queue = [(tuple(startState), [tuple(startState)])]
# While the queue is not empty, perform the search.
qcnt = 0
while queue:
qcnt += 1
(vertex, path) = queue.pop(0) # Pop the current graph key.
# For each child of a vertex/key compare to the states seen.
# The subtraction leaves only unvisited paths in each key.
cnt = 0
for next in legalGraph[vertex] - set(path):
cnt += 1
# If already visited state, skip to next child state.
if next in goalState:
yield path + [next]
else:
queue.append((next, path + [next]))
'''
shortestPath calls bfs (AKA the breadth first search function)
and is meant to return all successful paths.
'''
def shortestPath(self):
try:
return next(self.bfs())
except StopIteration:
return None
'''
All games and output format are run below.
'''
f = open("SearchResults.txt", 'w')
# Run the Eightpuzzle
eightGame = EightPuzzle()
bfsearch = BreadthFirst(eightGame)
eightSolutions = (bfsearch.shortestPath())
strSolutions = str(eightSolutions)
f.write(('EightPuzzle path to success \nStart:'))
moveCount = 0
for state in eightSolutions:
f.write(('\nMove '+str(moveCount)+'\n'+str(state[0:3])+'\n' + str(state[3:6])+'\n'+str(state[6:9])))
moveCount += 1
missionGame = MissionaryCannibal()
bfSearchMission = BreadthFirst(missionGame)
missionSolutions = (bfSearchMission.shortestPath())
f.write(('\n\nMissionary Path to success \nStart:'))
moveCount = 0
for state in missionSolutions:
f.write(('\nMove '+str(moveCount)+str(state)))
moveCount += 1
tileGame = SlidingTiles()
bfSearchTiles = BreadthFirst(tileGame)
tileSolutions = (bfSearchTiles.shortestPath())
f.write(('\n\nSliding Tiles Path to success \nStart:'))
moveCount = 0
for state in tileSolutions:
f.write(('\nMove '+str(moveCount)+str(state)))
moveCount += 1
# Close output file
f.close()
|
fec5f806a424dbb269144164cd465679d7279466 | AnujRuhela7/Python-Tutorial | /Q4.py | 418 | 3.984375 | 4 | a = int(input(" Enter 1st Value (a) = "))
b = int(input(" Enter 2nd Value (b) = "))
Sum = a + b
Difference = a - b
Product = a * b
Division = a / b
F_Division = a//b
Exponent = a ** b
Remainder = a % b
print("Sum = ",Sum)
print("Diiference = ",Difference)
print("Exponent = ",Exponent)
print("Remainder = ",Remainder)
print("Product = ",Product)
print("Division = ",Division)
print("Floor Division = ",F_Division) |
667dc7ef2332360fefe9f216c5900fa32a54d018 | zyyxydwl/Python-Learning | /file/nineth.py | 330 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#@Time :2017/10/25 22:49
#@Author :zhouyuyao
#@File :nineth.py
for i in range(10):
if i>3:
break
print('a=' +str(i))
print('#' *20)
i=0
for i in range(1,5):
print(i)
if i==3:
print('hello world')
continue
print('i = %d' %i)
|
564cae1515988951178d637a65ff6ef105801e0d | yehongyu/acode | /2019/binary_tree/binary_tree_preorder_traveersal_66.py | 1,572 | 3.9375 | 4 | #coding=utf-8
"""
Definition of TreeNode:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: A Tree
@return: Preorder in ArrayList which contains node values.
"""
def helper(self, root, res):
if root == None:
return
res.append(root.val)
self.helper(root.left, res)
self.helper(root.right, res)
## recursion
def preorderTraversal_with_recursion(self, root):
# write your code here
res = []
self.helper(root, res)
return res
## divide and conquer
def preorderTraversal_DC(self, root):
res = []
if root == None:
return res
left_res = self.preorderTraversal_DC(root.left)
right_res = self.preorderTraversal_DC(root.right)
res.append(root.val)
res.extend(left_res)
res.extend(right_res)
return res
## iteration
def preorderTraversal(self, root):
res = []
if root == None:
return res
stack = []
stack.append(root)
while len(stack) > 0:
node = stack[-1]
stack.pop(len(stack)-1)
res.append(node.val)
if node.right != None:
stack.append(node.right)
if node.left != None:
stack.append(node.left)
return res
root = TreeNode(1)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
s = Solution()
print(s.preorderTraversal(root))
|
5ff84fc111adb506f3aa0dda6d5e368580031a4b | ldpeng/study-code | /Python/lambda.py | 331 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。
# 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
|
8595a02904cd0e3b6fa685ea239a6830ae0769ce | Raipagnin/Python.exercises | /ex05.py | 404 | 4 | 4 | # ex 5 - faca um programa que leia um numero inteiro, e mostre na tela o numero, o antecessor e o sucessor
x = int(input('Digite um valor:'))
a = x - 1
s = x + 1
print('Baseado no valor {}, seu antecessor eh {} e seu sucessor eh {}'.format(x, a, s))
# vc tb pode fazer tudo com apenas uma variavel e dentro do .format colocar a equacao, porem se colocam variaveis a mais, caso use depois em outras linhas |
be9cbef15cfeadac528d84cd07b8e4d7a8ed0fa5 | nipuntalukdar/NipunTalukdarExamples | /python/misc/print_permute_recurse.py | 551 | 3.625 | 4 | from copy import copy
def print_permute(input, lst, printed):
if len(input) == 1:
lst.append(input[0])
word = ''.join(lst)
if word not in printed:
printed.add(word)
print(word)
lst.pop()
else:
i = 0
while i < len(input):
newinput = copy(input)
x = newinput.pop(i)
lst.append(x)
print_permute(newinput, lst, printed)
lst.pop()
i += 1
string = 'abcda'
print_permute(list(string), [], set())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.