blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
baefa5eaf3afaae33952a1ebc4c53fd3c1882086 | Sauvikk/practice_questions | /Level7/Dynamic Programming/Word Break.py | 1,056 | 3.953125 | 4 | # Given a string s and a dictionary of words dict, determine if s can be segmented into a
# space-separated sequence of one or more dictionary words.
#
# For example, given
#
# s = "myinterviewtrainer",
# dict = ["trainer", "my", "interview"].
# Return 1 ( corresponding to true ) because "myinterviewtrainer" can be segmented as "my interview trainer".
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
# http://www.programcreek.com/2012/12/leetcode-solution-word-break/
class Solution:
def sol(self, s, dic):
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(len(s)):
if not dp[i]:
continue
for string in dic:
end = i + len(string)
if end > len(s):
continue
if dp[end]:
continue
if s[i: end] == string:
dp[end] = True
return dp[len(s)]
s1 = "myinterviewtrainer"
dict1 = ["trainer", "my", "interview"]
print(Solution().sol(s1, dict1))
|
93a48eba826b20afb8ceae2cab4be4c249b68c3a | Sauvikk/practice_questions | /Level6/Trees/Construct Binary Tree From Inorder And Preorder.py | 1,374 | 3.96875 | 4 | # Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note: You may assume that duplicates do not exist in the tree.
# Example :
#
# Input :
# Preorder : [1, 2, 3]
# Inorder : [2, 1, 3]
#
# Return :
# 1
# / \
# 2 3
from Level6.Trees.BinaryTree import BinaryTree, Node
class Solution:
def __init__(self):
self.pre_index = 0
def search(self, arr, start, end, value):
for i in range(start, end + 1):
if arr[i] == value:
return i
def generate_tree(self, pre_order, in_order, start, end):
if start > end:
return None
node = Node(pre_order[self.pre_index])
self.pre_index += 1
if start == end:
return node
index = self.search(in_order, start, end, node.val)
node.left = self.generate_tree(pre_order, in_order, start, index - 1)
node.right = self.generate_tree(pre_order, in_order, index + 1, end)
return node
def solution(self, pre_order, in_order):
if pre_order is None or in_order is None:
return None
return self.generate_tree(pre_order, in_order, 0, len(in_order) - 1)
Solution.pre_index = 0
res = Solution().solution(['A', 'B', 'D', 'E', 'C', 'F'], ['D', 'B', 'E', 'A', 'F', 'C'])
BinaryTree().in_order(res)
|
7708927408c989e6d7d6a297eb62d27ca489ee49 | Sauvikk/practice_questions | /Level6/Trees/BinaryTree.py | 2,379 | 4.15625 | 4 |
# Implementation of BST
class Node:
def __init__(self, val): # constructor of class
self.val = val # information for node
self.left = None # left leef
self.right = None # right leef
self.level = None # level none defined
self.next = None
# def __str__(self):
# return str(self.val) # return as string
class BinaryTree:
def __init__(self): # constructor of class
self.root = None
def insert(self, val): # create binary search tree nodes
if self.root is None:
self.root = Node(val)
else:
current = self.root
while 1:
if val < current.val:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.val:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
def bft(self): # Breadth-First Traversal
self.root.level = 0
queue = [self.root]
out = []
current_level = self.root.level
while len(queue) > 0:
current_node = queue.pop(0)
if current_node.level > current_level:
current_level += 1
out.append("\n")
out.append(str(current_node.val) + " ")
if current_node.left:
current_node.left.level = current_level + 1
queue.append(current_node.left)
if current_node.right:
current_node.right.level = current_level + 1
queue.append(current_node.right)
print(''.join(out))
def in_order(self, node):
if node is not None:
self.in_order(node.left)
print(node.val)
self.in_order(node.right)
def pre_order(self, node):
if node is not None:
print(node.val)
self.pre_order(node.left)
self.pre_order(node.right)
def post_order(self, node):
if node is not None:
self.post_order(node.left)
self.post_order(node.right)
print(node.val)
|
3aa92d66e2535e8f29c538ea4d62a928dcac1c6d | Sauvikk/practice_questions | /Level7/Dynamic Programming/Max Product Subarray.py | 990 | 3.6875 | 4 | # Find the contiguous subarray within an array (containing at least one number) which has the largest product.
# Return an integer corresponding to the maximum product possible.
#
# Example :
#
# Input : [2, 3, -2, 4]
# Return : 6
#
# Possible with [2, 3]
# http://yucoding.blogspot.in/2014/10/leetcode-quesion-maximum-product.html
class Solution:
# @param n, an integer
# @return an integer
def sol(self, num):
maximum = [None] * len(num)
minimum = [None] * len(num)
maximum[0] = minimum[0] = result = num[0]
for i in range(1, len(num)):
if num[i] > 0:
maximum[i] = max(num[i], maximum[i-1]*num[i])
minimum[i] = min(num[i], minimum[i-1]*num[i])
else:
maximum[i] = max(num[i], minimum[i-1]*num[i])
minimum[i] = min(num[i], maximum[i-1]*num[i])
result = max(result, maximum[i])
return result
c = [2, 3, -2, 4]
print(Solution().sol(c))
|
a863a7a5670ee737a2bfadcea0bdfe193aefabb0 | Sauvikk/practice_questions | /Level3/Strings/Roman To Integer.py | 1,303 | 3.546875 | 4 | # Given a roman numeral, convert it to an integer.
#
# Input is guaranteed to be within the range from 1 to 3999.
#
# Read more details about roman numerals at Roman Numeric System
#
# Example :
#
# Input : "XIV"
# Return : 14
# Input : "XX"
# Output : 20
class Solution:
@staticmethod
def solution(string):
res = 0
pre = ' '
for i in range(len(string)):
if string[i] == 'M' and pre != 'C': res += 1000
if string[i] == 'C' and pre != 'X': res += 100
if string[i] == 'X' and pre != 'I': res += 10
if string[i] == 'M' and pre == 'C': res += 800
if string[i] == 'C' and pre == 'X': res += 80
if string[i] == 'X' and pre == 'I': res += 8
if string[i] == 'I': res+=1
if string[i] == 'V' and pre != 'I': res += 5
if string[i] == 'L' and pre != 'X': res += 50
if string[i] == 'D' and pre != 'C': res += 500
if string[i] == 'V' and pre == 'I': res += 3
if string[i] == 'L' and pre == 'X': res += 30
if string[i] == 'D' and pre == 'C': res += 300
pre = string[i]
return res
string = "XXIX"
res = Solution.solution(string)
print(res)
|
b07db3110b76bfc520d4b6c9c08e7946c65e0729 | Sauvikk/practice_questions | /Level3/Two Pointers/Remove Element from Array.py | 910 | 3.90625 | 4 | # Given an array and a value, remove all the instances of that value in the array.
# Also return the number of elements left in the array after the operation.
# It does not matter what is left beyond the expected length.
#
# Example:
# If array A is [4, 1, 1, 2, 1, 3]
# and value elem is 1,
# then new length is 3, and A is now [4, 2, 3]
# Try to do it in less than linear additional space complexity.
class Solution:
@staticmethod
def solution(arr, target):
size = len(arr)
i = 0
j = 0
while i < size:
if arr[i] == target:
i += 1
else:
arr[j] = arr[i]
i += 1
j += 1
if j < len(arr):
del arr[j:]
return j
arr = [4, 1, 1, 2, 1, 3]
target = 3
res = Solution.solution(arr, target)
print(arr)
print(res)
|
ac7c9d60f30fe32645ce91b43692610d133230bc | Sauvikk/practice_questions | /Level4/LinkedLists/Reverse Link List II.py | 1,244 | 4.0625 | 4 | # Reverse a linked list from position m to n. Do it in-place and in one-pass.
#
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
#
# return 1->4->3->2->5->NULL.
#
# Note:
# Given m, n satisfy the following condition:
# 1 ≤ m ≤ n ≤ length of list. Note 2:
# Usually the version often seen in the interviews is reversing the
# whole linked list which is obviously an easier version of this question.
# http://n00tc0d3r.blogspot.in/2013/05/reverse-linked-list.html
from Level4.LinkedLists.LinkedList import LinkedList, Node
class Solution:
@staticmethod
def solution(head, m, n):
dummy = Node(0, head)
current = head
prev = dummy
pos = 1
while pos < m and current:
prev = current
current = current.next
pos += 1
while pos < n and current:
next = current.next.next
current.next.next = prev.next
prev.next = current.next
current.next = next
pos += 1
head = dummy.next
return head
A = LinkedList()
A.add(5)
A.add(4)
A.add(3)
A.add(2)
A.add(1)
res = Solution.solution(A.get_root(), 1, 5)
# res = A.get_root()
while res:
print(res.val)
res = res.next
|
4a0eca90de3ce7fb0ab6decb0ec6aadb32c1a9fa | Sauvikk/practice_questions | /Level6/Trees/Identical Binary Trees.py | 998 | 4.15625 | 4 | # Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
#
# 1 1
# / \ / \
# 2 3 2 3
#
# Output :
# 1 or True
from Level6.Trees.BinaryTree import BinaryTree
class Solution:
def solution(self, rootA, rootB):
if rootA == rootB:
print('h')
return True
if rootA is None or rootB is None:
return False
# if rootA is None and rootB is None:
# return True
return ((rootA.val == rootB.val) and self.solution(rootA.left, rootB.left) and
self.solution(rootA.right, rootB.right))
A = BinaryTree()
A.insert(100)
A.insert(102)
A.insert(96)
B = BinaryTree()
B.insert(100)
B.insert(102)
B.insert(96)
res = Solution().solution(A.root, B.root)
print(res)
|
7a0344562a91aa7afd4413b71b045df2e4d1618d | Sauvikk/practice_questions | /Level2/Math/Excel Column Number.py | 374 | 3.59375 | 4 | import math
class Solution:
@staticmethod
def solution(n):
size = len(n) - 1
res = 0
power = 0
while size >= 0:
curr_char = n[size]
res += int(math.pow(26, power) * (ord(curr_char) - ord('A') + 1))
size -= 1
power += 1
return res
a = 'AAC'
res = Solution.solution(a)
print(res)
|
f01f207884a49e01abbe088eab7fb9f9080b0dce | Sauvikk/practice_questions | /Level4/LinkedLists/Palindrome List.py | 1,569 | 4.03125 | 4 | # Given a singly linked list, determine if its a palindrome.
# Return 1 or 0 denoting if its a palindrome or not, respectively.
#
# Notes:
# - Expected solution is linear in time and constant in space.
#
# For example,
#
# List 1-->2-->1 is a palindrome.
# List 1-->2-->3 is not a palindrome.
from Level4.LinkedLists.LinkedList import LinkedList, Node
class Solution:
def reverse(self, head):
current = head
prev = None
while current:
next = current.next
current.next = prev
prev = current
current = next
head = prev
return head
def compare(self, first, second):
while first and second:
if first.val == second.val:
first = first.next
second = second.next
else:
return 0
if first is None and second is None:
return 1
def solution(self, head):
fast = head
slow = head
prevSlow = head
while fast and fast.next:
fast = fast.next.next
prevSlow = slow
slow = slow.next
if fast:
slow = slow.next
second = slow
prevSlow.next = None
second = self.reverse(second)
res = self.compare(head, second)
if mid:
prevSlow.next = mid
mid.next = second
else:
prevSlow.next = second
LinkedList.print_any(head)
return res
A = LinkedList()
A.add(1)
res = Solution().solution(A.get_root())
print(res)
|
6b29be0ef1d29f8a339946489031902b36ca0494 | Sauvikk/practice_questions | /Level8/Capture Regions on Board.py | 2,104 | 3.734375 | 4 | # Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
#
# A region is captured by flipping all 'O's into 'X's in that surrounded region.
#
# For example,
#
# X X X X
# X O O X
# X X O X
# X O X X
# After running your function, the board should be:
#
# X X X X
# X X X X
# X X X X
# X O X X
class Solution:
def sol(self, board):
row = len(board)
if row == 0:
return
col = len(board[0])
bb = [[False for j in range(0, col)] for i in range(0, row)]
que = []
for i in range(0, col):
if board[0][i] == 'O':
bb[0][i] = True
que.append([0, i])
if board[row - 1][i] == 'O':
bb[row - 1][i] = True
que.append([row - 1, i])
for i in range(0, row):
if board[i][0] == 'O':
bb[i][0] = True
que.append([i, 0])
if board[i][col - 1] == 'O':
bb[i][col - 1] = True
que.append([i, col - 1])
while que:
i = que[0][0]
j = que[0][1]
que.pop(0)
if (i - 1 > 0 and board[i - 1][j] == 'O' and bb[i - 1][j] == False):
bb[i - 1][j] = True
que.append([i - 1, j])
if (i + 1 < row - 1 and board[i + 1][j] == 'O' and bb[i + 1][j] == False):
bb[i + 1][j] = True
que.append([i + 1, j])
if (j - 1 > 0 and board[i][j - 1] == 'O' and bb[i][j - 1] == False):
bb[i][j - 1] = True
que.append([i, j - 1])
if (j + 1 < col - 1 and board[i][j + 1] == 'O' and bb[i][j + 1] == False):
bb[i][j + 1] = True
que.append([i, j + 1])
for i in range(0, row):
for j in range(0, col):
if board[i][j] == 'O' and bb[i][j] == False:
board[i][j] = 'X'
return
b = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
(Solution().sol(b))
print(b)
|
60bd6a8acbae73c72ee3de7585009855256c0cdc | Sauvikk/practice_questions | /Level3/Bit Manipulation/Single Number.py | 561 | 3.921875 | 4 | # Given an array of integers, every element appears twice except for one. Find that single one.
#
# Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#
# Example :
#
# Input : [1 2 2 3 1]
# Output : 3
class Solution:
@staticmethod
def solution(arr):
res = 0
for num in arr:
print(str(res) + ' XOR ' + str(num), end=' = ')
res ^= num
print(res)
return res
arr = [1, 2, 2, 3, 1]
res = Solution.solution(arr)
print('ans')
print(res)
|
cfeee7ddf64c1e21b4aca25370aea489bc15be6a | TrellixVulnTeam/Python-Exercises_3RSX | /Training/Training.py | 15,093 | 3.609375 | 4 |
import tkinter
from tkinter import *
#Page 107~111
class ParentWindow(Frame):
def __init__(self, master):
Frame.__init__(self)
self.master = master
self.master.resizable(width=False, height=False)
self.master.geometry(f'{700}x{400}')
self.master.title('Learning Tkinter')
self.master.config(bg='#eee')
self.varFName = StringVar()
self.varLName = StringVar()
self.lblFName = Label(self.master, text='First Name: ', font=('Helvetica', 16), fg='black', bg='#eee')
self.lblFName.grid(row=0,column=0, padx=(30,0), pady=(30,0))
self.lblLName = Label(self.master, text='Last Name: ', font=('Helvetica', 16), fg='black', bg='#eee')
self.lblLName.grid(row=1,column=0, padx=(30,0), pady=(30,0))
self.lblDisplay = Label(self.master, text='', font=('Helvetica', 16), fg='black', bg='#eee')
self.lblDisplay.grid(row=3,column=1, padx=(30,0), pady=(30,0))
self.txtFName = Entry(self.master, text=self.varFName, font=('Helvetica', 16), fg='black', bg='#fff')
self.txtFName.grid(row=0,column=1, padx=(30,0), pady=(30,0))
self.txtLName = Entry(self.master, text=self.varLName, font=('Helvetica', 16), fg='black', bg='#fff')
self.txtLName.grid(row=1,column=1, padx=(30,0), pady=(30,0))
self.btnSubmit = Button(self.master, text='Submit', width=10, height=2, command=self.submit)
self.btnSubmit.grid(row=2,column=1, padx=(0,0), pady=(30,0), sticky=NE)
self.btnCancel = Button(self.master, text='Cancel', width=10, height=2, comman=self.cancel)
self.btnCancel.grid(row=2,column=1, padx=(0,90), pady=(30,0), sticky=NE)
def submit(self):
fn = self.varFName.get()
ln = self.varLName.get()
self.lblDisplay.config(text=f"Hello {fn} {ln}!")
def cancel(self):
self.master.destroy()
if __name__ == "__main__":
root = Tk()
App = ParentWindow(root)
root.mainloop()
# #page 104
# # parent class
# class Organism:
# name = "Unknown"
# species = "Unknown"
# legs = None
# arms = None
# dna = "Sequence A"
# origin = "Unknown"
# carbon_based = True
#
# def information(self):
# msg = f"\nName: {self.name}\nSpecies: {self.species}\nLegs: {self.legs}\
# \nArms: {self.arms}\nDNA: {self.dna}\nOrigin: {self.origin}\
# \nCarbon_Based: {self.carbon_based}"
# return msg
#
# # child class instance
# class Human(Organism):
# name = 'MacGuyver'
# species = "Homosapien"
# legs = 2
# arms = 2
# origin = 'Earth'
#
# def ingenuity(self):
# msg = "\nCreates a deadly weapon using only a paper clip, chewing gum, and a roll of duct tape!"
# return msg
#
# # another child class instance
# class Dog(Organism):
# name = "Spot"
# species = "Canine"
# legs = 4
# arms = 0
# dna = "Sequence B"
# origin = "Earth"
#
# def bite(self):
# msg = "\nEmits a loud, menacing growl and bites down ferociously on it's target!"
# return msg
#
# # another child class instance
# class Bacterium(Organism):
# name = 'X'
# species = 'Bacteria'
# legs = 0
# arms = 0
# dna = "Sequence C"
# origin = 'Mars'
#
# def replication(self):
# msg = "\nThe cells begin to divide and multiply into two separate organism!"
# return msg
#
#
# if __name__ == "__main__":
# human = Human()
# print(human.information())
# print(human.ingenuity())
#
# dog = Dog()
# print(dog.information())
# print(dog.bite())
#
# bacteria = Bacterium()
# print(bacteria.information())
# print(bacteria.replication())
# # page 101
# import sqlite3
# #print(dir(sqlite3))
# #print(help(sqlite3))
#
# conn = sqlite3.connect('test.db')
# with conn:
# cur = conn.cursor()
# cur.execute("CREATE TABLE IF NOT EXISTS tbl_persons(\
# ID INTEGER PRIMARY KEY AUTOINCREMENT,\
# col_fname TEXT,\
# col_lname TEXT,\
# col_email TEXT\
# )")
#
# conn.commit()
#
# conn.close()
#
# conn = sqlite3.connect('test.db')
#
# def init():
# with conn:
# cur = conn.cursor()
# # cur.execute("INSERT INTO tbl_persons(col_fname, col_lname, col_email) VALUES (?,?,?)", \
# # ('Bob', 'Smith','bsmith@gmail.com'))
# # cur.execute("INSERT INTO tbl_persons(col_fname, col_lname, col_email) VALUES \
# # ('Sarah', 'Johnes','sjones@gmail.com')")
# # cur.execute("INSERT INTO tbl_persons(col_fname, col_lname, col_email) VALUES \
# # ('Sally', 'May','smay@gmail.com')")
# cur.execute("INSERT INTO tbl_persons(col_fname, col_lname, col_email) VALUES \
# ('Kevin', 'Bacon','kbacon@rocketmail.com')")
# conn.commit()
# conn.close()
#
#
# conn = sqlite3.connect('test.db')
# with conn:
# cur = conn.cursor()
# cur.execute("SELECT col_fname,col_lname,col_email FROM tbl_persons WHERE col_fname = 'Sarah'")
# varPerson = cur.fetchall()
# for item in varPerson:
# msg = f"First Name: {item[0]}\nLast Name: {item[1]}\nEmail: {item[2]}"
# print(msg)
# conn.commit()
# conn.close()
# # page 99
# import os
# # visit docs.python.org
# fname = 'IOtest.txt'
# fpath = 'C:\\Users\\Student\\Desktop\\TechAcademy\\8b-Python'
#
# totalPath = os.path.join(fpath,fname)
# print(totalPath)
# # page 97 and 98
# import os
# print(dir(os.getcwd()))
# print(os.getcwd())
# print(os.listdir())
# #print(help(open))
#
# def writeData():
# data = '\nHello World!\n'
# with open('IOtest.txt', 'a') as f:
# f.write(data)
# f.close()
#
# def openFile():
# with open('IOtest.txt', 'r') as f:
# data = f.read()
# print(data)
# f.close()
#
#
# if __name__ == '__main__':
# writeData()
# openFile()
# # page 96
# def getName(name=""):
# name = askName(name)
# print("Thank you, welcome {}!".format(name))
#
#
# def askName(name):
# go = True
# while go:
# if name == "":
# name = input("Please enter your name:\n>>> ")
# if name != "":
# go = False
#
# return name
#
#
# if __name__ == '__main__':
# getName()
# page 94
#
# def start(nice=0,mean=0,name=""):
# # get user's name
# name = describe_game(name)
# nice,mean,name = nice_mean(nice,mean,name)
#
# def describe_game(name):
# '''
# check if this is a new game or not.
# If it is new, get the user's name.
# If it is not a new game, thank the player for
# playing again and continue with the game
# '''
# # meaning, if we do not already have this user's name.
# # then they are a new player and we need to get their name
# if name != "":
# print(f"\nThank you for playing again, {name}")
# else:
# stop = True
# while stop:
# if name == "":
# name = input("\nWhat is your name? \n>>> ").capitalize()
# if name != "":
# print(f"\nWelcome, {name}")
# print("\nIn this game, you will be greated \nby several different people.\nYou can choose to be nice or mean")
# print("but at the end of the game your fate\nwill be sealed by your actions.")
# stop = False
# return name
#
# def nice_mean(nice,mean,name):
# stop = True
# while stop:
# show_score(nice,mean,name)
# pick = input("\nA stranger approaches you for a \nconversation. Will you be nice\nor mean? (N/M)\n>>> ").lower()
# if pick =="n":
# print("\nThe stranger walks away smiling...")
# nice = (nice + 1)
# stop= False
# if pick == "m":
# print("\nThe stranger glares at you \nmenacingly and storms off...")
# mean = (mean + 1)
# stop = False
# score(nice, mean, name) # pass the 3 variables to the score()
# return
#
# def show_score(nice,mean,name):
# print(f"\n{name}, your current total: \n({nice}, Nice) and ({mean}, Mean)")
#
# def score(nice,mean,name):
# # score function is being passed the values stored within the 2 variables
# if nice>2: # if condition is valid, call win function passing in the variables so it can use them
# win(nice,mean,name)
# if mean > 2: # if condition is valid, call lose function passing in the variables so it can use them
# lose(nice,mean,name)
# else: # else, call nice_mean function passing in the variables so it can use them
# nice_mean(nice,mean,name)
#
# def win(nice,mean,name):
# #Substitute the {} wildcards with our variable values
# print(f"\nNice job {name}, you win! \nEveryone loves you and you've \nmade lots of friends along the way!")
# # call again function and pass in our variables
# again(nice,mean,name)
#
# def lose(nice,mean,name):
# #Substitute the {} wildcards with our variable values
# print(f"\nAhhh too bad, game over! \n{name}, you live in a dirty beat-up \nvan by the river, wretched and along!")
# #call again functio and pass in our variables
# again(nice,mean,name)
#
# def again(nice,mean,name):
# stop = True
# while stop:
# choice = input("\nDo you want to play again? (y/n):\n>>> ").lower()
# if choice == 'y':
# stop = False
# reset(nice,mean,name)
# if choice == 'n':
# print("\nOh, so sad, sorry to see you go!")
# stop = False
# quit()
# else:
# print("\nEnter ( Y ) for 'YES', ( N ) for 'NO':\n>>> ")
#
# def reset(nice,mean,name):
# nice = 0
# mean = 0
# #Notice, I do not reset the name variable as that same user has elected to play again
# start(nice,mean,name)
#
#
#
# if __name__ == "__main__":
# start()
# # page 93
# def start():
# fname = "Sarah"
# lname = "Connor"
# age = 28
# gender = "Female"
# get_info(fname,lname,age,gender)
# # print(f"Hello {get_name()}!")
#
# def get_info(fname, lname, age, gender):
# print(f"My name is {fname} {lname}. I am {age} year-old {gender}.")
#
# def get_name():
# name = input("What is your name? ")
# return name
#
# if __name__ == "__main__":
# start()
# # page 89 and 90
# def getInfo():
# var1 = input("Please provide the first numeric value: ")
# var2 = input("Please provide the second numeric value: ")
# return var1,var2
#
# def compute():
# go = True
# while go:
# var1, var2 = getInfo()
# try:
# var3 = int(var1) + int(var2)
# print("{} + {} = {}".format(var1, var2, var3))
# go = False
# except ValueError as e:
# print("{}: \n\nYou did not provide a numaric value!".format(e))
# except:
# print("\n\nOops, you provided an invalid input, program will close now!")
#
# if __name__ == "__main__":
# compute()
# # page 87
# def print_app():
# name = (__name__) # gets the name of the class
# return name
# print(print_app())
# # page 85
# # Save a file by a class name, import the file name, and access by the file name
#
# import math
#
# def getNumbers(num1, num2):
# results = num1 * num2
# print('test')
# return results
#
# getNumbers(3,5)
#
# if __name__ == '__main__':
# pass
# # page 83
# # commenting
# """ Long form commenting
# multi-line commenting
# """
#
# def printMe():
# '''This is the description for printMe'''
#
# print(printMe.__doc__)
#
# help(printMe)
# # page 81
# fName = input("What is your \"first name\"?\n>>> ")
# lName = input("What is your \"last name\"?\n>>> ")
# print("{} {}, welcome to python!".format(fName, lName))
# # page 77
# mySentence = 'loves the color'
# color_list = ['red','blue','green','pink','teal','black']
# def color_function(name):
# lst = []
# for color in color_list:
# msg = "{} {} {}".format(name, mySentence,color)
# lst.append(msg)
# return lst
#
# for sentence in color_function('Bob'):
# print(sentence)
# # page 76
# mySentence = 'I love the color'
# color_list = ['red','blue','green','pink','teal','black']
# def color_function():
# for color in color_list:
# print("{} {}".format(mySentence,color) )
#
# color_function()
# # page 68
# myList = ('Pink','Black','Green','Teal','Red','Blue')
# for color in myList:
# if color == 'Black':
# print('The chosen color is Green.')
# # page 67
# mySentence = 'loves the color'
# color_list = ['red','blue','green','pink','teal','black']
#
# def color_function(name):
# lst = []
# for i in color_list:
# msg = "{0} {1} {2}".format(name,mySentence,i)
# lst.append(msg)
# return lst
#
# def get_name():
# go = True
# while go:
# name = input('What is your name? ')
# if name.strip() == '':
# print('You need to provide a name: ')
# elif name.lower() == 'sally':
# print('Sally you may not use this software ;P')
# else:
# go = False
# lst = color_function(name)
# for i in lst:
# print(i)
#
# get_name()
# # page 66
# x = 12
# key = False
# if x == 12:
# if key:
# print("x is equal to 12 and they have the key!")
# else:
# print('x is equal to 12 and they DO NOT have the key!')
# elif x < 12:
# print('x is less than 12')
# else:
# print("x is greater than 12")
# # page 65
# for i in range(10):
# print(i)
#
# j = 0
# while j < 10:
# print(j)
# j += 1
# # page 63
# answer = True
# # page 62
# dict = {'index1': 1, 'index2': 2, 'index3':355}
# print(dict)
# print(dict['index2'])
#
# users = { 'employee1': {'fname':'Bob','lname':'Smith','phone':'123-456-7890'} , 'employee2': {'fname':'Mary','lname':'Jones','phone':'152-364-5764'}}
# print(users['employee2'])
# print(users['employee2']['phone'])
#
# print('User: {} {}\nPhone: {}'.format(users['employee2']['fname'],users['employee2']['lname'],users['employee2']['phone']) )
# # --------Drill 60---------
# lang = [ 'python', 'c#', 'c++', 'javascript', 'html', 'css' ]
# lang.insert(0,'java')
# lang.remove('html')
# lang.append('spl')
# print(lang)
# print(lang[ lang.index('python') ].upper() )
# List = [2,3,4]
# List.append(5)
# print(len(List))
# print()
# for i in List:
# print(i)
# print()
# print(List[2])
# str = "Hello World!"
# for i in enumerate(str):
# print(i)
# num1 = "1"
# print(type(num1))
# num2 = 2
# print(type(num2))
# print(int(num1) + num2)
# str = "Hello World!"
# len(str)
# str[0]
# str[1]
# str[12]
# str[11]
# print(str + " and " + str)
# print("{} and {}".format(str, str))
# for x in range(9, 10):
# print(x)
# string = "Hello World"
# for x in string:
# print(x)
# def myName():
# print("Hello World!")
# print()
# a = 'eat'
# b = 'sleep'
# c = 'code'
# alive = True
#
# for x in range(5):
# print("{}, {}, {}".format(a, b, c))
|
8bf85ec04b5f5619a235f1506b7226597a75bef0 | Kaushikdhar007/pythontutorials | /kaushiklaptop/NUMBER GUESS.py | 766 | 4.15625 | 4 | n=18
print("You have only 5 guesses!! So please be aware to do the operation\n")
time_of_guessing=1
while(time_of_guessing<=5):
no_to_guess = int(input("ENTER your number\n"))
if no_to_guess>n:
print("You guessed the number above the actual one\n")
print("You have only", 5 - time_of_guessing, "more guesses")
time_of_guessing = time_of_guessing + 1
elif no_to_guess<n:
print("You guessed the number below the actual one\n")
print("You have only",5-time_of_guessing,"more guesses")
time_of_guessing=time_of_guessing+1
continue
elif no_to_guess==n:
print("You have printed the actual number by guessing successfully at guess no.",time_of_guessing)
break
|
d490be3c8d03e183441c0409ede57369766f695e | Kaushikdhar007/pythontutorials | /kaushiklaptop/sayangym example2.py | 1,185 | 3.6875 | 4 | # QUESTION:there is n seats in a row.you are given a string s with length n ; for each valid i,the i'th character of s is '0' if the i'th seat is empty or '1' if there is someone sitting in that seat. t wo people are friends if they are sitting next to each other. two friends are always are part of the same group of friends . can you find the number of groups? using python
#ANS:
print("How much time you want to do the operation\n")
time_to_do_operation = int(input())
for _ in range(time_to_do_operation):
print("\n!!Enter the sitting sequence!!\n")
base=input()
arrangement = [int(i) for i in base ]
groups = 0
if arrangement[0] == 1:
groups += 1
for i in range(1, len(arrangement)):
rev = True
if arrangement[i] == 1:
if arrangement[i - 1] != 1:
groups += 1
print("Number of groups are",groups)
# t = int(input())
# for i in range(t):
# b = input()
#
# c = 0
# for i in range(len(b)):
# if b[i] == '0' and b[i - 1] == '1' and i != 0:
# c += 1
#
# if b[-1] == '1':
# c += 1
# print(c) |
9c3b52d69f87a42ca2160dfd9ec4ee713b2bc444 | juliazrtsk/programmer_school_python | /15_while.py | 4,992 | 4.375 | 4 | # Мы с вами уже изучили цикл for
# Если вы его забыли, бегом искать нужный файлик и повторять
# Если вспомнили, продолжим :)
# Цикл for - не единственный вид цикла в программировании
# Сегодня мы изучим с вами новый цикл
# Он называется while (читается "вайл")
# В переводе while означает "пока"
# Давайте сразу к примеру
# Выведем на экран числа от 1 до 3
n = 1
while n <= 3:
print(n)
n = n + 1
# На первый взгляд эта конструкция не кажется понятной
# Давайте разбираться
# Цикл начинается с ключевого слова while.
# А после него идёт хорошо знакомое вам условие.
# Но ведь мы же не if пишем, в чём дело?
# Вспомните перевод слова while - "пока"
# Основная идея цикла в том, что команды, которые находятся внутри него,
# будут выполняться ПОКА условие возле слова while будет равно True
# Теперь давайте пройдём каждый шаг цикла, чтобы в этом убедиться
# До начала цикла мы завели переменную n.
# Именно её значения мы будем выводить на экран. Начать нам надо с числа 1, поэтому в n мы сразу положим 1
# Далее, мы объявили цикл
# while n <= 3:
# Тело цикла будет выполняться ПОКА число n будет меньше либо равно 3.
# Кстати, не забывайте о двоеточии после условия, оно обязательно :)
# Дальше начинается тело цикла: это все команды с отступом слева
# Первая команда выводит текущее значение переменной n на экран
# print(n)
# Вторая команда интереснее: она ИЗМЕНЯЕТ значение переменной n
# А именно, увеличивает число, которое хранится в n, на 1
# n = n + 1
# Как это вычисляется: программа берёт то, то В ДАННЫЙ МОМЕНТ лежит в переменной n
# и подставляет его в выражение. На первой итерации цикла (итерация = шаг) в n лежит 1
# Поэтому будет вычисляться выражение 1 + 1.
# Результат программа запишет снова в переменную n.
# Т.е. после того, как на первой итерации выполнятся все команды внутри цикла, в переменной n будет лежать число 2
# А в конце второй итерации будет лежать число 3
# Это легко проверить. Давайте немного изменим программу:
n = 1
while n <= 3:
print('Начало итерации. n = ', n)
print(n)
n = n + 1
print('Конец итерации. n = ', n)
print('=====================================') # это просто разделитель, чтобы было проще смотреть, что вывелось на экран
# Итак, что мы видим
# Итерация 1: в начале n = 1, в конце n = 2
# Итерация 2: в начале n = 2, в конце n = 3
# Итерация 3: в начале n = 3, в конце n = 4
# Теперь давайте разберёмся, почему итераций ровно 3
# Когда итерация заканчивается (т.е. когда отработали все команды внутри цикла),
# цикл ПРОВЕРЯЕТ УСЛОВИЕ, которое написано после while
# Если его результат True, тело цикла выполняется ещё раз
# Если False, то цикл заканчивает свою работу
# Изменим программу ещё раз
n = 1
while n <= 3:
print('Начало итерации. n = ', n)
print(n)
n = n + 1
print('Конец итерации. n = ', n)
print('n < 3 == ', n <= 3)
print('=====================================')
# Теперь мы видим чему в конце каждой итерации равно условие
# На последней итерации n = 4, а это больше 3. Поэтому получаем False и завершаем вычисления. |
89a6c4aa2f721d5ea594de77df4db16412182987 | juliazrtsk/programmer_school_python | /SnakeGame/01_window_and_up_key.py | 2,443 | 3.5 | 4 | # Как обычно, в самом начале импортируем библиотеку
import turtle
# Это константа - переменная, значение которой мы не будем менять по ходу выполнения программы
# В ней лежит величина шага, котороый будет делать змея
step = 10
# Настройка окна
win = turtle.Screen() # Создаём объект, с помощью которого мы сможем управлять игровым окном
# Задаём ему заголовок (он будет сверху возле кнопки закрытия окна)
win.title("Игра Змейка")
# Настраиваем размеры окна
win.setup(width=600, height=600)
win.bgcolor("pink") # Можно поиграться и выбрать себе цвет игрового поля :)
# Создаём черепашку. Это мы сто раз делали
head = turtle.Turtle()
# Задаём черепашке форму. В данном случае, квадрат
head.shape("square")
# Поднимаем хвост для того, чтобы черепашка не оставляла линий за собой
head.penup()
head.setx(0) # Ставим черепашку в цент экрана. Т.е. задаём координаты (0,0)
head.sety(0)
head.direction = "stop" # Про это подробнее в другом файле
# Функция для передвижения змеи
def move():
if head.direction == "up": # Сравниваем, смотрит ли черепашка вверх
y = head.ycor() # Получаем координату y черепахи. Ту, в которой она В ДАННЫЙ МОМЕНТ
head.sety(y + step) # К координате прибавляем величину шага. В результате, черепаха сдвигается
# Это функция, которая меняет направление черепахи так, чтобы она как бы смотрела вверх
def go_up():
head.direction = "up"
# Здесь указываем окну, как реагировать на нажатия клавиш
win.onkeypress(go_up, "Up")
win.listen()
# Игровой бесконечный цикл
while True:
move()
win.update()
|
65073c8b0166563cde44701c2850fc3aea535463 | Faisal-Alqabbani/python_fudamentals_assigments | /OOP/user/alqabbani_faisal.py | 977 | 3.875 | 4 | class User:
def __init__(self, name):
self.name = name
self.balance = 10000
def make_deposit(self,amount):
if amount <= 0:
print('The amount must be greater than zero')
else:
self.balance += amount
return self
def make_withdrawal(self, amount):
if amount > self.balance:
print('You have no money enough')
else:
self.balance -= amount
return self
def display_user_balance(self):
print(f"{self.name} has ${self.balance}")
def transfer_money(self, amount, user):
self.balance -= amount
user.balance += amount
print(f"Transfer process ${amount} successfully to {user.name}")
return self
user1 = User(name='Mohammed')
user2 = User(name='Faisal')
user3 = User(name="khaled")
user1.display_user_balance()
user1.make_deposit(0)
user1.transfer_money(300, user2)
user2.display_user_balance()
|
e4d8c093844328eefc7d366c8bf254a73daddf08 | LMsmith/tic-tac-toe | /game.py | 3,239 | 3.671875 | 4 | """game.py - File for collecting game functions."""
import logging
from google.appengine.ext import ndb
import endpoints
import random
def check_win(positions, move):
"""Returns a status string of 'win' or 'continue'
Args:
positions: The X's or O's, depending on player turn
move: The most recent move"""
status = "continue"
winning_moves = [
[1,2,3],
[1,4,7],
[1,5,9],
[2,5,8],
[3,5,7],
[3,6,9],
[4,5,6],
[7,8,9]
]
for winning_move in winning_moves:
if set(winning_move) < set(sorted(positions)):
status = "win"
return status
def computer_move(omoves, xmoves, remaining):
"""Returns the computer's move
Args:
omoves: The O's already marked
xmoves: The X's already marked
remaining: The remaining empty spaces"""
choice = random.choice(remaining)
"""If the middle space is available and no winning or
saving moves are available, computer chooses 5"""
if 5 in remaining:
choice = 5
player_moves = [xmoves, omoves]
"""Check if there is a move to prevent user from winning
or to allow computer to win. Prioritize winning over
saving"""
for moves in player_moves:
if 1 in moves:
if 2 in moves and 3 in remaining:
choice = 3
if 3 in moves and 2 in remaining:
choice = 2
if 4 in moves and 7 in remaining:
choice = 7
if 5 in moves and 9 in remaining:
choice = 9
if 7 in moves and 4 in remaining:
choice = 4
if 9 in moves and 5 in remaining:
choice = 5
if 2 in moves:
if 3 in moves and 1 in remaining:
choice = 1
if 5 in moves and 8 in remaining:
choice = 8
if 8 in moves and 5 in remaining:
choice = 5
if 3 in moves:
if 5 in moves and 7 in remaining:
choice = 7
if 6 in moves and 9 in remaining:
choice = 9
if 7 in moves and 5 in remaining:
choice = 5
if 9 in moves and 6 in remaining:
choice = 6
if 4 in moves:
if 5 in moves and 6 in remaining:
choice = 6
if 6 in moves and 5 in remaining:
choice = 5
if 7 in moves and 1 in remaining:
choice = 1
if 5 in moves:
if 6 in moves and 4 in remaining:
choice = 4
if 7 in moves and 3 in remaining:
choice = 3
if 8 in moves and 2 in remaining:
choice = 2
if 9 in moves and 1 in remaining:
choice = 1
if 6 in moves:
if 9 in moves and 3 in remaining:
choice = 3
if 7 in moves:
if 8 in moves and 9 in remaining:
choice = 9
if 9 in moves and 8 in remaining:
choice = 8
if 8 in moves:
if 9 in moves and 7 in remaining:
choice = 7
return choice |
f6fe437f066f6732dd994591bd5d2afc9814123c | wangyouwei2016/51rebootstudy | /1day/作业.py | 1,757 | 3.875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# http://blog.csdn.net/onlyanyz/article/details/45177643 参考的算法讲解
# pycharm技巧: 选中 ctrl+/ 批量注释 ctrl+d 快速复制 ctrl+e 快速删除 shift+enter 快速换行 ctrl+alt+l 遵守PEP8编码规范的格式化
# 方法1
unsortedList = [1 , 2 , 3 , 2 , 12 , 3 , 1 , 3 , 21 , 2 , 2 , 3 , 4111 , 22 , 3333 , 444 , 111 , 4 , 5 , 777 , 65555 ,
45 , 33 , 45]
count = 0
def bubbleSort(unsortedList):
list_length = len(unsortedList)
for i in range(0 , list_length - 1):
for j in range(0 , list_length - i - 1):
if unsortedList[j] > unsortedList[j + 1]:
unsortedList[j] , unsortedList[j + 1] = unsortedList[j + 1] , unsortedList[j]
return unsortedList
print(bubbleSort(unsortedList)[-2:])
# 方法2
unsortedList = [1 , 2 , 3 , 2 , 12 , 3 , 1 , 3 , 21 , 2 , 2 , 3 , 4111 , 22 , 3333 , 444 , 111 , 4 , 5 , 777 , 65555 ,
45 , 33 , 45]
for i in sorted(unsortedList)[-2:]:
print(i)
# 同学的
# coding=utf-8
a = [1 , 2 , 3 , 2 , 12 , 3 , 1 , 3 , 21 , 2 , 2 , 3 , 4111 , 22 , 3333 , 444 , 111 , 4 , 5 , 777 , 65555 , 45 , 33 ,
45]
max_num = 0
min_num = 0
for i in a:
if i > max_num:
min_num = max_num
max_num = i
elif i > min_num:
min_num = i
print "最大的两个值为:%s,%s" % (min_num , max_num)
_list = [1 , 2 , 3 , 2 , 12 , 3 , 1 , 3 , 21 , 65555,2 , 2 , 3 , 4111 , 22 , 3333 , 444 , 111 , 4 , 5 , 777 , 65555 , 45 ,
33 , 45]
max1 = 0
max2 = 0
for i in _list:
for j in _list:
if max1 < i:
max1 = i
if max1 > j and j > max2:
max2 = j
print 'The first big number: %s. Second big numbers: %s' % (max1 , max2)
|
d3f548a840828e2ee1fea68ccae5e09b10edd5de | Norskeaksel/My-solutions-to-Leetcode-problems | /Valid_Palindrome.py | 307 | 3.515625 | 4 | class Solution:
def isPalindrome(self, s: str) -> bool:
s=s.lower()
print(s)
regex = re.compile('[^0-9a-z]')
s=regex.sub('', s)
print(s)
l=len(s)
for i in range(l//2):
if s[i]!=s[l-1-i]:
return False
return True |
23dcf97cc27e70c5f2ab2a499c72b9e7d200963b | hirethissnake/2017 | /app/Snake.py | 4,541 | 4.03125 | 4 | """Independent snake object for use in Game."""
class Snake:
"""
Feisty snake object.
Has the following attributes:
size (int) - > 0, describes length of snake
identifier (uuid) - unique identifier describing for each snake
coords ([coords]) - array of [x,y] describing snakes body
healthPoints (int) - 0..100, describes moves a snake has before
death, unless that snake eats food.
oldHealthPoints(int) - health_points of snake on last move
oldCoords ([[coords]])- array of array of [x,y] describing past
locations the snake was at
state (string) - (unknown | food | attack | flee), describes
past actions of snake
taunt (string) - snake's current taunt
name (string) - name of snake
"""
def __init__(self, data):
"""
Initialize the Snake class.
param1: data - all snake-related data from server
Raises: ValueError
if: size not int.
"""
# often updated
self.identifier = data['id']
self.coords = data['coords']
self.healthPoints = data['health_points']
# old
self.oldSize = len(self.coords)
self.oldHealthPoints = data['health_points']
self.oldCoords = [data['coords']]
# snake personality
if 'taunt' in data:
self.taunt = data['taunt']
if 'name' in data:
self.name = data['name']
self.state = 'unknown'
def update(self, data):
"""
Update snake after previous move.
param1: data - all snake-related data from server
"""
healthPoints = data['health_points']
if healthPoints > 100 or healthPoints < 0:
raise ValueError('health_points must be between 100 and 0')
self.oldHealthPoints = self.healthPoints
self.healthPoints = healthPoints
self.coords = data['coords']
if 'taunt' in data:
self.taunt = data['taunt']
self.oldCoords.insert(0, self.coords)
def getSize(self):
"""
Return snake size
return: int - snake
"""
return len(self.coords)
def getHealth(self):
""""
Return snake healthPoints
return: int - healthPoints
"""
return self.healthPoints
def getHunger(self):
"""
Return hunger of snake
return: int - 100-healthPoints.
"""
return 100 - self.healthPoints
def getHeadPosition(self):
"""
Return head position.
return: array - as [x, y] coords.
"""
return self.coords[0]
def getAllPositions(self):
"""
Return array of coords.
return: array[array] - [x,y] of all body coords.
"""
return self.coords
def getTailPosition(self):
"""
Return array of tail position.
return: array - [x, y] of tail coords
"""
return self.coords[-1]
def setState(self, state):
"""
Set snake state. One of (unknown | food | attack | flee).
Raises: ValueError
if: state does not match four options
"""
if state == 'unknown' or state == 'food' or state == 'attack' or \
state == 'flee':
self.state = state
return
else:
raise ValueError('invalid state')
def getState(self):
"""
Return snake state.
return: string
"""
return self.state
def getIdentifier(self):
"""
Return snake's identifier.
return: uuid (as string)
"""
return self.identifier
def toString(self):
"""
Return Snake attribues as a string.
"""
asString = "identifer: " + str(self.identifier) + "\n\
healthPoints: " + str(self.healthPoints) + "\n\
state: " + str(self.state) + "\n\
coords: " + str(self.coords)
return asString
@staticmethod
def isInt(num, name):
"""Double check value is int."""
if not isinstance(num, int):
raise ValueError(str(name) + ' must be an integer')
@staticmethod
def isString(value, name):
"""Double check value is int."""
if not isinstance(value, str):
raise ValueError(str(name) + ' must be a string')
|
84565f3ba1ffeafb0142fc91352a38594cd27d8e | i5m/cs_schools | /ps1b.py | 895 | 3.9375 | 4 | def get_int_input(str_to_show):
try:
var = int(input(str_to_show))
return var
except:
return get_int_input(str_to_show)
def main():
annual_salary = get_int_input("Annual Salary: ")
portion_saved = get_int_input("Percentage saved per month out of 100: ")
total_cost = get_int_input("Total cost of house: ")
semi_annual_raise = get_int_input("Enter the semiannual raise out of 100: ")
portion_down_payment = total_cost / 4
current_savings = 0
r = 0.04 # return
months_req = 0
while(portion_down_payment >= current_savings):
current_savings += ((portion_saved/100)*annual_salary/12) + (current_savings * r/12)
months_req += 1
if(months_req % 6 == 0):
annual_salary += annual_salary * semi_annual_raise / 100
print("Number of months: ", months_req)
if __name__ == "__main__":
main()
|
be99bff4b371868985a64a79a23e34be58a0831f | KrishnaPatel1/python-workshop | /theory/methods.py | 1,722 | 4.28125 | 4 | def say_hello():
print("Hello")
print()
say_hello()
# Here is a method that calculates the double of a number
def double(number):
result = number * 2
return result
result = double(2)
print(result)
print()
# Here is a method that calculates the average of a list of numbers
def average(list_of_numbers):
total = 0
number_of_items_in_list = 0
average = 0
for number in list_of_numbers:
number_of_items_in_list = number_of_items_in_list + 1
total = total + number
average = total/number_of_items_in_list
return average
a_bunch_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = average(a_bunch_of_numbers)
print(result)
print()
# Challenge 1
# Create a function that takes a number
# it returns the negative of the number
# Note, use print(method) to print out the value
print("Challenge 1:")
# Challenge 2
# Imagine you are given some product that has some cost to it (e.g. $14.99)
# calculate the tax of the product and and it to the cost of the product
# return the total cost of the product
# assume the tax is 15%
# Note, use print() to print out the result of the method
print()
print("Challenge 2:")
# Challenge 3
# Create a method that
# takes in a student's test score and the total amount of points in the test
# returns the result of the student in percentage
print()
print("Challenge 3:")
# Challenge 4
# Create a method that:
# takes in one number
# if even, print the number and state that it is even
# if odd, print the number and state that it is odd
# if less than zero, print the number and state that it is negative
# if the number is a combination of the above conditions, then print both conditions (e.g. -2 is even and negative)
print()
print("Challenge 4:") |
19f67bb106389b6c796e3e81ad41faa285a3d579 | mf2492/percolation | /percolate.py | 3,264 | 3.8125 | 4 | #################################################
#Author: Michelle Austria Fernandez
#Uni: mf2492
#
#Program: percolate.py
#Overview: Contains functions that runs the
#percolation simulations
#################################################
import numpy as np
import os
def gridFile():
"""Prompts user to either enter an existing file or create
a new file"""
choice = ' '
while (choice != 'r' and choice != 'c'):
choice = raw_input("Would you like to read(r) an existing file"
+ " or create(c) a new file? ")
if (choice == 'r'):
existing_file = raw_input("Enter name of file: ")
bool_array_r = readFile(existing_file)
return percolate(bool_array_r)
elif (choice == 'c'):
new_file = raw_input("Enter name of output file: ")
p,n = probability()
percolates = writeFile(new_file, p, n)
return percolates
def defaultFile(i_file):
"""Runs simulation with given files without prompting the user"""
bool_array_r = readFile(i_file)
return percolate(bool_array_r)
def probability():
"""Prompts user to enter probability factor and size"""
p = input("Enter probability factor (between 0-1): ")
n = input("Enter grid size: ")
return p, n
def readFile(existing_file):
"""reads in the file and converts it to an array"""
f = open(existing_file, 'r')
size = f.readline()
print size.rstrip('\n')
line = f.readline()
array = []
while line:
print line.rstrip('\n')
array_line = line.split()
array_line = [int(item) for item in array_line]
array_line = [bool(item) for item in array_line]
array_line = np.invert(array_line)
array_line = array_line.astype(int)
array.append(array_line)
line = f.readline()
full_array = np.vstack(array)
f.close()
return full_array
def writeFile(file_name, probability, grid_size):
"""Writes out the file and runs the percolation program"""
grid = np.random.random(size = (grid_size,grid_size)) < probability
does_percolate = percolate(grid)
grid = grid.astype(bool)
grid = np.invert(grid)
grid = grid.astype(int)
grid = '\n'.join(' '.join(str(cell) for cell in row) for row in grid)
print(grid)
f = open(file_name, "w")
f.write(str(grid_size)+ '\n')
f.write(str(grid))
f.close
return does_percolate
def flow(bool_array):
"""Starts from the top of the grid to test percolation"""
x = bool_array.shape[0]
full = np.zeros(shape = (x, x))
for i in range(x):
flowFull(bool_array, full, 0, i)
return full
def flowFull(sites, full, i, j):
"""Goes through neighboring sites to fill"""
x = sites.shape[0]
if (i < 0 or i >= x): return;
if (j < 0 or j >= x): return;
if (not (sites[i][j])): return;
if (full[i][j]): return;
full[i][j] = True
flowFull(sites, full, i+1, j);
flowFull(sites, full, i, j+1);
flowFull(sites, full, i, j-1);
def percolate(site):
"""Determines wether the grid percolates"""
x = site.shape[0]
full = flow(site)
for i in range(x):
if (full[x-1][i]):
return True
else:
return False
|
a302c77cc096388b41f6b6c08dc6722d83f4792a | scottshull/Beer_Song-2 | /Beer_song2.py | 268 | 3.796875 | 4 | number = 99
while number >= 1:
print (str(number) + " bottles of beer on the wall, " + str(number) + " bottles of beer.")
print ("if one of those bottles should happen to fall")
number -= 1
print (str(number) + " bottles of beer on the wall.")
|
6631f58668a892977a251955f7d4301bdf8a0727 | JooHis/Euler | /Problem6_sumofnatural.py | 253 | 3.5625 | 4 | def main():
numbers = []
numbers_square = []
for i in range(1, 101):
numbers.append(i)
for j in range(1, len(numbers)+1):
numbers_square.append(numbers[j-1]**2)
print((sum(numbers))**2 - sum(numbers_square))
main()
|
157851270dbf9157dd88a88bfe73abdac9a630d3 | TurbulentCupcake/PythonLearning | /MyFirstClass.py | 904 | 3.578125 | 4 |
__metaclass__ = type
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello, world! I'm %s." %self.name
class Secretive:
def __inaccessible(self):
print "Bet you can't see me..."
def accessible(self):
print "The secret message is: "
self.__inaccessible()
class StudentCount:
__count = 0
def init(self):
self.count = 1
def show(self):
return self.count
def inc(self):
self.count += 1
class FooBar:
def __init__(self, value = 42):
self.somevar = value
def getValue(self):
return self.somevar
# Filters spam
class Filter:
def init(self):
self.blocked = []
def filter(self, sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter):
def init(self): #override init function in Filter
self.blocked = ['SPAM']
class Hello:
def printGreeting(self) |
6aa525dca1e1706fb98af98b3505d63e0f9af33d | mehulchopradev/first-python | /xyz/supercoders/modules/math.py | 408 | 3.765625 | 4 | # math.py -> math
def isEvenOrOdd(n):
'''take in n and return a string "even" or "odd"'''
return "Odd" if n % 2 else "Even"
# testing the functions in the module
# magic variable
print(__name__)
# when running this module separately __name__ = '__main__'
# when running this module as part of an import __name__ = 'math_ops'
if __name__ == '__main__':
n = int(input('enter n : '))
print(isEvenOrOdd(n)) |
e877edd10ee6819c51a5f763c04a02753506028f | mehulchopradev/first-python | /professor.py | 446 | 3.5625 | 4 | from person import Person
class Professor(Person):
def __init__(self, name, gender, subjects, contact=None):
super().__init__(name, gender, contact) # calls the Person class constructor
'''
Person.__init__(self, name, gender)
'''
self.subjects = subjects
# forced to override the @abstractmethod
def giveAttendance(self):
print('Attendance given by logging into the web portal')
|
8e0be5ef4b1c748f40df19cc63cee5b3023569ea | ashutoshm1771/Source-Code-from-Tutorials | /Python/19_python.py | 205 | 4.0625 | 4 | groceries = {'cereal', 'milk', 'starcrunch', 'beer', 'duck tape', 'lotion', 'beer'}
print(groceries)
if 'milk' in groceries:
print("You already have milk hoss!")
else:
print("Oh yea, you need milk!")
|
90fec32f73734fe80caf499592e50c140c881b78 | ashutoshm1771/Source-Code-from-Tutorials | /Python/09_python.py | 296 | 3.8125 | 4 | #from 0 to 10
for x in range(10):
print(x)
print("")
#from 5 to 12
for x in range(5, 12):
print(x)
print("")
#from 10 to 40 increment value 5
for x in range(10, 40, 5):
print(x)
print("")
#While loop
buttcrack = 5
while(buttcrack < 10):
print(buttcrack)
buttcrack += 1 |
8a854cdb27e9d56e28be4e9a3c613261baaef136 | sbikash-dev/python-impl-data-structures | /heaps.py | 2,499 | 3.578125 | 4 | ''' Implement Heap Data Structure (using Array).
1. minHeap
2. maxHeap
'''
def minHeapify(arr, i):
index = i
n = len(arr)
leftChild = 2*i + 1
rightChild = 2*i + 2
if (rightChild < n) and (arr[index] > arr[rightChild]):
index = rightChild
if (leftChild < n) and (arr[index] > arr[leftChild]):
index = leftChild
if index != i:
arr[index], arr[i] = arr[i], arr[index]
minHeapify(arr, index)
def maxHeapify(arr, i):
index = i
n = len(arr)
leftChild = 2*i + 1
rightChild = 2*i + 2
if (rightChild < n) and (arr[index] < arr[rightChild]):
index = rightChild
if (leftChild < n) and (arr[index] < arr[leftChild]):
index = leftChild
if index != i:
arr[index], arr[i] = arr[i], arr[index]
maxHeapify(arr, index)
def heapify(arr, func = minHeapify):
n = len(arr) // 2 - 1
for i in range(n, -1, -1):
func(arr, i)
def minHeapInsert(arr, item):
if not arr:
arr = [item]
return
arr.append(item)
i = len(arr) - 1
parent = (i - 1) // 2
while parent >= 0:
if arr[i] < arr[parent]:
arr[i], arr[parent] = arr[parent], arr[i]
i = parent
parent = (i - 1) // 2
else:
break
def minHeapifyDelete(arr):
delItem = None
if arr:
n = len(arr) - 1
if n == 0:
delItem = arr.pop(0)
else:
delItem = arr[0]
arr[0] = arr.pop(n)
minHeapify(arr, 0)
return delItem
if __name__ == '__main__':
<<<<<<< HEAD
=======
>>>>>>> c9dffcb4b59c9a63ec3064bc97b4c283d7845984
# Sample Input Cases
arr1 = [0,1,2,3,4,5,6,7,8,9]
arr2 = [9,8,7,6,5,4,3,2,1,0]
arr3 = [1,6,8,2,5,7,1,6,9,2]
arr4 = [9,2,6,3,7,1,3,5,6,9]
arr5 = [6,7,3,4,5,8,9,4,5,2]
arr6 = [3,6,8,2,7,9,2,1,9,4]
# Selected Input Case
arr = arr3
print('Input Array :',arr)
# Execute tests
#heapify(arr, maxHeapify)
#print('Max Heap :',arr)
heapify(arr, minHeapify)
print('Min Heap :',arr)
minHeapInsert(arr, 0)
print('Min Heap Insert :',arr)
minimun = minHeapifyDelete(arr)
<<<<<<< HEAD
print('Minimum Deleted :', minimun)
=======
print('minimum deleted :', minimun)
>>>>>>> c9dffcb4b59c9a63ec3064bc97b4c283d7845984
print('Min Heap Delete :', arr)
|
7b5018c93a21844025317efe9e1d63f6b39a1660 | kevinS-code/gapyear | /[2nd]ATM.py | 1,573 | 3.796875 | 4 | #ATM.py
money = 20000
print('กด 1 : ถอดเงิน')
print('กด 2 : เช็คยอดเงินเงิน')
print('กด q : ออกจากระบบ')
print('------------')
menu = input('กรุณาเลือกเมนู: ') #user เลือกแล้วเราจะเก็บเมนูไว้
while menu != 'q':
if menu == '1':
print('<<<< ถอดเงิน >>>>')
withdraw = int(input('กรุณากรองจำนวนเงิน: '))
while withdraw > money:
print('เงินในบัญชีไม่พอ กรุณากรองยอดงินในบัญขีให้ถูกต้อง')
withdraw = int(input('กรุณากรองจำนวนเงิน: '))
print('กรุณารับเงินงิน {} บาท'.format(withdraw))
money = money - withdraw # เอาจำนวนเงินตอนนี้มาลบกับเงินที่ถอน
print('คุณมียอดเงินคงเหลือ {} บาท'.format(money))
elif menu == '2':
print('ยอดเงินของคุณคือ: {} บาท'.format(money))
print('กด 1 : ถอดเงิน')
print('กด 2 : เช็คยอดเงินเงิน')
print('กด Q : ออกจากระบบ')
menu = input('กรุณาเลือกเมนู: ')
print('ขอบคุณที่ใช้บริการ กรุณารับบัตรคืน')
|
e83f064894c6d9a9a64de0bfbfc59f9d99640b79 | ArmstrongYang/StudyShare | /Python/string.py | 371 | 4.09375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
str = ('Hello World!')
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串
|
0efd3c6d587eaf6406f5663a8ad310791a4b28d1 | ArmstrongYang/StudyShare | /Python/shuffle.py | 773 | 3.5625 | 4 | #! usr/bin/python
# coding :utf-8
import copy
def shuffle(dic):
lst = []
if dic['k'] == 0:
return dic['l']
else:
lst = copy.deepcopy(dic['l'])
for i in range(dic['n']):
dic['l'][2*i] = lst[i]
dic['l'][2*i+1] = lst[i+dic['n']]
dic['k'] = dic['k'] - 1
return shuffle(dic)
T = int(input())
dic = {}
for i in range(T):
dic[i] = {}
dic[i]['n'], dic[i]['k'] = input().split()
dic[i]['n'] = int(dic[i]['n'])
dic[i]['k'] = int(dic[i]['k'])
dic[i]['l'] = input().split()
print('n ',dic[i]['n'])
print('k ',dic[i]['k'])
print('l ',dic[i]['l'])
#for j in len(dic[i]['l']):
# dic[i]['l'][j] = int(dic[i]['l'][j])
for i in range(T):
print(shuffle(dic[i]))
|
1264dcc56e287f6045788940dc366e09ae5296e2 | hoanghuyen98/fundamental-c4e19 | /Session04/homeword/turtle_2.py | 365 | 4 | 4 | from turtle import*
import random
shape("turtle")
colors = ['red', 'green', 'blue', 'white', 'yellow', 'pink', 'purple', 'orange']
bgcolor("black")
size = 1
speed(-1)
for i in range(100):
for j in range(4):
color(random.choice(colors))
forward(size)
left(90)
left(5)
size = size+3
color(random.choice(colors))
mainloop() |
45503c26f013260c74e10508d82eada3df377039 | hoanghuyen98/fundamental-c4e19 | /Session01/turtle_ex.py | 228 | 4.0625 | 4 | from turtle import *
shape("turtle")
color("black")
speed(-1)
soCanh = int(input("How much edge you want : "))
print("Number of side: ", soCanh)
for i in range(soCanh) :
forward(100)
left(360 / soCanh)
mainloop()
|
06bea009748a261e7d0c893a18d60e4b625d6243 | hoanghuyen98/fundamental-c4e19 | /Session05/homeword/Ex_1.py | 1,302 | 4.25 | 4 |
inventory = {
'gold' : 500,
'pouch': ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone', 'dagger', 'bedroll', 'bread loaf']
}
# Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list
print("1: Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list ")
print()
print(" =====>> List ban đầu : ")
print(inventory)
inventory['pocket'] = ['seashell', 'strange', 'berry', 'lint']
print(" =====>> List sau khi thêm : ")
print(inventory)
print()
print("* "*20)
# Then remove('dagger') from the list of items stored under the 'backpack' key
print("2: Then remove('dagger') from the list of items stored under the 'backpack' key")
print()
key = "backpack"
if key in inventory:
value = inventory[key]
value.pop(1)
print(" =====>> List sau khi xóa value dagger của key 'backpack ")
print()
print(inventory)
else:
print(" not found ")
print()
print("* "*20)
# Add 50 to the number stored under the 'gold' key.
print("3: Add 50 to the number stored under the 'gold' key.")
print()
key_1 = 'gold'
if key_1 in inventory:
inventory[key_1] += 50
print(" =====>> List sau khi thêm 50 vào 500 ")
print()
print(inventory)
print()
else:
inventory[key_1] = 50
print(inventory)
|
2892926d2543128cd90574c3f6d51a43d7b28b6a | hoanghuyen98/fundamental-c4e19 | /Session02/rand.py | 490 | 3.5625 | 4 | # # from random import randint
# # numb = randint(0,100)
# # print(numb)
# from random import randint
# numb = randint(0,100)
# if numb < 30 :
# print(" :< ")
# elif numb < 60 :
# print(" +__+ ")
# else :
# print(" ^__^ ")
n = 10
for i in range(n):
for j in range(n):
if j < n - i - 1:
print(" ", end = "")
else:
print("* ", end = "")
print("")
# for i in range(7):
# for j in range(7):
# pr
|
ddc625938250819c922150061152ab0ca36360c8 | hoanghuyen98/fundamental-c4e19 | /Session05/homeword/Ex_20_8_1.py | 208 | 3.84375 | 4 | strings = input(" Enter a string ")
letter_counts = {}
for letter in strings:
# print(letter)
letter_counts[letter] = letter_counts.get(letter, 0) + 1
# print(letter_counts)
print(letter_counts)
|
05ba21e69dab1b26f1f98a48fc3c186d37f8097b | hoanghuyen98/fundamental-c4e19 | /Session02/Homeword/BMI.py | 373 | 4.25 | 4 | height = int(input("Enter the height : "))
weight = int(input("Enter the weight : "))
BMI = weight/((height*height)*(10**(-4)))
print("BMI = ", BMI)
if BMI < 16:
print("==> Severely underweight !!")
elif BMI < 18.5:
print("==> Underweight !!")
elif BMI < 25:
print("==> Normal !!")
elif BMI < 30:
print("==> Overweight !!")
else :
print("==> Obese !!")
|
7bde2e83785eb3c44a6f2b69d1dff64bde4642e1 | Hengle/AutoAbstract | /calculate_df.py | 663 | 3.5625 | 4 | from get_data import read_data
from split_sentence import SplitSentence
from split_word import SimpleSplitWord
if __name__ == '__main__':
articles = read_data()
articles = [SplitSentence(article).split() for article in articles]
articles = [[SimpleSplitWord(sentence).split() for sentence in article ] for article in articles]
df = {}
for article in articles:
words = set()
for sentence in article:
words.update(sentence)
for word in words:
if word not in df:
df[word] = 0
df[word] += 1
with open('data/df.txt', 'w', encoding='utf-8') as f:
f.write('{}\n'.format(len(articles)))
for k in df:
f.write('{}: {}\n'.format(k, df[k])) |
5dcd6d8bab47ae6d5eac61616580a52cc572e5a8 | j-how/fisher | /app/libs/helper.py | 307 | 3.640625 | 4 | import re
def is_isbn_or_key(word):
word = word.replace('-', '')
prog = re.compile(r'^(\d{13})$|^(\d{10})$')
if prog.match(word):
isbn_or_key = 'isbn'
else:
isbn_or_key = 'key'
return isbn_or_key
if __name__ == '__main__':
print(is_isbn_or_key('99937-0-014-2'))
|
2bb7320fdd7042ad410a1d10f7b58b508f801c1a | nanfeng-dada/leetcode_note | /easy/27.removeElement.py | 1,224 | 3.96875 | 4 | # 在python中复制操作重新赋一个标识符,所以可以直接赋值
class Solution():
def removeElement(self, nums: list, val: int) -> int:
lst=[]
for i in range(len(nums)):
if nums[i]!=val:
lst.append(nums[i])
nums[:]=lst
return len(lst)
#python计数与删除操作
class Solution2:
def removeElement(self, nums, val):
c = nums.count(val)
i = 0
while i < c:
nums.remove(val)
i += 1
return len(nums)
# 正常解法为快慢指针
class Solution1():
def removeElement(self, nums: list, val: int) -> int:
cur_next=0
for j in range(len(nums)):
if nums[j]!=val:
nums[cur_next]=nums[j]
cur_next+=1
return cur_next
# 上面的解法的另一种书写形式
class Solution4:
def removeElement(self, nums: list, val: int) -> int:
i = 0
while i < len(nums):
if nums[i] == val:
nums[i] = nums[-1]
del nums[-1]
else:
i += 1
return len(nums)
if __name__=="__main__":
a=Solution1()
print(a.removeElement([3,2,2,3],3)) |
10e747d03c59a1a2f715b752a9f46fcb7351f750 | nanfeng-dada/leetcode_note | /easy/112.hasPathSum.py | 1,166 | 3.703125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#采用堆栈进行DFS,求解所有路径和,最后判断指定和是否在
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
q = [(root.val, root)]
allsum = []
while q:
cursum, node = q.pop()
if not node.right and not node.left:
allsum.append(cursum)
if node.left:
q.append((cursum + node.left.val, node.left))
if node.right:
q.append((cursum + node.right.val, node.right))
return sum in allsum
# 采用递归,递归返回值一般可通过and or max min 等去构造
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return sum==root.val
else:
return self.hasPathSum(root.right,sum-root.val) or \
self.hasPathSum(root.left,sum-root.val)
|
66e9d55b1eef5d6f57e8ae45f397f3ce087b9b56 | nanfeng-dada/leetcode_note | /easy/202.isHappy.py | 918 | 3.578125 | 4 |
# 按照快乐数的定义做就是了
# 还有一种找到了不快乐数的循环,这种非一般的解法不做考虑,机试的时候一般想不到
class Solution:
def isHappy(self, n: int) -> bool:
for _ in range(100):
n1 = 0
while n:
n1 += (n % 10) ** 2
n //= 10
if n1 == 1:
return True
n = n1
return False
# 保存一下结果,加速
class Solution1(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
already = set()
while n != 1:
num = 0
while n > 0:
tmp = n % 10
num += tmp ** 2
n //= 10
if num in already:
return False
else:
already.add(num)
n = num
return True
|
78a89301dca15e8d0709a881fa53eae4eb30e14a | piglaker/PAT | /AdvancedLevel_Python/1145.py | 1,520 | 3.640625 | 4 | def get_prime(Msize):
number = Msize
def is_prime(number):
for i in range(2, number):
if number % i == 0:
return False
else:
return True
while 1:
if is_prime(number):
return number
else:
number += 1
Msize, M, N = list(map(int, input().split()))
arr = list(map(int, input().split()))
task = list(map(int, input().split()))
hashing = {}
Msize = get_prime(Msize)
def insert_hash(e, hashing):
k = 1
key = e % Msize
if not key in hashing.keys():
hashing[key] = e
return [k]
elif hashing[key] == e:
return [k]
else:
success = False
for i in range(1, Msize):
key_tmp = (key + i ** 2) % Msize
k += 1
if not key_tmp in hashing.keys():
hashing[key_tmp] = e
success = True
break
elif hashing[key_tmp] != e :
pass
else:
return [k]
if not success :
k += 1
return k, str(e) + ' cannot be inserted.'
else:
return [k]
for e in arr:
insert_hash(e, hashing)
ans = 0
for e in task:
from copy import deepcopy
hashing_ = deepcopy(hashing)
tmp = insert_hash(e, hashing_)
if len(tmp) > 1:
print(tmp[1])
ans += tmp[0]
from math import modf
a, b = modf(ans / len(task) * 10)
if a >= 0.5:
print((b / 10 + 0.1))
else:
print(b / 10)
|
540983122e053194caafc99d91a49f38da01ae19 | StarliteOnTerra/csci127-Assignments | /hw_02/pig.py | 474 | 3.5625 | 4 | # By Jadeja Baptiste & Stacy Li
def part_pig_latin(name):
vowels = ('a', 'e', 'i', 'o', 'u',)
x = name[0]
if x.startswith(vowels):
return name + "ay"
else:
return name[1:] + x + "ay"
print(part_pig_latin("owen"))
print(part_pig_latin("evan"))
print(part_pig_latin("kayla"))
print(part_pig_latin("john"))
print(part_pig_latin("twilight"))
print(part_pig_latin("ulyesses"))
print(part_pig_latin("ian"))
print(part_pig_latin("becky")) |
71b291f8d923465e73b69f1cbd22d1e7583bd9ec | StarliteOnTerra/csci127-Assignments | /hw_05/hw_05.py | 337 | 3.703125 | 4 | l = [3, 4, 5, 6, 7, 8, 9, 10, 11]
def filterodd(l):
for x in l:
if x % 2 != 1:
continue
print(x)
print(filterodd(l))
l = [2, 3, 4, 5, 6]
def mapsquare(l):
l = [2, 3, 4, 5, 6]
for x in l:
x = x ** 2
print(x)
print(mapsquare(l))
|
2ee4e98f1a31c2ec2f85f2e582744301bd7833df | Laurasoto98/Adversarial-Search | /MiniMax.py | 1,950 | 3.59375 | 4 | #class that implements the MiniMax algorithm.
import random
import sys
import math
import Square
from TicTacToeAction import TicTacToeAction
from AlphaBetaSearch import AlphaBetaSearch
class MiniMax:
def __init__(self):
self.numberOfStates=0 #< counter to measure the number of iterations / states.
self.usePruning=False
def MinimaxDecision(self,state, usePruning):
self.usePruning = usePruning
if usePruning:
alphaBeta = AlphaBetaSearch()
action = alphaBeta.AlphaBetaDecision(state)
return action
self.numberOfStates = 0
actions = state.getActions()
utility=[]
for action in actions:
scores=[]
s=state.getResult(action)
utility.append(self.MinValue(s))
s.restoreState(action)
for i in range(len(actions)):
if utility[i] == max(utility):
action = actions[i]
break
print("State space size: " , self.numberOfStates)
return action
def MaxValue(self,state):
self.numberOfStates+=1
if state.isTerminal():
return state.getUtility()
v=-10000
actions = state.getActions()
utility=[]
for action in actions:
scores=[]
s=state.getResult(action)
utility.append(self.MinValue(s))
s.restoreState(action)
v=max(utility)
return v
def MinValue(self, state):
self.numberOfStates += 1
if state.isTerminal():
return state.getUtility()
v=10000
actions = state.getActions()
utility=[]
for action in actions:
s=state.getResult(action)
utility.append(self.MaxValue(s))
s.restoreState(action)
v=min(utility)
return v
|
5e4b6bd85d831e399fab92b6f745a6f7b0847cdb | kgraghav/expsolver | /expsolver.py | 7,105 | 3.703125 | 4 | class Solver:
"""
***Purpose: Solve "exp = 0"***
Inputs:
a. exp: expression to be solved e.g. 2*x**2+3*x-100=0
Solve:
a. solve(): solves for "exp = 0"
Outputs:
a. get_order(): Integer order of equation "exp=0"
b. get_root(): List of roots for "exp=0"
c. get_delta(): List of "0-exp(root)"
d. get_minima(): List of local minima
e. get_maxima(): List of local maxima
Determining order of equation:
a. IF "**" in expression, find the highest value following the "**" as order
b. Else if "*x" in expression, order is 1
c. Else if "x" in expression, order is 1
d. Else order is zero
e. If any execption occurs in steps "a" through "d"
If "x" in expresssion, order= 10
else order = 0
Order of expression is used to calculate the tolerance (xtol and ytol),since for higher orders,
small changes in "x" can result in significant changes in expression value
Determining roots of equation:
a. Find a semi-random starting "x" value as a function of order
b. create a list of "x" values (xlist) as [x, x+tol, x, x-tol]
c. Evaluate exp for xlist to obtain ylist
d. If ylist has a zero, append the x value to roots list
e. If ylist[0]*ylist[1] < 0 indicating the root lies between xlist[0] and xlist[1]
add the arithmetic mean of xlist[0] and xlist[1] to roots
f. If ylist[2]*ylist[3] < 0 indicating the root lies between xlist[2] and xlist[3]
add the arithmetic mean of xlist[2] and xlist[3] to roots
g. Else make xlist as [x=x+tol, x+tol=x+2*tol, x=x-tol, x-tol=x-2*tol]
h. Repeat steps a through f for a certain number of times (a large value, based on xtol)
i. Change xtol = xtol / order and repeat step h till exp(roots) is within ytol around zero
Determining maxima and minima:
a. If the difference in ylist[0] and ylist[1] from ylist goes from negative to positive,
add xlist[0] to minima
b. If the difference in ylist[0] and ylist[1] from ylist goes from positive to negative,
add xlist[0] to maxima
b. If the difference in ylist[2] and ylist[3] from ylist goes from negative to positive,
add xlist[2] to minima
b. If the difference in ylist[2] and ylist[3] from ylist goes from positive to negative,
add xlist[2] to maxima
"""
def __init__(self, exp):
### Create expression variable ###
self.exp=exp
def solve(self):
### Determine order of expression ###
ind=[0]
try:
if '**' in self.exp:
while '**' in self.exp[ind[-1]:len(self.exp)+1] and ind[-1]+2<len(self.exp)-1:
ind.append(self.exp.find('**',ind[-1],len(self.exp))+2)
order=0
for i in ind:
if i>order:
order=int(self.exp[i])
elif '*x' in self.exp:
order=1
elif 'x' in self.exp:
order=1
else:
order=0
except:
if 'x' in self.exp:
order=10
else:
order=0
print('order='+str(order))
######################################
### Get roots ###
xtol=0.1/order
ytol=0.1*order
min_abs_y=10**5
i=0
try:
while min_abs_y>ytol:
# Initialize values
x1=order*2.1+1.5
x2=x1+xtol
x3=x1
x4=x3-xtol
xlist=[x1,x2,x3,x4]
roots=[]
minima=[]
maxima=[]
j=0
while j<10**4/(xtol):
# Evaluate ylist
ylist=[eval(self.exp) for x in xlist]
# Calculate roots
for y_ind in range(0,len(ylist)):
if ylist[y_ind]==0:
roots.append(xlist[y_ind])
if ylist[0]*ylist[1]<0:
roots.append((xlist[0]+xlist[1])/2)
if ylist[2]*ylist[3]<0:
roots.append((xlist[2]+xlist[3])/2)
# Determine if minima or maxima
y_diff_1=ylist[1]-ylist[0]
y_diff_2=ylist[3]-ylist[2]
if j>1:
if y_diff_1_old<0 and y_diff_1>0:
minima.append(xlist[0])
elif y_diff_1_old>0 and y_diff_1<0:
maxima.append(xlist[0])
if y_diff_2_old<0 and y_diff_2>0:
minima.append(xlist[2])
elif y_diff_2_old>0 and y_diff_2<0:
maxima.append(xlist[2])
y_diff_1_old=y_diff_1
y_diff_2_old=y_diff_2
# Move X brackets
xlist[0]=xlist[1]
xlist[1]=xlist[0]+xtol
xlist[2]=xlist[3]
xlist[3]=xlist[2]-xtol
# Update count
j=j+1
i=i+1
# Check for roots within ytol of zero
y=[eval(self.exp) for x in roots]
abs_y=[-1*x if x<0 else x for x in y]
min_abs_y=abs_y[0]
for k in range(1,len(abs_y)):
if abs_y[k]<min_abs_y:
min_abs_y=abs_y[k]
xtol=xtol/order
except Exception as err:
print(err)
print("Exception at iteration = {}".format(j))
print("Exception at xlist = {}".format(xlist))
print("Exception at ylist = {}".format(ylist))
######################################
### Check Delta ###
delta=[0-eval(self.exp) for x in roots]
######################################
### print ###
self.order=order
self.roots=roots
self.delta=delta
self.minima=minima
self.maxima=maxima
######################################
def get_order(self):
return self.order
def get_roots(self):
return self.roots
def get_delta(self):
return self.delta
def get_minima(self):
return self.minima
def get_maxima(self):
return self.maxima |
d8a8a3a1caed51d397ab4ffe6e23f6ba7e1092c4 | arcsingh/DG_Work | /replaceText.py | 869 | 4.0625 | 4 |
# Script to read a file and replace the _ with spaces
#Step1: Open the file to be modified and store the content in memory
#Step2: Replace the text with ' ' using the replace function
#Step3: Write the replaced text back to a new file. Note: Can be written to the same file as well
#Step4: We can also provide the filepath from any location in the script
#Function to replace text
def replaceText(input_filename, output_filename):
#Read the input file
s = open(input_filename).read()
#Replace _ with ' '
s = s.replace('_', ' ')
#Open the Output file and write the replaced text
f = open(output_filename, 'w')
f.write(s)
#Close the output file
f.close()
print "Convertion Successfully completed - " +output_filename
#Function Ends
#Convert File
replaceText("neg.wn", "neg_update.wn")
replaceText("pos.wn", "pos_update.wn")
|
9b61d09c177e304bfde25bc6b39050387d86a241 | jatin711-debug/PythonProjectVirusdetectorTkinter | /menu.py | 3,533 | 4.0625 | 4 | from tkinter import *
from tkinter.messagebox import *
txt=""" This project consists of scanning of virus in the following:
1: Domain :-When referring to an Internet address or name, a domain or domain name is the location of a website.\n For example, the domain name "google.com" points to the IP address "216.58.216.164".
::> Our project can detect if the domain is infected with virus and not,It can also tell about the details of domain
2: Port :- A port is a virtual point where network connections start and end. Ports are software-based and managed by a computer's operating system. Each port is associated with a specific process or service. Ports allow computers to easily differentiate between different kinds of traffic: emails go to a different port than webpages, for instance, even though both reach a computer over the same Internet connection.
::> Project can ensure if a dangerous port is open or not
3: Url :- URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.
::> Our project supports url scanning
4: files :- A file is an object on a computer that stores data, information, settings, or commands used with a computer program. In a GUI (graphical user interface), such as Microsoft Windows, files display as icons that relate to the program that opens the file. For example, all PDF icons appear the same and open in Adobe Acrobat or the reader associated with PDF files.
::> files scanning is supported
"""
def st():
result.insert(1.0,txt)
def quitApp():
d=askyesno("Want To Quit","Are You Sure You Want to Quit")
if d:
win.destroy()
def domainwin():
win.destroy()
import domainwin
def portwin():
win.destroy()
import portwin
def urlwin():
win.destroy()
import urlwin
def task():
win.destroy()
import files
clr="White"
clr1="black"
clr2="red"
win=Tk()
win.title("Virus Scanner")
win.wm_iconbitmap("form.ico")
win.geometry("800x400+200+100") #WxH+x+y
win.config(bg=clr1)
#frames
frame1=Frame(win,bg=clr,height=50,padx=70,pady=10)
frame1.pack(side=TOP,fill="both")
frame2=Frame(win,bg=clr,height=350)
frame2.pack(side=TOP,fill="both")
scroll=Scrollbar(frame2)
scroll.pack(side=RIGHT,fill=Y)
b1=Button(frame1,text="Domain Who is",bg=clr,width=16,pady=5,font='Serif 10',command=domainwin)
b1.pack(side=LEFT,pady=7)
b2=Button(frame1,text="Port Scanning",bg=clr,width=16,pady=5,font='Serif 10',command=portwin)
b2.pack(side=LEFT,pady=7)
b3=Button(frame1,text="URL Scanning",bg=clr,width=16,pady=5,font='Serif 10',command=urlwin)
b3.pack(side=LEFT,pady=7)
b4=Button(frame1,text="Files",bg=clr,width=16,pady=5,font='Serif 10',command=task)
b4.pack(side=LEFT,pady=7)
b5=Button(frame1,text="Quit",bg=clr,width=8,pady=5,font='Serif 10',command=quitApp)
b5.pack(side=LEFT,pady=7)
Label(frame2,text="Welcome",bg=clr,fg="purple",font="georgia 20").pack(pady=10)
result=Text(frame2,bg=clr1,fg=clr,font='Serif 10',yscrollcommand=scroll.set,width=120,padx=10,pady=10)
result.pack(fill=Y)
scroll.config(command=result.yview)
st()
win.mainloop()
|
6909505f9fbd960a8cdfb24c294e006a7b695261 | bbaja42/projectEuler | /src/problem15.py | 714 | 3.625 | 4 | '''
Starting in the top left corner of a 2x2 grid,
there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 20x20 grid?
'''
from math import factorial
def find_routes():
'''
Since backtracking is not allowed,
it is only possible to go right and bottom.
It will take 40 steps to cover whole grid.
20 down and 20 right.
Simple combinatorics
'''
size = 20
return factorial(size * 2) // (factorial(size) * factorial(size))
print ("Number of routes is {}".format(find_routes()))
import timeit
t = timeit.Timer("find_routes", "from __main__ import find_routes")
print ("Average running time: {} seconds".format(t.timeit(1000)))
|
e1139905c3f17bd9e16a51a69853a0923160c84f | bbaja42/projectEuler | /src/problem14.py | 1,496 | 4.15625 | 4 | '''
The following iterative sequence is defined for the set of positive integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 40 20 10 5 16 8 4 2 1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms.
Although it has not been proved yet (Collatz Problem),
it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
'''
#Contains maximum chain length for each found origin number
cache_numbers = {}
def find_start_number():
'''
Find start number with largest chain
Uses cache for found numbers as an optimization
'''
max_value = 1
index = 0
for i in range(2, 1000000):
cache_numbers[i] = calc_chain(i)
if cache_numbers[i] > max_value:
max_value = cache_numbers[i]
index = i
return index
def calc_chain(n):
if n in cache_numbers:
return cache_numbers[n]
if n == 1:
return 1
result = 1
if (n % 2 == 0):
result += calc_chain(n // 2)
else:
result += calc_chain(3 * n + 1)
return result
print ("Chain is {}".format(find_start_number()))
import timeit
t = timeit.Timer("find_start_number", "from __main__ import find_start_number")
print ("Average running time: {} seconds".format(t.timeit(1000)))
|
20cd326aa3fb04948413d015208658a6eb392437 | nikshrimali/TSAI_END | /S8_HandsOn2/snippets.py | 20,867 | 4.0625 | 4 | # Write a function that adds 2 iterables a and b such that a is even and b is odd
def add_even_odd_list(l1:list,l2:list)-> list:
return [a+b for a,b in zip(l1,l2) if a%2==0 and b%2!=0]
# Write a function that strips every vowel from a string provided
def strip_vowels(input_str:str)->str:
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' ]
return ''.join(list(filter(lambda x: x not in vowels, input_str)))
# write a function that acts like a ReLU function for a 1D array
def relu_list(input_list:list)->list:
return [(lambda x: x if x >= 0 else 0)(x) for x in input_list]
# Write a function that generates Factorial of number
def factorial(n):
if n == 0 or n ==1:
return 1
else:
return n*factorial(n-1)
# Write a function that returns length of the list
def list_length(l):
return len(l)
# Write a function that sorts list of numbers and returns top element
def biggest_no(l:list)->int:
sorted(l)
# Write a function to print a string by repeating it n times
def print_repeatnstring(text:str, n:int)-> str:
return text*n
# Write a function to merge two lists element wise
def merge_lists(l1:list, l2:list):
return list(zip(l1,l2))
# Write a function to merge two lists element wise
def merge_lists(l1:list, l2:list):
return list(zip(l1,l2))
# Write a function to append two lists
def append_lists(l1:list, l2:list)->list:
return l1.extend(l2)
# Write a function to return reverse of a list
def reverse_list(l1:list)->list:
return l1[::-1]
# Write a function to adds two lists element wise
def adds_listelements(l1:list, l2:list):
return [i+j for i, j in zip(l1,l2)]
# Write a function to Subtracts two lists element wise
def sub_listelements(l1:list, l2:list):
return [i-j for i, j in zip(l1,l2)]
# Write a function to adds two lists element wise only if numbers are even
def adds_listevenelements(l1:list, l2:list):
return [i+j for i, j in zip(l1,l2) if i*j%2 == 0]
# Write a function to multiplies two lists element wise only if numbers are odd
def adds_listoddelements(l1:list, l2:list):
return [i*j for i, j in zip(l1,l2) if i*j%2 == 1]
# Write a function that returns list of elements with n power to elements of list
def n_power(l1:list, power:int)->list:
return [i**power for i in l1]
# Write a function that generates fibbonacci series
def Fibonacci(n:int)-> int:
if n==1:
fibonacci = 0
elif n==2:
fibonacci = 1
else:
fibonacci = Fibonacci(n-1) + Fibonacci(n-2)
return fibonacci
# Write a function that returns sine value of the input
def sin(x:float) -> float:
import math
return math.sin(x)
# Write a function that returns derivative of sine value of the input
def derivative_sin(x:float)-> float:
import math
return math.cos(x)
# Write a function that returns tan value of the input
def tan(x:float) -> float:
import math
return math.tan(x)
# Write a function that returns derivative of tan value of the input
def derivative_tan(x:float)-> float:
import math
return (1/math.cos(x))**2
# Write a function that returns cosine value of the input
def cos(x:float) -> float:
import math
return math.cos(x)
# Write a function that returns cosine value of the input
def derivative_cos(x:float)-> float:
import math
return -(math.sin(x))
# Write a function that returns the exponential value of the input
def exp(x) -> float:
import math
return math.exp(x)
# Write a function that returns Gets the derivative of exponential of x
def derivative_exp(x:float) -> float:
import math
return math.exp(x)
# Write a function that returns log of a function
def log(x:float)->float:
import math
return math.log(x)
# Write a function that returns derivative of log of a function
def derivative_log(x:float)->float:
return (1/x)
# Write a function that returns relu value of the input
def relu(x:float) -> float:
x = 0 if x < 0 else x
return x
# Write a function that returns derivative derivative relu value of the input
def derivative_relu(x:float) -> float:
x = 1 if x > 0 else 0
return x
# Write a function that returns runs a garbage collector
def clear_memory():
import gc
gc.collect()
# Write a function that calculates the average time taken to perform any transaction by Function fn averaging the total time taken for transaction over Repetations
def time_it(fn, *args, repetitons= 1, **kwargs):
import time
total_time = []
for _ in range(repetitons):
start_time = time.perf_counter()
fn(*args,**kwargs)
end_time = time.perf_counter()
ins_time = end_time - start_time
total_time.append(ins_time)
return sum(total_time)/len(total_time)
# Write a function to identify if value is present inside a dictionary or not
def check_value(d:dict, value)->bool:
return any(v == value for v in dict.values())
# Write a function to identify to count no of instances of a value inside a dictionary
def count_value(d:dict, value)->bool:
return list(v == value for v in dict.values()).count(True)
# Write a function to identify if value is present inside a list or not
def check_listvalue(l:list, value)->bool:
return value in l
# Write a function to identify if value is present inside a tuple or not
def check_tuplevalue(l:tuple, value)->bool:
return value in l
# Write a function that returns lowercase string
def str_lowercase(s:str):
return s.lower()
# Write a function that returns uppercase string
def str_uppercase(s:str):
return s.upper()
# Write a function that removes all special characters
def clean_str(s):
import re
return re.sub('[^A-Za-z0-9]+', '', s)
# Write a function that returns a list sorted ascending
def ascending_sort(l:list):
sorted(l, reverse=False)
# Write a function that returns a list sorted descending
def descending_sort(l:list):
sorted(l, reverse=True)
# Write a function that returns a dictionary sorted descending by its values
def descending_dict_valuesort(d:dict):
return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[1])}
# Write a function that returns a dictionary sorted ascending by its values
def ascending_dict_valuesort(d:dict):
return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1])}
# Write a function that returns a dictionary sorted descending by its keys
def descending_dict_keysort(d:dict):
return {key: val for key, val in sorted(d.items(), reverse=True, key = lambda ele: ele[0])}
# Write a function that returns a dictionary sorted ascending by its keys
def ascending_dict_keysort(d:dict):
return {key: val for key, val in sorted(d.items(), key = lambda ele: ele[0])}
# Write a function that returns a replace values in string with values provided
def replace_values(s:str, old, new)->str:
s.replace(old, new)
# Write a function that joins elements of list
def join_elements(l:list)-> str:
return (''.join(str(l)))
# Write a function that splits the elements of string
def split_elements(s:str, seperator)-> list:
return s.split(seperator)
# Write a function that returns sum of all elements in the list
def sum_elements(l:list):
return sum(l)
# Write a function that returns sum of all odd elements in the list
def sum_even_elements(l:list):
return sum([i for i in l if i%2==0])
# Write a function that returns sum of all odd elements in the list
def sum_odd_elements(l:list):
return sum([i for i in l if i%2==1])
# write a python function to count number of times a function is called
def counter(fn):
count = 0
def inner(*args, **kwargs):
nonlocal count
count += 1
print(f'Function {fn.__name__} was called {count} times.')
return fn(*"args, **kwargs)
return inner
# write a python function to remove duplicate items from the list
def remove_duplicatesinlist(lst):
return len(lst) == len(set(lst))
# write a python decorator function to find how much time user given function takes to execute
def timed(fn):
from time import perf_counter
from functools import wraps
@wraps(fn)
def inner(*args, **kwargs):
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
elapsed = end - start
args_ = [str(a) for a in args]
kwargs_ = ['{0}={1}'.format(k, v) for k, v in kwargs.items()]
all_args = args_ + kwargs_
args_str = ','.join(all_args) # now it is comma delimited
print(f'{fn.__name__}({args_str}) took {elapsed} seconds')
return result
# inner = wraps(fn)(inner)
return inner
# write a python program to add and print two user defined list using map
input_string = input("Enter a list element separated by space ")
list1 = input_string.split()
input_string = input("Enter a list element separated by space ")
list2 = input_string.split()
list1 = [int(i) for i in list1]
list2 = [int(i) for i in list2]
result = map(lambda x, y: x + y, list1, list2)
print(list(result))
# write a python function to convert list of strings to list of integers
def stringlist_to_intlist(sList):
return(list(map(int, sList)))
# write a python function to map multiple lists using zip
def map_values(*args):
return set(zip(*args))
# write a generator function in python to generate infinite square of numbers using yield
def nextSquare():
i = 1;
# An Infinite loop to generate squares
while True:
yield i*i
i += 1
# write a python generator function for generating Fibonacci Numbers
def fib(limit):
# Initialize first two Fibonacci Numbers
a, b = 0, 1
# One by one yield next Fibonacci Number
while a < limit:
yield a
a, b = b, a + b
# write a python program which takes user input tuple and prints length of each tuple element
userInput = input("Enter a tuple:")
x = map(lambda x:len(x), tuple(x.strip() for x in userInput.split(',')))
print(list(x))
# write a python function using list comprehension to find even numbers in a list
def find_evennumbers(input_list):
list_using_comp = [var for var in input_list if var % 2 == 0]
return list_using_comp
# write a python function to return dictionary of two lists using zip
def dict_using_comp(list1, list2):
dict_using_comp = {key:value for (key, value) in zip(list1, list2)}
return dict_using_comp
#Write a function to get list of profanity words from Google profanity URL
def profanitytextfile():
url = "https://github.com/RobertJGabriel/Google-profanity-words/blob/master/list.txt"
html = urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")
textlist = []
table = soup.find('table')
trs = table.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
for td in tds:
textlist.append(td.text)
return textlist
#write a python program to find the biggest character in a string
bigChar = lambda word: reduce(lambda x,y: x if ord(x) > ord(y) else y, word)
#write a python function to sort list using heapq
def heapsort(iterable):
from heapq import heappush, heappop
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]
# write a python function to return first n items of the iterable as a list
def take(n, iterable):
import itertools
return list(itertools.islice(iterable, n))
# write a python function to prepend a single value in front of an iterator
def prepend(value, iterator):
import itertools
return itertools.chain([value], iterator)
# write a python function to return an iterator over the last n items
def tail(n, iterable):
from collections import deque
return iter(deque(iterable, maxlen=n))
# write a python function to advance the iterator n-steps ahead
def consume(iterator, n=None):
import itertools
from collections import deque
"Advance the iterator n-steps ahead. If n is None, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(itertools.islice(iterator, n, n), None)
# write a python function to return nth item or a default value
def nth(iterable, n, default=None):
from itertools import islice
return next(islice(iterable, n, None), default)
# write a python function to check whether all elements are equal to each other
def all_equal(iterable):
from itertools import groupby
g = groupby(iterable)
return next(g, True) and not next(g, False)
# write a python function to count how many times the predicate is true
def quantify(iterable, pred=bool):
return sum(map(pred, iterable))
# write a python function to emulate the behavior of built-in map() function
def pad_none(iterable):
"""Returns the sequence elements and then returns None indefinitely.
Useful for emulating the behavior of the built-in map() function.
"""
from itertools import chain, repeat
return chain(iterable, repeat(None))
# write a python function to return the sequence elements n times
def ncycles(iterable, n):
from itertools import chain, repeat
return chain.from_iterable(repeat(tuple(iterable), n))
# write a python function to return the dot product of two vectors
def dotproduct(vec1, vec2):
return sum(map(operator.mul, vec1, vec2))
# write a python function to flatten one level of nesting
def flatten(list_of_lists):
from itertools import chain
return chain.from_iterable(list_of_lists)
# write a python function to repeat calls to function with specified arguments
def repeatfunc(func, times=None, *args):
from itertools import starmap, repeat
if times is None:
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
# write a python function to convert iterable to pairwise iterable
def pairwise(iterable):
from itertools import tee
a, b = tee(iterable)
next(b, None)
return zip(a, b)
# write a python function to collect data into fixed-length chunks or blocks
def grouper(iterable, n, fillvalue=None):
from itertools import zip_longest
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
# write a python program to create round robin algorithm: "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
def roundrobin(*iterables):
from itertools import islice, cycle
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
# write a python function to use a predicate and return entries particition into false entries and true entries
def partition(pred, iterable):
from itertools import filterfalse, tee
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
# write a python function to return powerset of iterable
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
from itertools import chain, combinations
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
list(powerset([1,2,3]))
# write a python function to list all unique elements, preserving order
def unique_everseen(iterable, key=None):
from itertools import filterfalse
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
# write a python function to list unique elements, preserving order remembering only the element just seen."
def unique_justseen(iterable, key=None):
import operator
from itertools import groupby
# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
# unique_justseen('ABBCcAD', str.lower) --> A B C A D
return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
# write a python function to call a function repeatedly until an exception is raised.
def iter_except(func, exception, first=None):
"""Converts a call-until-exception interface to an iterator interface.
Like builtins.iter(func, sentinel) but uses an exception instead
of a sentinel to end the loop.
Examples:
iter_except(s.pop, KeyError) # non-blocking set iterator
"""
try:
if first is not None:
yield first() # For database APIs needing an initial cast to db.first()
while True:
yield func()
except exception:
pass
# write a python function to return random selection from itertools.product(*args, **kwds)
def random_product(*args, repeat=1):
import random
pools = [tuple(pool) for pool in args] * repeat
return tuple(map(random.choice, pools))
# write a python function to return random selection from itertools.permutations(iterable, r)
def random_permutation(iterable, r=None):
import random
pool = tuple(iterable)
r = len(pool) if r is None else r
return tuple(random.sample(pool, r))
# write a python function to random select from itertools.combinations(iterable, r)
def random_combination(iterable, r):
import random
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.sample(range(n), r))
return tuple(pool[i] for i in indices)
# write a python function to perform random selection from itertools.combinations_with_replacement(iterable, r)
def random_combination_with_replacement(iterable, r):
import random
pool = tuple(iterable)
n = len(pool)
indices = sorted(random.choices(range(n), k=r))
return tuple(pool[i] for i in indices)
# write a python function to locate the leftmost value exactly equal to x
def index(a, x):
from bisect import bisect_left
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
# write a python function to locate the rightmost value less than x
def find_lt(a, x):
from bisect import bisect_left
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
# write a python function to find rightmost value less than or equal to x
def find_le(a, x):
from bisect import bisect_right
i = bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
# write a python function to find leftmost value greater than x
def find_gt(a, x):
from bisect import bisect_right
i = bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
# write a python function to find leftmost item greater than or equal to x
def find_ge(a, x):
from bisect import bisect_left
i = bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError
# write a python function to map a numeric lookup using bisect
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
from bisect import bisect
i = bisect(breakpoints, score)
return grades[i]
# write a regex pattern in python to print all adverbs and their positions in user input text
import re
text = input("Enter a string: ")
for m in re.finditer(r"\w+ly", text):
print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
# write a python function to read a CSV file and print its content
def read_csv(filename):
import csv
with open(filename, newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# write a python snippet to convert list into indexed tuple
test_list = [4, 5, 8, 9, 10]
list(zip(range(len(test_list)), test_list))
# write a python function to split word into chars
def split(word):
return [char for char in word]
# write a python function to pickle data to a file
def pickle_data(data, pickle_file):
import pickle
with open(pickle_file, 'wb') as f:
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
return None
# write a python function to load pickle data from a file
def load_pickle_data(pickle_file):
import pickle
with open(pickle_file, 'rb') as f:
data = pickle.load(f)
return data |
d38ca5318a0687d16c49517fcaf6cac030cc1601 | sys-ryan/python-django-fullstack-bootcamp | /10. Python Level One/string.py | 598 | 4.40625 | 4 | # STRINGS
mystring = 'abcdefg'
print(mystring)
print(mystring[0])
# Slicing
print(mystring[:3])
print(mystring[2:5])
print(mystring[:])
print(mystring[::2])
# upper
print(mystring.upper())
# capitalize
print(mystring.capitalize())
# split
mystring = 'Hello World'
x = mystring.split()
print(x)
mystring = 'Hello/World'
x = mystring.split('/')
print(x)
# Print Formatting
x = "Insert another string here: {}".format("<INSERTED STRING>")
print(x)
x = "Item one : {} \nItem Two : {}".format("dog", "cat")
print(x)
x = "Item one : {y} \nItem Two : {x}".format(x = "dog", y = "cat")
print(x)
|
062755f73d0fc0ae3217f5db61e43ed18b53f468 | guyeshet/keras-accent-trainer | /data_loader/csv_parser.py | 1,567 | 3.5625 | 4 | from sklearn.model_selection import train_test_split
from keras import utils
def split_people(df, test_size=0.2):
'''
Create train test split of DataFrame
:param df (DataFrame): Pandas DataFrame of audio files to be split
:param test_size (float): Percentage of total files to be split into test
:return X_train, X_test, y_train, y_test (tuple): Xs are list of df['language_num'] and Ys are df['native_language']
'''
return train_test_split(df['language_num'],
df['new_native_language'],
test_size=test_size,
stratify=df['new_native_language'],
random_state=1234)
def to_categorical(y):
'''
Converts list of languages into a binary class matrix
:param y (list): list of languages
:return (numpy array): binary class matrix
'''
lang_dict = {"english": 0,
"other": 1}
# for index, language in enumerate(set(y)):
# lang_dict[language] = index
# go over all the result and convert the name of the language to its index
# because we have only two classes, it's either english or not
# y = list(map(lambda x: lang_dict[x] if x == "english" else lang_dict["other"], y))
y = list(map(lambda x: lang_dict["english"] if x == "english" else lang_dict["other"], y))
return utils.to_categorical(y, len(lang_dict))
def find_classes(y):
lang_dict = {}
for index, language in enumerate(set(y)):
lang_dict[language] = index
return lang_dict
|
ed62a80a5374b9115293376b791546fcd5c817c7 | sudoghut/Leetcode-notes | /21. Merge Two Sorted Lists.py | 1,010 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
output = []
if hasattr(l1,"next"):
while l1.next!=None:
output.append(l1.val)
l1 = l1.next
output.append(l1.val)
if hasattr(l2,"next"):
while l2.next!=None:
output.append(l2.val)
l2 = l2.next
output.append(l2.val)
token = 0
while token==0:
token =1
for i in range(len(output)-1):
if output[i]>output[i+1]:
temp = output[i]
output[i] = output[i+1]
output[i+1] = temp
token*=0
else:
token*=1
return output |
9b2cef3fdc7aef39811b0c517652bae23dc1066a | sudoghut/Leetcode-notes | /53. Maximum Subarray.py | 539 | 3.546875 | 4 | class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sumList = []
ans = nums[0]
sumNum = 0
for i in nums:
print("i:%d"%i)
sumNum+=i
print("sumNumi:%d"%sumNum)
print("ans:%d"%ans)
ans = max(sumNum, ans)
print("Final Ans:%d"%ans)
print()
sumNum = max(sumNum, 0)
return ans
a = Solution()
print(a.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
|
dee3f47d3b1befb9835946b10a6b96a711383dbd | drednout5786/Python-UII | /hwp_5/divisor_master.py | 1,945 | 4.125 | 4 | def is_prime(a):
"""
:param a: число от 1 до 1000
:return: простое или не простое число (True/False)
"""
if a % 2 == 0:
return a == 2
d = 3
while d * d <= a and a % d != 0:
d += 2
return d * d > a
def dividers_list(a):
"""
:param a: число от 1 до 1000
:return: список делителей числа
"""
div_list = []
for i in range(1, a + 1):
if a % i == 0: div_list.append(i)
return div_list
def simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: список простых делителей числа
"""
d_list = dividers_list(a)
smpl_div_list = []
l = len(d_list)
for i in range(l):
if is_prime(d_list[i]):
smpl_div_list.append(d_list[i])
return smpl_div_list
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a))
def max_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой делитель (не обязательно простой) числа
"""
return max(dividers_list(a))
def canonical_decomposition(a):
"""
:param a: число от 1 до 1000
:return: каноническое разложение числа на простые множители
"""
a_begin = a
sd = simple_dividers(a)
lsd = len(sd)
# print("sd = ", sd)
con_dec = []
# print("con_dec = ", con_dec)
for i in range(1, lsd):
while a_begin % sd[i] == 0:
con_dec.append(sd[i])
a_begin = a_begin/sd[i]
lcd = len(con_dec)
con_dec_txt = str(con_dec[0])
for i in range(1, lcd):
con_dec_txt = "{}*{}".format(con_dec_txt, con_dec[i])
return con_dec_txt |
c0f1315caa2d5eb3f1a22a49acc1dc419e3c2069 | yuzhucu/AlgoBacktest | /market/interfaces/orderrouter.py | 895 | 3.609375 | 4 | from abc import ABCMeta, abstractmethod
class OrderbookException(Exception):
pass
class OrderRouter(object):
__metaclass__ = ABCMeta
def __init__(self):
self.orderStatusObservers = []
self.positionObservers = []
@abstractmethod
def place_order(self, order):
# send new order to market
pass
@abstractmethod
def modify_order(self, order):
# modify order on market
pass
@abstractmethod
def cancel_order(self, order):
# cancel order on market
pass
@abstractmethod
def modify_position(self, position):
pass
@abstractmethod
def close_position(self, position):
pass
def addOrderStatusObserver(self, observer):
self.orderStatusObservers.append(observer)
def addPositionObserver(self, observer):
self.positionObservers.append(observer)
|
62b5cf7cf844601a99c1ecb0301708f34fe4b02d | athina-rm/function-vningar | /functionövningar/fuctionÖvningar/fuctionÖvningar/module5.py | 476 | 3.8125 | 4 | # Skapa en metod som du döper till HittaLangstaOrdet. Metoden skall ta som inparameter en array
#med strängar. Metoden skall loopa igenom arrayen och returnera det längsta ordet.
def findLongestWord(a):
long=a[0]
for i in a:
if len(long)<=len(a[i]) :
long=a[i]
return long
wordArray=[]
count=int(input("no.of words:"))
for i in range (0,count):
wordArray.append(input("mata in ord:"))
print (findLongestWord(wordArray))
|
1ce923e11d53f1795a578c91accfc71a09b8e58e | Mahedi522/Python_basic | /26_Array.py | 626 | 3.625 | 4 | from array import *
val = array('i', [5, 4, -6, 3, 7, 4])
print(val)
print(val.buffer_info())
print(val.typecode)
val.reverse()
print(val)
val.append(12)
print(val)
print(val[0])
for i in range(len(val)): # or for i in range val:
print(val[i], end=" ")
char = array('u', ['a', 'f', 'r', 'g'])
print(char)
for e in char:
print(e)
newVal = array(val.typecode, [a for a in val])
for i in newVal:
print(i)
newVal = array(val.typecode, [a*a for a in val])
for i in newVal:
print(i)
newVal = array(val.typecode, [a**3 for a in val])
i = 0
while i < len(newVal):
print(newVal[i], end=",")
i += 1
|
4ca2727580ddedb855151586875d1c9058b75518 | Mahedi522/Python_basic | /70_Bubble_Sort.py | 303 | 3.828125 | 4 | def sort(list):
temp = 0
for i in range(len(list)-1, 0, -1):
for j in range(i):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
li = [34, 45, 57, 32, 87, 34, 9, 4, 23]
print(li)
sort(li)
print(li)
|
13b0381f260fbb5ad663ac5eff67734f5117e1c4 | Mahedi522/Python_basic | /16MathFunction.py | 355 | 4.0625 | 4 | import math
x=math.sqrt(25)
print(x)
x=math.sqrt(15)
print(x)
print(math.floor(2.9))
print(math.ceil(2.9))
x=3**2 #power
print(x)
print(math.pow(3,2)) #another way to represent power
print(math.pi)
print(math.e)
import math as m #concept of alise
print(m.sqrt(16))
from math import sqrt,pow
print(pow(4,5))
print(sqrt(25))
x=pow(2,5)
print(x)
|
7bea960e37995bb7a8eba9b9a4f8d52345e6deab | Mahedi522/Python_basic | /37_List_Fuction.py | 312 | 3.84375 | 4 | lst = [23, 33, 45, 56, 6, 76, 34, 345, 99]
def count(lst):
even = 0
odd = 0
for i in lst:
if i % 2 == 0:
even += 1
elif i % 2 != 0:
odd += 1
return even, odd
even, odd = count(lst)
print(even)
print(odd)
print("even: {} and odd: {}".format(even, odd))
|
fc846895589cb0b3d0227622ca53c4c6a62b61bc | Mahedi522/Python_basic | /strip_function.py | 384 | 4.34375 | 4 | # Python3 program to demonstrate the use of
# strip() method
string = """ geeks for geeks """
# prints the string without stripping
print(string)
# prints the string by removing leading and trailing whitespaces
print(string.strip())
# prints the string by removing geeks
print(string.strip(' geeks'))
a = list(map(int, input().rstrip().split()))
print(a)
print(type(a[1]))
|
d1b87c248a766c8704c7b26712b2306ce213ee01 | Mahedi522/Python_basic | /hackerrank_Game_of_Stones.py | 248 | 3.5625 | 4 | def gameOfStones(num):
a = "First"
b = "Second"
if num % 7 < 2:
return b
else:
return a
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
result = gameOfStones(n)
print(result)
|
ad27d21501d4b59c69778bd19341a5c202c26324 | Mahedi522/Python_basic | /18input.py | 141 | 4 | 4 | x = int(input("Enter 1st number: "))
y = int(input("Enter 2nd number: "))
# initially input function takes input as string
z = x+y
print(z)
|
21309acc49d40ee588913a574d7b163d1b5bb3e5 | Mahedi522/Python_basic | /hackerrank_Apple and Orange.py | 362 | 3.640625 | 4 | def countApplesAndOranges(s, t, a, b, apples, oranges):
x = 0
y = 0
for i in apples:
if s <= (a+i) <= t:
x += 1
for i in oranges:
if s <= (b + i) <= t:
y += 1
print(x)
print(y)
s = 7
t = 10
a = 4
b = 12
apples = [2, 3, -4]
oranges = [3, -2, -4]
countApplesAndOranges(s, t, a, b, apples, oranges) |
4bddf0f0af9fe99816d0ea840424a1f12469aed5 | Mahedi522/Python_basic | /38_Fibonacci.py | 235 | 3.8125 | 4 | def fib(x):
first, second = 0, 1
for i in range(x):
if i <= 1:
print(i)
else:
fibo = first + second
first = second
second = fibo
print(fibo)
fib(3)
|
fc4968b89fedd1793b2a9db3320529025ce8e479 | Mahedi522/Python_basic | /31_multiDimentional_array_matrix.py | 426 | 4 | 4 | from numpy import *
arr = array([
[1, 2, 3, 4, 5, 6],
[4, 5, 6, 7, 8, 9]
])
print(arr)
print(arr.dtype)
print(arr.ndim)
print(arr.shape)
print(arr.size)
arr2 = arr.flatten() # 2 dimension to 1 dimension
print(arr2)
print("Reshape")
arr3 = arr2.reshape(3,4) # 1 dimension to 3 dimension
print(arr3)
print("2 2 dimensional array in a 3d array")
arr4 = arr2.reshape(2, 2, 3) # 1 dimension to 3 dimension
print(arr4) |
155d2e79918526e4e73e3b80a5675bb7403bda10 | jiataoxiang/Chopsticks-and-subtractSquare | /new_version.py | 9,094 | 3.625 | 4 |
class Current_state():
def __init__(self, movement):
self.movement = movement
class Chopsticks_state(Current_state):
def __init__(self, movement, left1,left2,right1,right2):
"""
Create a new Chopsticks self
"""
Current_state.__init__(self,movement)
self.left1 = left1 % 5
self.left2 = left2 % 5
self.right1 = right1 % 5
self.right2 = right2 % 5
def __str__(self):
"""
Return a user-friendly string representation of Chopsticks self
"""
return "Player1: {}-{} Player2: {}-{}".format(self.left1,self.right1,
self.left2,self.right2)
def is_valid_move(self, move_to_make):
"""
return True if the move is valid, else return False
"""
if move_to_make == None:
return False
elif self.left1 == 0:
if move_to_make not in ["rl","rr"]:
return False
if self.left2 == 0:
if move_to_make != "rr":
return False
elif self.right1 == 0:
if move_to_make not in ["ll","lr"]:
return False
if self.right2 == 0:
if move_to_make != "ll":
return False
elif self.left2 == 0:
if move_to_make not in ["rr","lr"]:
return False
if self.right1 == 0:
if move_to_make != "lr":
return False
elif self.right2 == 0:
if move_to_make not in ["ll","rl"]:
return False
if self.left1 == 0:
if move_to_make != "rl":
return False
elif move_to_make not in ["ll","lr","rl","rr"]:
return False
return True
def get_possible_moves(self):
"""
Return the possible moves
"""
if self.left1 == 0 and self.left2 * self.right2 != 0:
if self.movement % 2 == 1:
return ["rl","rr"]
else:
return ["lr","rr"]
elif self.right1 == 0 and self.left2 * self.right2 != 0:
if self.movement % 2 == 1:
return ["ll","lr"]
else:
return ["ll","rl"]
elif self.left2 == 0 and self.left1 * self.right1 != 0:
if self.movement % 2 == 1:
return ["lr","rr"]
else:
return ["rl","rr"]
elif self.right2 == 0 and self.left1 * self.right1 != 0:
if self.movement % 2 == 1:
return ["ll","lr"]
else:
return ["ll","rl"]
elif self.left1 == 0 and self.left2 == 0:
return ["rr"]
elif self.left1 == 0 and self.right2 == 0:
if self.movement % 2 == 1:
return ["rl"]
else:
return ["lr"]
elif self.right1 == 0 and self.left2 == 0:
if self.movement % 2 == 1:
return ["lr"]
else:
return ["rl"]
elif self.right1 == 0 and self.right2 == 0:
return ["ll"]
else:
return ["ll","lr","rl","rr"]
def get_current_player_name(self):
if self.movement % 2 == 1:
return "p1"
else:
return "p2"
def make_move(self, move_to_make):
if self.movement % 2 == 1:
if move_to_make == "ll":
return Chopsticks_state(self.movement+1, self.left1,
self.left2 + self.left1,
self.right1, self.right2)
if self.movement % 2 == 1:
if move_to_make == "lr":
return Chopsticks_state(self.movement+1, self.left1,
self.left2,self.right1,
self.right2 + self.left1)
if self.movement % 2 == 1:
if move_to_make == "rl":
return Chopsticks_state(self.movement+1, self.left1,
self.left2 + self.right1,
self.right1, self.right2)
if self.movement % 2 == 1:
if move_to_make == "rr":
return Chopsticks_state(self.movement+1, self.left1,
self.left2,self.right1,
self.right2 + self.right1)
if self.movement % 2 == 0:
if move_to_make == "ll":
return Chopsticks_state(self.movement+1,
self.left1 + self.left2,
self.left2,
self.right1, self.right2)
if self.movement % 2 == 0:
if move_to_make == "lr":
return Chopsticks_state(self.movement + 1, self.left1,
self.left2,
self.right1 + self.left2,
self.right2)
if self.movement % 2 == 0:
if move_to_make == "rl":
return Chopsticks_state(self.movement+1,self.left1,
self.left2,
self.right1 + self.left2, self.right2)
if self.movement % 2 == 0:
if move_to_make == "rr":
return Chopsticks_state(self.movement + 1, self.left1,
self.left2,
self.right1 + self.right2,
self.right2)
class Subtract_state(Current_state):
def __init__(self,number, movement):
Current_state.__init__(self,movement)
self.number = int(number)
def __str__(self):
return "value {}".format(int(self.number))
def is_valid_move(self, move_to_make):
"""
return True if the move is valid, else return False
"""
if move_to_make == None:
return False
elif move_to_make > self.number:
return False
elif int(move_to_make ** 0.5) != float(move_to_make) ** 0.5:
return False
return True
def get_possible_moves(self):
move = []
max_value = int(self.number ** 0.5)
for i in range(1, max_value+1):
move.append(i ** 2)
return move
def get_current_player_name(self):
if self.movement % 2 == 1:
return "p1"
else:
return "p2"
def make_move(self, move_to_make):
a = Subtract_state(self.number - move_to_make, self.movement + 1)
return a
class Game():
def __init__(self):
raise NotImplementedError
class Chopsticks(Game):
def __init__(self, is_p1_turn):
self.current_state = Chopsticks_state(1,1,1,1,1)
if not is_p1_turn:
self.current_state.movement = 2
def __str__(self):
pass
def is_over(self, current_state: Chopsticks_state):
return (current_state.left1 + current_state.right1 == 0 or
current_state.left2 + current_state.right2 == 0)
def str_to_move(self, a):
return a
def is_winner(self, player_name):
if (self.current_state.left1 + self.current_state.right1 == 0 or
self.current_state.left2 + self.current_state.right2 == 0):
if player_name == "p1" and self.current_state.movement % 2 == 0:
return True
elif player_name == "p2" and self.current_state.movement % 2 == 1:
return True
return False
def get_instructions(self):
"""
Return
"""
return """Players take turns adding the values of one of their hands to
one of their opponents(modulo 5). A hand with a total of 5
(or 0; 5 modulo 5) is considered 'dead'. The first player to hand 2
dead hands is the loser.
"""
class Subtract_square(Game):
def __init__(self, is_p1_turn):
self.start_number = input("choose the start_number: ")
self.current_state = Subtract_state(self.start_number, 1)
if not is_p1_turn:
self.current_state.movement = 2
def __str__(self):
pass
def is_over(self, current_state: Subtract_state):
return current_state.number == 0
def str_to_move(self, a):
return int(a)
def is_winner(self, player_name):
if self.current_state.number == 0:
if player_name == "p1" and self.current_state.movement % 2 == 0:
return True
elif player_name == "p2" and self.current_state.movement % 2 == 1:
return True
return False
def get_instructions(self):
return"""Players take turns subtracting square numbers from the
starting number. The winner is the person who subtract to 0.
"""
|
80a8695e8bb0f05afa36e377f5f2a9635dd99de7 | Justinnn07/python-works | /app.py | 1,885 | 4.09375 | 4 | # data types
justin = (str(13))
"""
str, float, type, variables, int
"""
# print(type(justin))
# operators
a = 3
b = 2
"""
addition, subtraction, division(print) normally
"""
# exponents, remainders , flow division
"""
print(a%b)
remainder
"""
"""
print(a**b)
exponents
"""
"""
print(a//b)
"""
# inline function
"""
a+= 1
print(a)
+ - * (expo + // )
"""
"""
mylist = ["hello", 25, "bye", 100.01]
# print(type(mylist))
print(mylist[3])
# str, type etc etc type must pe destructured in ordered to work with it
"""
# tuples
"""
mytups = ("ster", 1, "hello")
print(mytups)
"""
# sets
"""
mySet = {"abcd", 12, 12.9}
"""
# dictionaries
"""
myDict = {
"justin" : "varghese"
}
print(type(myDict))
"""
# if else
"""
x = 100
y = 200
z = 500
if x>y or z>y :
print("X is greater than y")
elif x==y:
print("X is equal to y")
else:
print("y is greater than x")
"""
# for loops
# colors = ["red", "blue", "green" ]
# for i in range(10):print(i)
"""
b = 6
for b in range(10):
print(b)
if b==6:
print("i am equal to 6")
else:
print("hiii")
"""
# While loops
"""
k = 120
while k > 100:
print("i am greater than 100")
k = k-5
print(" i am out")
"""
"""
kiran = " I am the header "
akshay = "I AM TEH HEADER"
# print(kiran.replace("a", "1233"))
yui = kiran.strip()
# print(yui)
print(akshay.lower())
"""
# print(6+6)
"""
kiran = 100
str = "I want {} mangoes"
print(str.format(kiran))
"""
"""
kiran = 900
vishakh = 600
akshay = 800
str = "Akshay {} Vishakh {} Kiran"
print(str.format(akshay, vishakh, kiran))
"""
"""
myList = [89, 99, 11]
myList1 = [99, 11, 12]
x = myList+myList1
x.sort()
print(x)
"""
### Append
"""
myList = [89, 99, 11]
myList1 = [99, 11, 12]
for x in myList1:
myList.append(x)
print(myList)
#hello world chod dia bhai tune
=======
"""
a = 2
print(type(a))
|
15e75d4c881460793d2dfa74c0f80c037b32d320 | ajivani/movie-trailer-website | /media.py | 716 | 3.515625 | 4 | import webbrowser
class Movie():
"""Class that is a container for movies. Used with fresh_tomatoes.py to generate an html page displaying movies. """
## def __init__():
## self.title = ""
## self.storyline = ""
## self.poster_image = ""
## self.trailer_youtube_url = ""
MOVIE_RATING = ["G", "PG", "PG-13", "R"]
#isntance methods all take self as first arg
def __init__(self, title, storyline, image_url, youtube_url):
self.title = title
self.story_line = storyline
self.poster_image = image_url
self.trailer_youtube_url = youtube_url
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
|
3398e9e6043a0fc5d300110d89b16f65085d9485 | Tillotama12/Tic-Tac-Toe | /day5.py | 660 | 4 | 4 |
#ACCESSING MEMBERS(VARIABLE AND METHOD) OF ONE CLASS INSIDE ANOTHER CLASS
'''
class Employee:
def __init__(self,name,age,sal,city): #constructor
self.name=name
self.age=age
self.sal=sal
self.city=city
def display(self): #instance
print(self.name)
print(self.age)
print(self.sal)
print(self.city)
class Manager:
def updateSalary(emp): #instead of emp we can also use self
emp.sal=emp.sal+1500
emp.name="sam"
emp.display()
e=Employee("raju",20,25000,"Bangolore")
Manager.updateSalary(e)
''''
#HAS-A relationship vs IS-A relationship
#HAS-A relationship
|
0b9e842cbeb52e819ecc2a10e135008f4380f8ed | monadplus/python-tutorial | /07-input-output.py | 1,748 | 4.34375 | 4 | #!/user/bin/env python3.7
# -*- coding: utf8 -*-
##### Fancier Output Formatting ####
year = 2016
f'The current year is {year}'
yes_votes = 1/3
'Percentage of votes: {:2.2%}'.format(yes_votes)
# You can convert any variable to string using:
# * repr(): read by the interpreter
# * str(): human-readable
s = "Hello, world."
str(s)
repr(s)
#### Formatted String Literals ####
name = 'arnau'
f'At least 10 chars: {name:10}' # adds whitespaces
# * !a ascii()
# * !s str()
# * !r repr()
f'My name is {name!r}'
#### The String format() Method ####
'{1} and {0}'.format('spam', 'eggs')
'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
# :d for decimal format
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
#### Reading and Writing Files #####
# By default is opened for text mode
#f = open('foo', 'x') # 'a' to append instead of erasing
# 'r+' reading/writing
# 'b' for binary mode
# 'x' new file and write
#f.write("Should not work")
#f.close()
with open('lore.txt', 'r') as f:
# print(f.readline())
# print(f.read(100))
# print(f.read())
for line in f:
print(line, end='')
f = open('lore.txt', 'rb+')
f.write(b'0123456789abcdef')
f.seek(5) # Go to the 6th byte in the file
f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
f.read(1)
#### JSON ####
import json
json.dumps([1, 'simple', 'list'])
f = open('foo.json', 'r+')
json.dump(['i', 'simple', 'list'], f)
f.seek(0) # rewind
x = json.load(f)
print(x)
f.close()
|
41c4e9a1d7d865fcb78d78cc2796f46f45cadcda | Conormc98/pyhangman | /gamemodes.py | 3,142 | 3.71875 | 4 | #
# pyhangman - 'Hangman' clone developed in python
# CREATED BY CONOR MCCORMICK
# Script to run the games
#
import wordhandler
import os
def player_vs_cpu():
print('\nPlayer vs CPU game.\n')
word, definition = wordhandler.get_word()
init_game(word, definition)
def player_vs_player():
print('\nPlayer vs Player game.\n')
word = input("Please choose a word for the other player to guess.\n")
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
init_game(word.lower())
def init_game(word, definition):
lives = 6
draw_lives(lives)
letters_questions = []
for i in range(len(word)):
letters_questions.append("?")
draw_letters(letters_questions, definition)
letters_answers = list(word)
guessed_letters = []
game_loop(lives, letters_questions, letters_answers, guessed_letters,\
definition)
def game_loop(lives, letters_questions, letters_answers, guessed_letters,\
definition):
print("\nGuessed Letters:\n")
print(guessed_letters)
print("\n")
guess = input("Guess a letter to find in the word.\n").lower()
if(len(guess) == 1):
if guess not in guessed_letters:
guessed_letters.append(guess)
if guess not in letters_answers:
lives -= 1
else:
for i in range(len(letters_answers)):
if (letters_answers[i] == guess):
letters_questions[i] = guess
if letters_questions == letters_answers:
print("\nYOU WIN!\n")
update_log(letters_answers, "WIN")
return None
else:
print("\nLetter has already been guessed!\n")
draw_lives(lives)
draw_letters(letters_questions, definition)
if (lives < 1):
print("\nYOU LOSE!\nThe word was:")
word = ''.join(letters_answers)
print(word)
update_log(letters_answers, "LOSS")
return None
game_loop(lives, letters_questions, letters_answers, guessed_letters,\
definition)
def update_log(letters_answers, result):
word = ''.join(letters_answers)
log = open('log.txt', 'a')
to_write_list = [word, " [", result, "] \n"]
to_write = ''.join(to_write_list)
log.write(to_write)
log.close()
def draw_lives(lives):
clear = os.system('clear')
print("\n")
print("----------")
print("| |")
if(lives < 6):
print("| O")
else:
print("|")
if(lives == 4):
print("| |")
elif(lives == 3):
print("| \|")
elif(lives < 3):
print("| \|/")
else:
print("|")
if (lives == 1):
print("| /")
elif (lives < 1):
print("| /\\")
else:
print("|")
print("----------\n")
def draw_letters(letters_questions, definition):
print("\n")
print(definition)
print("\n")
for i in range(len(letters_questions)):
if letters_questions[i] == "?":
print("-", end="")
else:
print(letters_questions[i], end="")
print("\n") |
abb20148c49272284d9820e63c367d2a9302b734 | BWizz/TI_Hercules_Development | /LIDAR PC Visualization Applications/Python_Visualization/Lidar_Animation.py | 1,218 | 3.90625 | 4 | """
A simple example of an animated plot
"""
import numpy as m
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
ser = serial.Serial('COM5')
ser.baudrate = 115200
ser.bytesize = 8
ser.parity='N'
ser.stopbits=1
plt.ion()
figure = plt.figure()
plt.plot([0], [0],'.')
ax = plt.gca() # get axis handle
lines = ax.lines[0]
ydata = [None]*1000
xdata = [None]*1000
print('Begin')
def plot_data():
try:
x = ser.readline().strip()
A = x.decode().split(',')
#print(len(A))
if len(A) == 3:
r = float(A[0])
a = float(A[1])
if a > 0 and a < 360:
X= r* m.cos(a*3.14 / 180)
Y= r* m.sin(a*3.14 / 180)
lines.set_xdata(m.append(lines.get_xdata(), X))
lines.set_ydata(m.append(lines.get_ydata(), Y))
#Need both of these in order to rescale
ax.relim()
ax.autoscale_view()
#We need to draw *and* flush
figure.canvas.draw()
figure.canvas.flush_events()
else:
print('Nothing To Append')
except:
print('Error')
pass
while 1:
plot_data()
ser.close()
|
c920125a46523e7319c17d28b7814cb48be44103 | Luciana1012/Term-5 | /starTriangle.py | 356 | 3.765625 | 4 | # def starTriangle(numberOfLine)
# numberOfLine = 9
# numberOfLine = 1("*")
# numberOfLine = 2("*+**")
# print ()
def starTriangle(numberOfLine):
currentLine = 1
for x in range(0, numberOfLine):
numberOfStars = currentLine + (x * 2)
print (" " * (numberOfLine-x), "x" * numberOfStars)
starTriangle(10) |
809de699e91de3aa4812066e8a05908c025d8142 | CesarBoria/backUpProject | /Anton and polyhedrons.py | 370 | 3.875 | 4 | polyhedrons = {'Tetrahedron': 4, 'Cube': 6, 'Octahedron': 8, 'Dodecahedron': 12, 'Icosahedron': 20}
number_polyhedrons = int(input())
list_polyhedrons = []
for i in range(number_polyhedrons):
list_polyhedrons.append(input())
faces = 0
for i in range(len(list_polyhedrons)):
faces += polyhedrons[list_polyhedrons[i]]
print(faces)
print('hello')
|
f4cd623de0c3f572d3a7c21dceb73e484702f3fc | kiram15/ChristmasPacman | /Pacman.py | 3,307 | 3.53125 | 4 | #grinch
class Pacman:
def __init__(self, Maze):
self.location = (5,1)
self.maze = Maze()
def getLocation(self):
return self.location
def actions(self):
walls = [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),
(1,0),(2,0),(3,0),(4,0),(5,0),(6,0),
(6,1),(6,2),(6,3),(6,4),(6,5),(6,6),
(1,6),(2,6),(3,6),(4,6),(5,6),
(2,2),(3,2),(4,2),
(2,4),(3,4),(4,4)]
validActions = []
currentLocation = self.location
right = (currentLocation[0] + 1, currentLocation[1])
left = (currentLocation[0] - 1, currentLocation[1])
up = (currentLocation[0], currentLocation[1] + 1)
down = (currentLocation[0], currentLocation[1] - 1)
if right not in walls:
validActions.append("right")
if left not in walls:
validActions.append("left")
if up not in walls:
validActions.append("up")
if down not in walls:
validActions.append("down")
return validActions
def takeAction(self, action):
tLocation = self.location
newLocation = ()
if action == "right":
newLocation = (tLocation[0] + 1, tLocation[1])
elif action == "left":
newLocation = (tLocation[0] - 1, tLocation[1])
elif action == "up":
newLocation = (tLocation[0], tLocation[1] + 1)
elif action == "down":
newLocation = (tLocation[0], tLocation[1] - 1)
self.maze.makeMove(self, newLocation[0], newLocation[1])
self.location = newLocation
def takeShortest(self, maze):
possibleActions = Pacman.actions(self)
shortestDistance = 100
bestAction = ""
for a in possibleActions:
tempDistance = Pacman.testAction(self, a, maze) #distance to closest dot
if shortestDistance > tempDistance:
shortestDistance = tempDistance
bestAction = a
Pacman.takeAction(self, bestAction)
def testAction(self, action, maze): #specified action, which dot is closest
tempLocation = self.location
if action == "right":
newX = tempLocation[0] + 1
tempLocation = (newX, tempLocation[1])
elif action == "left":
newX = tempLocation[0] - 1
tempLocation = (newX, tempLocation[1])
elif action == "up":
newY = tempLocation[1] + 1
tempLocation = (tempLocation[0], newY)
elif action == "down":
newY = tempLocation[1] - 1
tempLocation = (tempLocation[0], newY)
allDots = Pacman.getDots(maze)
minDistance = 100
for d in allDots:
testDistance = Pacman.distance(self, tempLocation, d)
if testDistance < minDistance:
minDistance = testDistance
return minDistance
def getDots(self):
myMaze = self.maze.maze
dotLocations = []
for r in range(len(myMaze)):
for el in range(len(myMaze[0])):
if myMaze[r][el] == '.':
dotLocations.append((r, el))
return dotLocations
def distance(self, l1, l2):
return abs(l1[0] - l2[0]) + abs(l1[1] - l2[1])
|
a6e45809dea70e29d090375d1dca15cec867d981 | allanko/real-time-red-line | /Control.py | 460 | 3.6875 | 4 | import math
from IllegalArgumentException import *
class Control:
def __init__(self, lon, lat, s, theta):
# Check to make sure theta in range
if (theta<-math.pi or theta>=math.pi):
raise IllegalArgumentException("theta out of range")
self.__lon = lon
self.__lat = lat
self.__s = s
self.__theta = theta
def getLoc(self):
return self.__lon, self.__lat
def getSpeed(self):
return self.__s
def getTheta(self):
return self.__theta
|
1a6d006285b2904126669759afbedbc817c26443 | euvictorfarias/Filtros-Chebyshev2 | /principal.py | 3,209 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from funcoes_cheb2 import *
# Boas Vindas
print("\nBem Vindo(a)!\n")
print("--------------------------------------------------------------------")
print("Tipos de Filtros Chebyshev 2:")
print("(PB) - Passa-Baixa\n(PA) - Passa-Alta")
print("(PF) - Passa-Faixa\n(RF) - Rejeita-Faixa")
print("--------------------------------------------------------------------")
# Pega o tipo de filtro e os pontos de projeto
tipo = input("Digite a SIGLA do tipo que deseja: ")
print("\nAgora vamos aos Pontos de Projeto ... ")
if tipo == "PB" or tipo == "PA":
Wp = float(input("Digite a Frequência de Passagem (Wp): "))
Ws = float(input("Digite a Frequência de Rejeição (Ws): "))
Ap = float(input("Digite a Atenuação de Passagem (Ap): "))
As = float(input("Digite a Atenuação de Rejeição (As): "))
elif tipo == "PF" or tipo == "RF":
Wp1 = float(input("Digite a Frequência de Passagem (Wp1): "))
Wp2 = float(input("Digite a Frequência de Passagem (Wp2): "))
Ws1 = float(input("Digite a Frequência de Rejeição (Ws1): "))
Ws2 = float(input("Digite a Frequência de Rejeição (Ws2): "))
Ap = float(input("Digite a Atenuação de Passagem (Ap): "))
As = float(input("Digite a Atenuação de Rejeição (As): "))
# Inicializa um Objeto da Classe Butterworth
if tipo == "PB" or tipo == "PA":
filtro = chebyshev(tipo, Wp, Ws, Ap, As)
elif tipo == "PF" or tipo == "RF":
filtro = chebyshev(tipo, Wp1, Ws1, Ap, As, Wp2, Ws2)
print("\n--------------------------------------------------------------------")
print("As definições do seu filtro são as seguintes:")
print("--------------------------------------------------------------------")
# Define e exibe a Constante de Proporcionalidade
e = filtro.constProp()
print(f'(e) - Constante de Proporcionalidade: {e:.5f}')
# Define e exibe frequência de ressonancia e bandas de passagem
if tipo == "PF" or tipo == "RF":
Wo = filtro.freq_ress()
print(f'(Wo) - Frequência de Ressonância: {Wo:.5f}')
Bp, Bs = filtro.bandas()
print(f'(Bp) - Banda de Passagem: {Bp:.5f}')
print(f'(Bs) - Banda de Rejeição: {Bs:.5f}')
# Define e exibe ordem do filtro
n, N = filtro.ordem()
print(f'(N) - Ordem: {N} ({n:.5f})')
# Define e exibe frequência de corte
if tipo == "PB" or tipo == "PA":
Wc = filtro.freq_corte()
print(f'(Wc) - Frequência de Corte: {Wc:.5f}')
elif tipo == "PF" or tipo == "RF":
Wc1, Wc2 = filtro.freq_corte()
print(f'(Wc1) - Frequência de Corte 1: {Wc1:.5f}')
print(f'(Wc2) - Frequência de Corte 2: {Wc2:.5f}')
# Define e exibe Função de Transferência
H = filtro.func_tranf()
print("--------------------------------------------------------------------")
print("Sua Função de Transferência H(s) é:")
print(H)
print("--------------------------------------------------------------------")
# Plotar Gráficos
print("Deseja Plotar os gráficos de Bode?")
resposta = input("'s' ou 'n' (sem aspas): ")
if resposta == 's':
filtro.plotar()
elif resposta == 'n':
print("Gráfico não iniciado!")
else:
print("Resposta não identificada.")
print("--------------------------------------------------------------------\n")
|
310bd0d238c14f35a0ac9c6a8224b6d7fac97780 | arunpandian17/python-problemsolving-programs | /zoho qn.py.py | 419 | 3.59375 | 4 | '''given a array of numbers and a numbers k print the max possible k digit numbers which can
be form using given numbers
input:
4
1 4 973 97
3
output:
974
'''
import itertools as it
n=int(input())
a=input().split()
b=int(input())
c=list()
for i in range(0,n+1):
d=list(it.permutations(a,i))
for j in d:
f=""
f=f.join(j)
if(len(f)==b):
c.append(f)
print(max(c)) |
70e65b0ba9069b2aab12d6668bb7d08fa0f1913e | arunpandian17/python-problemsolving-programs | /fibonacci.py | 463 | 4.09375 | 4 | def fib(n):
a, b = 0, 1
count = 0
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n)
else:
print("Fibonacci sequence:")
while count < n:
print(a)
c = a + b
a = b
b = c
count += 1
n= int(input("terms :"))
if n>1:
fib(n)
else:
print("Enter valid number")
|
39e6f81018ea224401cf4c663245f2df15e19696 | arunpandian17/python-problemsolving-programs | /extract num.py.py | 184 | 3.578125 | 4 | '''a=input()
sum=0
res=0
a=int(a)
while int(a)>0:
b=int(a)%10
sum+=b
a//=10
while sum>0:
sum1=sum%10
res+=sum1
sum//=10
print(res)
'''
a=4
c=(a<<3)-a
print(c) |
0ad6fba21fcf3f030a7421322de0fcbbbfc119f0 | miczek2309/logia | /wiatraki.py | 1,647 | 3.65625 | 4 | import turtle
t = turtle.Pen()
t.speed(0)
t.left(90)
kratka = 26
def wiatrak():
t.forward(kratka * 3)
t.color("black", "orange")
t.begin_fill()
t.right(90)
t.forward(kratka * 2)
t.left(135)
t.forward(36.77)
t.left(45)
t.forward(kratka)
t.left(90)
t.forward(kratka)
t.setheading(0)
t.end_fill()
t.color("black", "green")
t.up()
t.left(90)
t.forward(kratka)
t.right(90)
t.forward(kratka)
t.left(90)
t.down()
t.begin_fill()
t.forward(kratka * 2)
t.left(135)
t.forward(36.77)
t.left(45)
t.forward(kratka)
t.left(90)
t.forward(kratka)
t.setheading(0)
t.end_fill()
t.up()
t.setheading(180)
t.forward(kratka)
t.color("black", "orange")
t.down()
t.begin_fill()
t.forward(kratka)
t.right(45)
t.forward(36.77)
t.right(135)
t.forward(kratka * 2)
t.end_fill()
t.color("black", "green")
t.up()
t.right(90)
t.forward(kratka)
t.down()
t.begin_fill()
t.forward(kratka)
t.right(45)
t.forward(36.77)
t.right(135)
t.forward(kratka * 2)
t.right(90)
t.forward(kratka)
t.end_fill()
def duzy_wiatrak():
wiatrak()
t.right(90)
t.forward(kratka * 4)
t.left(90)
t.forward(kratka * 2)
t.left(90)
t.forward(kratka * 5)
wiatrak()
t.right(90)
t.forward(kratka * 9)
t.left(90)
t.forward(kratka * 2)
t.left(90)
def wiatraki(ilosc):
if ilosc == 1:
duzy_wiatrak()
wiatrak()
else:
for i in range(ilosc):
duzy_wiatrak()
wiatrak()
wiatraki(6)
|
d6228dec0847ca4d3cc5d34c07ce66a795c49682 | miczek2309/logia | /max_pod_listy.py | 204 | 3.796875 | 4 | def max_listy_list(lista):
for i in lista:
reka = 0
for x in i:
if x > reka:
reka = x
print(reka,end=" ")
max_listy_list([[2, 5], [8, 10], [0, 1]])
|
2453dd359e7434bddc63fec4f3fab8b6dba97b19 | KenOtis/-Automate-The-Boring-Stuff--Youtube-tutorials | /ATBSLesson5.py | 511 | 4.0625 | 4 | #if else statements
#If statement
name = 'alice'
if name == 'alice':
print ('Hello Alice')
print ('Done')
#If else Statement--> Password
password='Pencil'
if password=='Pencil':
print("Acess Granted")
else:
print("Wrong Password")
name='Kenny'
age= 21
if name=='Alice':
print('Hello Alice')
elif age<12:
print("You are not Alice you child!")
elif age>200:
print("Unlike you, Alice is not a wacky old person")
elif age ==21:
print("Hello, Alice?") |
1262490a7623b49b78f664afe6e697492c3c3ace | harbungenTA/python | /index.py | 212 | 3.609375 | 4 | print("Moj program")
print("Podaj swoje imie:")
imie=input()
print("Twoje imie:")
print(imie)
x = [1, 2, 3, "ein", "duo"]
print(x)
print(x[0])
print(x[0:1])
print(len(x))
for e in x:
pass
|
88fe4f96bbd9c35bc4bb02643525a09e919e1a4a | joyfeel/leetcode | /leetcode-algorithms/125. Valid Palindrome/solution.py | 239 | 3.5 | 4 | #
# @lc app=leetcode id=125 lang=python3
#
# [125] Valid Palindrome
#
class Solution:
def isPalindrome(self, s: str) -> bool:
clean_list = [ c for c in s.lower() if c.isalnum() ]
return clean_list == clean_list[::-1]
|
4c14fce06e4ee571f3cea253a07fa49d7b9ea8ce | Jovian2000/forever-young | /derde-opdracht.py | 118 | 3.984375 | 4 | for time in range(1,13):
print(str(time) + ":00 am")
for time in range(1,13):
print(str(time) + ":00 pm") |
ad3189f3c124b726a44f0148c6695b67e055d598 | antonyngayo/react-upload | /server/db.py | 1,094 | 3.609375 | 4 | #!/usr/bin/python3
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, TIMESTAMP, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import text
Base = declarative_base()
class User(Base):
__tablename__ = "person"
id = Column('id', Integer, primary_key=True, autoincrement=True)
username = Column('username', String, unique=True)
last_login_date = Column(TIMESTAMP(timezone=False), server_default=func.now(), nullable=False)
engine = create_engine('sqlite:///users.db', echo=True)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
# Creating a session object to help in creating, updating, deleting objects in database
session = Session()
# Adding user
# user = User()
# user.id = 1
# user.username = "Anthony"
# session.add(user)
# session.commit()
users = session.query(User).all()
for user in users:
print(f"The username is {user.username} and id: {user.id} and they last logged in at: {user.last_login_date}")
session.close()
|
ceccbd79d0f1dde0b90510eaf8e9208eead6072d | Demi-Leigh/BMI-Calculator | /main.py | 2,332 | 3.71875 | 4 | # Designing a program that calculates your BMI
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
# Creating a window
window = tk.Tk()
window.title("BMI Calculator")
window.geometry("500x300")
window.resizable(0, 0)
# Creating labels and entry boxes for Height
height_label = tk.Label(text="Height: ")
height_label.grid(row=0, column=0, pady=20, padx=20)
cm_label = tk.Label(text="cm")
cm_label.grid(row=0, column=2)
Height = tk.StringVar()
height_ent = tk.Entry(width=10, bg="grey", textvariable=Height)
height_ent.grid(row=0, column=1)
# Creating labels and entry boxes for Weight
weight_label = tk.Label(text="Weight: ")
weight_label.grid(row=1, column=0)
kg_label = tk.Label(text="Kilograms")
kg_label.grid(row=1, column=2)
Weight = tk.StringVar()
weight_ent = tk.Entry(width=10, bg="grey", textvariable=Weight)
weight_ent.grid(row=1, column=1)
# Creating option menu for gender
gender_label = tk.Label(text="Gender: ")
gender_label.grid(row=3, column=0)
Gender = tk.StringVar()
gender_box = ttk.Combobox(window, width=10, textvariable="Gender", state="readonly")
gender_box["values"] = "Select Male Female"
gender_box.current(0)
gender_box.grid(row=3, column=1, pady=10)
# Creating label and entry for Age
age_label = tk.Label(text="Age: ")
age_label.grid(row=4, column=0, pady=10)
Age = tk.StringVar()
age_ent = tk.Entry(window, width=10, bg="grey", textvariable="Age")
age_ent.grid(row=4, column=1)
# Creating the Calculate,Exit and Clear buttons
ans_btn = tk.Button(text="Calculate", command="calculate_bmi", bg="grey")
ans_btn.grid(row=5, column=0, padx=10, pady=20)
clear_btn = tk.Button(text="Clear", command="clear", bg="grey")
clear_btn.grid(row=5, column=1, padx=10, pady=20)
exit_btn = tk.Button(text="Exit", command="exit", bg="grey")
exit_btn.grid(row=5, column=2, padx=10, pady=20)
# Defining functions
def calculate_bmi():
print(weight_entry.get())
weight = float(weight_ent.get())
height = float(height_ent.get())
answer = weight / (height / 100) ** 2
def ideal_bmi():
weight = float(weight_ent.get())
height = float(height_ent.get())
gender = gender_box.get()
if gender == "male":
result = 0.5 * weight / ((height / 100) ** 2) + 11.5
bmi = round(result, 2)
print(bmi)
window.mainloop()
|
2ba4518f80b3e9e582177995541ff97e60b768ff | lgaetano/automate_the_boring_stuff | /randomQuizGenerator.py | 1,097 | 3.9375 | 4 | #! python3
# randomQuizGenerator.py - Creates quizzes with questions
# and answers in random order, along with answer key.
import random
# Quiz data
capitals = {'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Colorado': 'Denver'
}
# Generate 5 quiz files
for i in range(5):
# Create the quiz and answer key files
quiz_file = open(f'quiz{i + 1}.txt', 'w')
ans_file = open(f'quiz{i + 1}Ans.txt', 'w')
# Write out the header for the quiz
quiz_file.write('Name:\n\nDatae:n\n\Period:\n\n')
quiz_file.write(f'State Capitol Quiz Form {i+1}')
quiz_file.write('\n\n')
# Shuffle the order of the states
states = list(capitals.keys())
random.shuffle(states)
# Loop through all states, making a question for each
for i in range(len(states)):
quiz_file.write(f'{i + 1}: What is the capital of {states[i]}\n')
ans_file.write(f'{i + 1}: {capitals[states[i]]}\n')
quiz_file.close()
ans_file.close()
|
3e9ca0a8d378d03c4ae3aa580c4f1e8b12d42953 | saimkhan92/Recursion | /list_sum_recursive.py | 194 | 3.921875 | 4 | # Sum of a python list using recursion
l=[2,5,2,6,88,4,6,8,7]
def listsum(lst):
if len(lst)==1:
return lst[0]
else:
return lst[0]+listsum(lst[1:])
print(listsum(l))
|
b8cf28e3459fe7c637dacef97e6285289b4128d2 | SeveroYug/Python-tests-and-exercises | /Разрядность и списки.py | 511 | 3.6875 | 4 | # Задача: вывести на экран N (вводится пользователем) чисел от 0 до бесконечности, которые делятся без остатка на свой порядок (1 на 1, 11 на 2, 111 на 3 и т.д.)
n = int(input('Введите N: '))
i = 0
p = 0
lst = []
while len(lst)<n:
z = len(str(i))
if i%z == 0:
print(i)
lst.append(i)
p += 1
i += 1
else:
p +=1
i += 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.