blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
47115e590894e88e12ec51d274170e521bcc21a9 | CrisPirat/devsu-jam-2021-preclasificatory | /Question02.py | 1,906 | 3.625 | 4 | def sumOfElement(numbers, number):
sum = 0
for n in numbers:
if n != number:
sum += n
return sum
def searchMaximum(numbers):
max = numbers[0]
for n in numbers:
if max < n:
max = n
return max
def searchMinimum(numbers):
min = numbers[0]
for n in numbers:
if min > n:
min = n
return min
def searchIndexValue(numbers, number):
indexNumbers = []
index = 0
for n in numbers:
if number == n:
indexNumbers.append(index)
index += 1
return indexNumbers
def getOnlyIndexesValues(numbers,indexes):
values = []
for n in indexes:
values.append(numbers[n])
return values
def maximumElementWithMinimunSum(numbers):
numbersSum =[]
for n in numbers:
numbersSum.append(sumOfElement(numbers,n))
minSum = searchMinimum(numbersSum)
indexNumbersMinimunSum = searchIndexValue(numbersSum,minSum)
numbersValues = getOnlyIndexesValues(numbers,indexNumbersMinimunSum)
maxValue = searchMaximum(numbersValues)
return maxValue
if __name__ == "__main__":
numbers = [1,2,3,3,3,3,4,5,6,6] #Output: 6
test_01 = [4,-10,6,-3,-2,-4,-9,10,0,-7,-4,-9,-4,2,-6,-7,10,1,8,10,5,1,2,-8,2,-10,0,-6,4,-2,-6,8,-3,0,9,-4,4,-5,4,-8,-1,-3,-8,8,-6,-7,8,6,0,9,2,-3,-4,4,-5,-2,0,3,0,-3,-6,-4,1,-4,-5,3,2,1,4,-8,-8,-3,-6,2,-4,9,-6,-9,0,9,9,-6,3,-4,0,-7,-5,0,6,-6,-10,4,-2,6,-3,-1,4,1,-3,-7]
test_02 = [2,-10,0,-8,4,-5,10,0,8,-9,4,-6,3,4,8,10,6,-5,2,-6,9,-10,4,-1,6,-1,7,10,-10,-3,-6,1,7,-1,9,-1,2,3,4,8,-3,-3,-5,5,-8,-1,9,8,8,0,-5,3,-6,-9,10,-8,-3,-4,-1,-8,-6,4,-10,1,7,-1,0,10,1,-1,-6,-2,-2,5,-1,-7,4,5,-5,6,-7,6,-2,-5,5,7,-4,8,0,8,-10,-7,-2,0,9,10,5,5,-8,9]
print(maximumElementWithMinimunSum(numbers)) #output 6
print(maximumElementWithMinimunSum(test_01)) #output 9
print(maximumElementWithMinimunSum(test_02)) #output 10 |
e6a0c9d85682741a71ef06d321855c8fa9aff4f3 | zenubis/LeetCodeAnswers | /04-Daily/20210211/20210211.py | 1,280 | 4.21875 | 4 | # Valid Anagram
# https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3636/
# Given two strings s and t , write a function to determine if t is an anagram of s.
# Example 1:
# Input: s = "anagram", t = "nagaram"
# Output: true
# Example 2:
# Input: s = "rat", t = "car"
# Output: false
# Note:
# You may assume the string contains only lowercase alphabets.
# Follow up:
# What if the inputs contain unicode characters? How would you adapt your solution to such case?
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
# def isAnagram(self, s: str, t: str) -> bool:
# ls = len(s)
# if ls != len(t):
# return False
# lookup = {}
# for i in range(ls):
# if s[i] in lookup:
# lookup[s[i]] += 1
# else:
# lookup[s[i]] = 1
# try:
# for i in range(ls):
# lookup[t[i]] -= 1
# except KeyError:
# return False
# for k in lookup:
# if lookup[k] != 0:
# return False
# return True |
0b4d18c2aca539bbc7aa918cf2220b8f6b872610 | ngzhaoming/Kattis | /Difficulty 4.1/Rock Paper Scissors/RockPaperScissors.py | 1,327 | 3.609375 | 4 | counter = 0
def isDraw(onePlay, twoPlay):
if onePlay == twoPlay:
return True
return False
def isWin(onePlay, twoPlay):
if onePlay == "rock" and twoPlay == "scissors":
return True
elif onePlay == "scissors" and twoPlay == "paper":
return True
elif onePlay == "paper" and twoPlay == "rock":
return True
else:
return False
while True:
line = input().split(" ")
players = int(line[0])
if players == 0:
break
if counter != 0:
print()
wins = []
loses = []
for x in range(players + 1):
wins.append(0)
loses.append(0)
games = int(int(line[1]) * players * (players - 1) / 2)
for x in range(games):
line = input().split(" ")
one = int(line[0])
onePlay = line[1]
two = int(line[2])
twoPlay = line[3]
if isDraw(onePlay, twoPlay):
pass
elif isWin(onePlay, twoPlay):
wins[one] += 1
loses[two] += 1
else:
loses[one] += 1
wins[two] += 1
for x in range(1, len(wins)):
winner = wins[x]
loser = loses[x]
if winner + loser == 0:
print("-")
else:
print("{0:.3f}".format((winner / (winner + loser))))
counter += 1 |
1ce729c324238a194cb2a30495e7cd64fe693c6f | MokkeMeguru/dsa | /aoj/merge_sort.py | 1,026 | 3.84375 | 4 | import sys
import math
import copy
from typing import Tuple, List, Union
input = sys.stdin.readline
def merge(left, right):
result = []
compare = 0
while len(left) > 0 and len(right) > 0:
compare += 1
if left[0] <= right[0]:
result.append(left[0])
left = left[1:]
else:
result.append(right[0])
right = right[1:]
if len(left) < 1:
compare += len(right)
result += right
elif len(right) < 1:
compare += len(left)
result += left
return result, compare
def merge_sort(A):
if len(A) < 2:
return A, 0
else:
mid = int(len(A) / 2)
left, c1 = merge_sort(A[mid:])
right, c2 = merge_sort(A[:mid])
Aa, c = merge(left, right)
return Aa, c1 + c2 + c
def main():
n = int(input())
S = list(map(int, input().split()))
Ss, count = merge_sort(S)
print(" ".join (list(map(str, Ss))))
print(count)
if __name__ == '__main__':
main()
|
9d652a046432b5d06e06d77dafcf360145d8ecba | NaveenSingh4u/python-learning | /basic/python-oops/calculator.py | 574 | 3.859375 | 4 | class Calculator:
# Note: 1. staticmethod is used for creating utility
# 2. Do not pass self param in static method
@staticmethod
def add(x, y):
return x + y;
@staticmethod
def sub(x, y):
return x - y;
@staticmethod
def mul(x, y):
return x * y;
@staticmethod
def div(x, y):
return x / y;
@staticmethod
def avg(x, y):
return (x + y) / 2;
print(Calculator.add(120, 39))
print(Calculator.sub(20, 38))
print(Calculator.mul(20, 10))
print(Calculator.div(20, 10))
print(Calculator.avg(10, 20))
|
f1fd18ffa7100ad090b25338f8bc4dccd1b460dc | nengen/pythRSQL | /homework1/wayOfTheProgram.py | 480 | 3.640625 | 4 | #source = http://greenteapress.com/thinkpython2/html/thinkpython2002.html
print("Hello world!")
constant = 4/3
pi = 3.14
radius = 5
volumeOfSphere = float( constant * pi * radius**3)
print(volumeOfSphere)
priceOfBook = 24.95
discount = 0.4
shippingCostsFirstCopy = 3
shippingCostsRest = 0.75
amountOfCopiesSold = 60
totalWholeSaleCost = (priceOfBook*discount)*amountOfCopiesSold + shippingCostsFirstCopy + (amountOfCopiesSold-1)*shippingCostsRest
print(totalWholeSaleCost)
|
3a280a04d0334a5b7bfbcb662629462b608e1377 | m-RezaFahlevi/we_still_learning_gitGithub | /pythonFiles/web_scraping.py | 774 | 3.578125 | 4 | from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
from urllib.error import URLError
#I think, it is good to write a program in the term of
#Object-Oriented Programming :)
class WebScraping:
def __init__(self, someUrl):
self.someUrl = someUrl
def getUrl(self):
try:
html = urlopen(self.someUrl)
except HTTPError:
return None
try:
bs = BeautifulSoup(html.read(), "html5lib")
title = bs.body.h
except AttributeError:
return None
return title
pyObject = WebScraping('http://www.pythonscraping.com/pages/page1.html')
print("Title could not be found") if pyObject.getUrl() == None else print(pyObject.getUrl())
|
98c01701c1918ecd23f3a3d68e89f0b0c80447ca | olegzinkevich/programming_books_notes_and_codes | /numpy_bressert/ch02_scipy/sparse_matrix.py | 1,483 | 3.8125 | 4 | # h sparse matrices (разреженная матрица)
# WithNumPy we can operatewith reasonable speeds on arrays containing 106 elements.
# Oncewe go up to 107 elements, operations can start to slowdown and Python’smemory
# will become limited, depending on the amount of RAM available. What’s the best
# solution if you need to work with an array that is far larger—say, 1010 elements? If
# these massive arrays primarily contain zeros, then you’re in luck, as this is the property
# of sparse matrices. If a sparse matrix is treated correctly, operation time and memory
# usage can go down drastically
import numpy as np
from scipy.sparse.linalg import eigsh
from scipy.linalg import eigh
import scipy.sparse
import time
N = 3000
# Creating a random sparse matrix
m = scipy.sparse.rand(N, N)
print(m)
# Creating an array clone of it
a = m.toarray()
print('The numpy array data size: ' + str(a.nbytes) + ' bytes')
print('The sparse matrix data size: ' + str(m.data.nbytes) + ' bytes')
# Non-sparse
t0 = time.time()
res1 = eigh(a)
dt = str(np.round(time.time() - t0, 3)) + ' seconds'
print('Non-sparse operation takes ' + dt)
# Sparse
t0 = time.time()
res2 = eigsh(m)
dt = str(np.round(time.time() - t0, 3)) + ' seconds'
print('Sparse operation takes ' + dt)
# The memory allotted to the NumPy array and sparse matrix were 68MB and 0.68MB,
# respectively. In the same order, the times taken to process the Eigen commands were
# 36.6 and 0.2 seconds onmy computer. |
21a44f17b75a3397ca787e169817783415d809c9 | annaQ/annaWithLeetcode | /buildTree.py | 1,793 | 3.984375 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param inorder, a list of integers
# @param postorder, a list of integers
# @return a tree node
def buildTree(self, inorder, postorder):
if len(inorder) == 0 or len(postorder) != len(inorder):
print("None")
return None
#postorder's last one is the root
root = TreeNode(postorder[-1])
print("root", root.val)
print("in:",inorder)
print("post:",postorder)
if len(inorder) == 1:
return root
#seperate the lists in to two children's
root_index = inorder.index(postorder[-1])
print("sperate at:", root_index)
#inorder list is divided by root, first part is for left child
left_in = inorder[:root_index]
print("left_in",left_in)
right_in = inorder[root_index + 1 :]
print("right_in",right_in)
#postorder list should have the first part for left child, as long as the inorder list
left_post = postorder[:len(left_in)]
print("left_post",left_post)
right_post = postorder[len(left_in) : -1]
print("right_post",right_post)
root.left = self.buildTree(left_in, left_post)
root.right = self.buildTree(right_in, right_post)
return root
def levelOrder(self, root):
entire = []
if root == None:
return entire
parent = [root]
while len(parent) != 0:
children = []
listLevel = []
for x in parent:
if x == None:
continue
listLevel.append(x.val)
if x.left != None:
children.append(x.left)
if x.right != None:
children.append(x.right)
parent = children
entire.append(listLevel)
return entire
postorder = [4,1,3,10,11,8,2,7]
inorder = [4,10,3,1,7,11,8,2]
s = Solution()
root = s.buildTree(inorder, postorder)
print(s.levelOrder(root))
|
b9313069019d3c542026ed567e80bdc209b14729 | vinod77-sudo/Python-Fundamentals-B_12 | /testclass_1.py | 491 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class Animal:
"""A simple function of dog"""
def __init__(self,name,age):
"""About the intro"""
self.name=name
self.age=age
print("success fully completed ")
def sit(self):
"""about sitting position of dog"""
print(f"{self.name} is in sitting position")
def roll_over(self):
"""about the rollover position"""
print(f"{self.name} is rolled over")
# In[ ]:
|
4a3f9b74cfad2f7118c006c911b8c75fbc5a9f92 | ErikMurt/Automate-the-boring-stuff | /isPhoneNumber.py | 921 | 4.1875 | 4 | ### Checking if string is a phone number
def isPhoneNumber(text):
if len(text) != 12: # Checking if number is 12 symbols long
return False
for i in range(0, 3): # Checking if first 3 symbols are numbers
if not text[i].isdecimal():
return False
if text[3] != '-': # Checking if symbol 4 is a -
return False
for i in range(4, 7): # Checking if symbols 5 - 7 are numbers
if not text[i].isdecimal():
return False
if text[7] != '-': # Checking if symbol 8 is a -
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):
chunk = message[i:i+12]
if isPhoneNumber(chunk):
print('Phone number found: ' + chunk)
print('Done')
|
25b8c48a515cf7302313e14792e770ca8f16ca9c | TerryLun/Code-Playground | /Leetcode Problems/lc628e.py | 1,408 | 4.125 | 4 | """
628. Maximum Product of Three Numbers
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
"""
def maximumProduct(nums):
highs = [float('-inf'), float('-inf'), float('-inf')]
lows = [0, 0]
for n in nums:
if n > highs[0]:
highs[2] = highs[1]
highs[1] = highs[0]
highs[0] = n
elif n > highs[1]:
highs[2] = highs[1]
highs[1] = n
elif n > highs[2]:
highs[2] = n
if n < lows[0]:
lows[1] = lows[0]
lows[0] = n
elif n < lows[1]:
lows[1] = n
print(highs, lows)
return max(highs[0] * highs[1] * highs[2], highs[0] * lows[0] * lows[1])
inp = [1, 2, 3]
exp = 6
print(maximumProduct(inp) == exp)
inp = [1, 2, 3, 4]
exp = 24
print(maximumProduct(inp) == exp)
inp = [1, 2, 3, 4, -2, -9]
exp = 4 * -2 * -9
print(maximumProduct(inp) == exp)
inp = [1, 2, 3, 4, -2, -3]
exp = 4 * 2 * 3
print(maximumProduct(inp) == exp)
inp = [1, 2, 3, 4, -2, -1]
exp = 4 * 2 * 3
print(maximumProduct(inp) == exp)
inp = [-1, -2, -3]
exp = -6
print(maximumProduct(inp) == exp)
print(maximumProduct(inp))
|
240e71f340b33b9235adcee42b0ba1228ae5bad2 | than5466/advent_of_code | /day_15/main.py | 7,817 | 3.515625 | 4 | #!/usr/bin/env python3
import random
import queue
class Graph():
def __init__(self):
self.vertices = {}
self.tested_direction = {}
self.not_explored = set()
self.input = 0
self.current_vertice = [0,0]
self.Goal = None
self.output = None
self.previous_vertice = None
self.prev_pos = None
self.Add_If_Not_Visited()
def Move(self):
self.previous_vertice = self.current_vertice
self.prev_pos = self.curr_pos
if self.input == 1:
self.current_vertice = self.current_vertice[0],self.current_vertice[1] + 1
elif self.input == 2:
self.current_vertice = self.current_vertice[0],self.current_vertice[1] - 1
elif self.input == 3:
self.current_vertice = self.current_vertice[0] - 1,self.current_vertice[1]
elif self.input == 4:
self.current_vertice = self.current_vertice[0] + 1,self.current_vertice[1]
def Add_If_Not_Visited(self):
self.curr_pos = '{},{}'.format(self.current_vertice[0],self.current_vertice[1])
if self.curr_pos not in self.vertices.keys():
self.vertices[self.curr_pos] = set()
self.tested_direction[self.curr_pos] = set()
self.not_explored.add(self.curr_pos)
def Check_If_Fully_Visited(self):
Length = len(self.tested_direction[self.curr_pos])
if Length == 4 and self.curr_pos in self.not_explored:
self.not_explored.remove(self.curr_pos)
def Set_Goal(self):
self.Goal = self.curr_pos
def Completed(self):
if len(self.not_explored) == 0:
return True
return False
def Add_Vertice(self):
self.vertices[self.curr_pos].add(self.prev_pos)
self.vertices[self.prev_pos].add(self.curr_pos)
def Add_Node(self):
self.tested_direction[self.curr_pos].add(self.input)
if self.output == 1:
self.Move()
self.Add_If_Not_Visited()
self.Add_Vertice()
elif self.output == 2:
self.Move()
self.Add_If_Not_Visited()
self.Set_Goal()
self.Add_Vertice()
self.Check_If_Fully_Visited()
def Set_Output(self, output):
self.output = output
def Set_Input(self):
self.input = random.randint(1,4)
if self.curr_pos in self.not_explored:
while self.input in self.tested_direction[self.curr_pos]:
self.input = random.randint(1,4)
return self.input
def Get_Goal(self):
return self.Goal
def Get_Vertices(self):
return self.vertices
def Quotient(number, divisor):
return number // divisor
def Remainder(number, divisor):
return number % divisor
def Get_Value(Code, Dict, Index):
if Index < len(Code):
return Code[Index]
elif Index in Dict.keys():
return Dict[Index]
return 0
def Get_Parameter_Value(Code, Dict, Index, Mode, Base):
if Mode == 0:
Index = Get_Value(Code, Dict, Index)
elif Mode == 2:
Index = Get_Value(Code, Dict, Index) + Base
elif Mode != 1:
raise RuntimeError("Parameter mode {} is not supported".format(Mode))
return Get_Value(Code, Dict, Index)
def Insert(Code,Dict,Value,Index):
if Index < len(Code):
Code[Index] = Value
else:
Dict[Index] = Value
return Code, Dict
def Insert_At_Correct_Index(Code, Dict, Value, Index, Mode, Base):
if Mode == 0:
Index = Get_Value(Code, Dict, Index)
elif Mode == 2:
Index = Get_Value(Code, Dict, Index) + Base
return Insert(Code,Dict,Value,Index)
def Intcode_Program(Intcode, Node):
Pointer = 0
Base = 0
Indexes_Outside_Scope = {}
while True:
First_Instruction = Get_Value(Intcode, Indexes_Outside_Scope, Pointer)
OP_Code = Remainder(First_Instruction,100)
Noun_Mode = Remainder(Quotient(First_Instruction,100),10)
Verb_Mode = Remainder(Quotient(First_Instruction,1000),10)
Insert_Mode = Remainder(Quotient(First_Instruction,10000),10)
Noun_Index = Pointer + 1
Verb_Index = Pointer + 2
Insert_Index = Pointer + 3
if OP_Code == 99:
return Node
elif OP_Code in [1,2,7,8]:
Noun = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Noun_Index, Noun_Mode, Base)
Verb = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Verb_Index, Verb_Mode, Base)
if OP_Code == 1:
Var = Noun+Verb
elif OP_Code == 2:
Var = Noun*Verb
elif OP_Code == 7:
Var = int(Noun < Verb)
elif OP_Code == 8:
Var = int(Noun == Verb)
Intcode, Indexes_Outside_Scope = Insert_At_Correct_Index(Intcode, Indexes_Outside_Scope, Var, Insert_Index, Insert_Mode, Base)
Pointer += 4
elif OP_Code in [3,4]:
if OP_Code == 3:
Input = Node.Set_Input()
Intcode, Indexes_Outside_Scope = Insert_At_Correct_Index(Intcode, Indexes_Outside_Scope, Input, Noun_Index, Noun_Mode, Base)
elif OP_Code == 4:
value = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Noun_Index, Noun_Mode, Base)
Node.Set_Output(value)
if Node.Completed():
return Node
Node.Add_Node()
Pointer += 2
elif OP_Code in [5,6]:
First_Parameter = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Noun_Index, Noun_Mode, Base)
Second_Parameter = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Verb_Index, Verb_Mode, Base)
if OP_Code == 5:
if First_Parameter > 0:
Pointer = Second_Parameter
else:
Pointer += 3
elif OP_Code == 6:
if First_Parameter != 0:
Pointer += 3
else:
Pointer = Second_Parameter
elif OP_Code == 9:
Parameter = Get_Parameter_Value(Intcode, Indexes_Outside_Scope, Noun_Index, Noun_Mode, Base)
Base += Parameter
Pointer += 2
else:
raise RuntimeError("OP_Code {} not allowed".format(OP_Code))
def Find_Closest_Paths(graph, start_pos):
q = queue.Queue()
current_dist = 0
current_size = 0
visited = set()
distances = dict()
q.put(start_pos)
visited.add(start_pos)
distances[current_dist] = set()
distances[current_dist].add(start_pos)
current_size = 1
while not q.empty():
if current_size == 0:
current_dist += 1
current_size = q.qsize()
distances[current_dist] = set()
current_node = q.get()
current_size -= 1
for vertice in graph[current_node]:
if vertice not in visited:
visited.add(vertice)
distances[current_dist].add(vertice)
q.put(vertice)
return distances
def Program(Code):
# Part 1
Node = Graph()
Node = Intcode_Program(Code,Node)
Goal = Node.Get_Goal()
Distances = Find_Closest_Paths(Node.Get_Vertices(), '0,0')
for k,v in Distances.items():
if Goal in v:
dist = k
print("Answer, Part 1: {}".format(dist))
# Part 2
Distances_2 = Find_Closest_Paths(Node.Get_Vertices(), Goal)
time = max(Distances_2.keys())
print("Answer, Part 2: {}".format(time))
if __name__ == '__main__':
f = open("data.txt", "r")
Data = [int(x) for x in f.read().split(",")]
Program(Data.copy()) |
a08fec99b4d6413bf279bbd6bd30d8d3bb8ed820 | rajan596/python-hacks | /Tut-2-classes.py | 657 | 4.125 | 4 | #!/usr/bin/python3
# classes
class calculator:
def addition(x,y):
return x+y
def subtraction(x,y):
return x-y
def mult(x,y):
return mult
def divide(x,y):
if y==0:
print("Error")
return -1
else:
return x/y
print(calculator.addition(2,5))
# class car
class Car:
name='car-object'
color='car-color'
def __init__(self,name,color):
self.name=name
self.color=color
def details(self):
print('name : ' + self.name)
print('color : ' + self.color)
if __name__=='__main__':
c=Car('A','red')
c.details()
|
7137c8e1d31b94aa1d52333665f2178db0e5b875 | hj8239ka45/python_test | /python/Tkinter窗口/basic_Tkinter_5_scale.py | 1,257 | 3.671875 | 4 | ## 2018/01/12 basic_Tkinter_5
## scale
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('300x150')
l = tk.Label(window,bg='yellow',width=20,text='')
l.pack()
#v(隨意假設)自動由scale擷取,因為scale有get value功能
def print(v):
l.config(text='you have selected'+v)
#從5~11,方向,length pixal寬度,顯示 1 true 0 false,標籤長度
#單位精準度,回應副函式
#HORIZONTAL VERTICAL
#get() : This method returns the current value of the scale.
#set(value) : Sets the scale's value.
s = tk.Scale(window,label='try me',from_=5,to=11,
orient=tk.HORIZONTAL,length=200,showvalue=0,
tickinterval=3,resolution=0.001,command=print)
s.pack()
window.mainloop()
def sel():
selection = "Value = " + str(var.get())
label.config(text=selection)
window2 = tk.Tk()
window2.title('my window2')
window2.geometry('300x180')
label = tk.Label(window2,bg='yellow',width=20)
label.pack()
var = tk.DoubleVar()
#不傳函數,用tk的var去接,否則則需如同window寫法一致
scale = tk.Scale( window2, variable = var)
scale.pack()
button = tk.Button(window2, text="Get Scale Value", command=sel)
button.pack()
window2.mainloop()
|
8a19fb662b00b0d8c0059117effacbb3278c4eb2 | vkn84527/100-days-coding-challenge | /2. Add Two Numberslist.py | 922 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a=[]
b=[]
node=l1
node2=l2
while node:
a.append(node.val)
node=node.next
while node2:
b.append(node2.val)
node2=node2.next
a=a[::-1]
b=b[::-1]
s=''
s1=''
for i in a:
s=s+str(i)
for i1 in b:
s1=s1+str(i1)
s2=int(s)+int(s1)
print(s2)
c=[]
for i in str(s2):
c.append(int(i))
c=c[::-1]
dummy=node=ListNode(0)
for i in c:
node.next=ListNode(i)
node=node.next
return dummy.next
|
e05c7afb4c868a3e9951d5a6937b98a139993897 | nothingtosayy/Number-Guessing-Computer- | /main.py | 898 | 3.90625 | 4 | #Number guessing (Computer)
import random as rd
user_number = int(input())
lower_bound = 1 #set by user to computer to check within these limits, your wish any number u can fix as upper_bound
upper_bound = 1000 #set by user to computer to check within these limits,your wish any number u can fix as upper_bound
comp_number = rd.randint(lower_bound,upper_bound)
count = 0
while comp_number != user_number:
if comp_number < user_number:
comp_number = rd.randint(comp_number,user_number)
print(f"{comp_number} too low!")
count = count+1
else:
if comp_number > user_number:
comp_number = rd.randint(user_number,comp_number)
print(f"{comp_number} too high!")
count = count+1
if user_number == comp_number:
print(f"The Number is {comp_number}")
print(f"The Computer Guessed it Correctly at {count}th Iteration")
|
f75d20526df452fbc8185e0de183acb9eee09711 | g10guang/offerSword | /app/idea/sum_solution.py | 1,802 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# author: Xiguang Liu<g10guang@foxmail.com>
# 2018-05-03 15:55
# 题目描述:https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&tqId=11200&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
class Solution:
def Sum_Solution(self, n):
"""
借助 Python 的小 trick
"""
return sum(range(1, n + 1))
class Solution2:
"""
循环可以借助递归栈完成,那么问题就转移为如何判断递归是否应该结束
"""
def __init__(self):
self.result = 0
def Sum_Solution(self, n):
self.result += n
# 借助布尔运算的逻辑短路判断递归结束
n > 0 and self.Sum_Solution(n - 1)
return self.result
class Solution3:
def __init__(self):
self.result = 0
def Sum_Solution(self, n):
"""
借助异常停止递归
"""
try:
t = 1 // n
except ZeroDivisionError:
return self.result
self.result += n
self.Sum_Solution(n - 1)
return self.result
class Solution3:
"""
使用字典映射函数
"""
def __init__(self):
self.result = 0
self.index = 0
self.map = {True: self.recursion, False: self.stop}
def Sum_Solution(self, n):
self.result = 0
self.index = n
self.map[self.index > 0]()
return self.result
def recursion(self):
self.result += self.index
self.index -= 1
self.map[self.index > 0]()
def stop(self):
pass
import unittest
class TestCase(unittest.TestCase):
def setUp(self):
self.s = Solution3()
def test_1(self):
n = 1
r = self.s.Sum_Solution(n)
self.assertEqual(1, r)
|
5aeb7227c5a657ab0ae6f1858527ccfdb64bc866 | yhoazk/hckrnk | /katas/AoC/2019/d1/day1b.py | 813 | 3.78125 | 4 | from fuel_calc import fuel_calc
# calculate the fuel needed to take the fuel
def fuel2fuel(mass):
if mass == 0:
return 0
else:
m = fuel_calc(mass)
# print("mass fuel: {}".format(m))
return m + fuel2fuel(m)
def non_rec_fuel2fuel(mass):
tot = 0
mass = (mass // 3) - 2 # only mass of fuel
while mass > 0:
tot += mass
mass = (mass // 3) - 2
return tot
if __name__ == "__main__":
# print(fuel2fuel(100756)) # = 50346
print(non_rec_fuel2fuel(100756)) # = 50346
acc = 0
acc2 =0
with open("input.log") as data:
for line in data:
acc += fuel2fuel(int(line))
acc2 += non_rec_fuel2fuel(int(line))
print("ans: {}".format(acc)) # ans: 4939939
print("ans2: {}".format(acc2)) # ans: 4939939 |
776e70d1d6f09e0c4aa901f4814fb3ff3192c653 | theresaneate/codewithmosh | /exercises_3.02_accessinglists.py | 957 | 4.34375 | 4 | #!/usr/bin/env python3
# https://codewithmosh.com/courses/423295/lectures/6781740
numbers = list(range(20))
print(numbers)
print(numbers[0])
print(numbers[-1])
numbers[4] = 100
print(numbers)
for n in numbers:
print(n)
newrange = tuple(range(3, 6))
print("\nNaughty tuple. Range from 3 to 6:")
print(type(newrange))
print(newrange)
for n in newrange:
print(n)
jump2 = list(range(3, 20, 2))
print("\nJump 2:")
for n in jump2:
print(n)
startat1 = list(range(1, 20))
print("\nStart at 1:")
for n in startat1:
print(n)
print("\nIndexing 0:3 using the above list: ")
print(startat1[0:3])
print("\nIndexing :3 using the above list: ")
print(startat1[:3])
print("\nIndexing 0: using the above list: ")
print(startat1[0:])
print("\nIndexing : using the above list: ")
print(startat1[:])
print("\nIndexing 1::2 step using the above list: ")
print(startat1[1::2])
print("\nIndexing ::-1 step using the above list: ")
print(startat1[::-1])
|
e8f31e13e04282d5b79fb4e73f39ec359d2172d4 | RoshikDiana/home_work_python | /Lesson_1/task_5.py | 1,570 | 4.03125 | 4 | # Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
revenue = float(input("Введите выручку фирмы "))
expenses = float(input("Введите расходы фирмы "))
if revenue > expenses:
print(f"фирма работает в прибыль. Прибыль фирмы составила {revenue - expenses}")
print(f"Рентабельность выручки {(revenue - expenses) / revenue : .2f}")
workers = int(input("Введите количество сотрудников фирмы "))
print(f"прибыль в расчете на одного сторудника сотавила {revenue / workers: .2f}")
elif revenue == expenses:
print("Фирма работает в ноль")
else:
print("Фирма работает в убыток")
|
0232bd5969437545300c86b123795da4f6844f5c | gracekim17/studyCS | /LearnPython/madlibs.py | 266 | 4.03125 | 4 |
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
celebrity = input("Enter a celebrity name: ")
print("Roses are " + color.lower())
print(plural_noun.lower().capitalize() + " are blue")
print("I love " + celebrity.lower().capitalize())
|
06b4e593ebf992b1cf67c7f09c276324f0fcc43b | cvmsprogclub/2016-cyoas | /adventure1234567890.py | 5,189 | 4.15625 | 4 | print("You are stranded on a island")
print("press a to climb a tree")
print("press b to start swimming")
print("press c to scope the island")
print("press d to drink coconut water")
user_choice = input()
if user_choice == "c" :
print("you scope the island")
print("you find flint")
print("Do you want to pick up the flint and use it? (y/n)")
user_choice = input()
if user_choice == "n":
print("you die of hypothermia")
elif user_choice == "y":
print("You survive the night")
print("you wake up and see smoke you think it is the airplane but then you hear some one yell help")
print("do you go and help this person? (y/n)")
user_choice = input()
if user_choice == "n":
print("You here a person die of the heat")
print("you feel guilty and kill yourself by jumping into the fire you had from the previous night")
elif user_choice == "y":
print("You go and find your childhood friend Jim Bob Cooter")
print("he starts acting like a savage")
print("You try and help him")
print("HE KILLS YOU!!!!!")
elif user_choice == "b" :
print("you start swimming")
print("You are surrounded by sharks")
print("Do you want to ride a shark? (y/n)")
user_choice = input()
if user_choice == "y":
print("You get bucked of and die")
elif user_choice == "n":
print("You die while trying to escape")
elif user_choice == "a" :
print("you climb a tree")
print("you see pinapples at the top")
print("Do you wish to drop the pinapples on the ground? (y/n)")
user_choice = input()
if user_choice == "y":
print("You lose your balance and fall off the tree and die")
elif user_choice == "n":
print("you slide down the tree and think about what to do")
print("You see a pinapple on the ground")
print("Do you wish to eat it? (y/n)")
user_choice = input()
if user_choice == "y":
print("Oh no it was a rotten pinapple")
print("You die of food poisoning")
elif user_choice == "n":
print("You use the pinapple as a trap")
print("You capture a turtle")
print("Do you want to eat the turtle? (y/n)")
user_choice = input()
if user_choice == "y":
print("You die of food posioning initially from the pinapple")
elif user_choice == "n":
print("you put the turtle in the ocean doget on it? (y/n)?")
user_choice = input()
if user_choice == "y":
print("you are two heavy and drown you die")
elif user_choice == "n":
print("You kill yourself because you did not get on the turtle")
elif user_choice == "d" :
print("you drink coconut water")
print("Do you want to run now? (y/n)", end=' ')
user_choice = input()
if user_choice == "n":
print("you die of nothing to do")
elif user_choice == "y":
print("you find a crashed burning airplane")
print("Do you run into the airplane? (y/n)", end=' ')
user_choice = input()
if user_choice == "y":
print("You die of the heat")
elif user_choice == "n":
print("You survive Yay!!!!")
print("you see a parachute")
print("do you try to fly with the parachute? (y/n)")
user_choice = input()
if user_choice == "y":
print("You get in the air but lose your grip on the parachute then fall into the burning plane")
elif user_choice == "n":
print("You use the parachute as a fishing net")
print("You catch five fish")
print("You go back to the burning airplane to cook them")
print("you see a flare gun do you pick it up? (y/n)")
user_choice = input()
if user_choice == "n":
print("you see a helicopter pass by and you kill yourself because you didn't pick up")
elif user_choice == "y":
print("you take the flare gun back to your campsite")
print("do you shoot the flare gun? (y/n)")
user_choice = input()
if user_choice == "y":
print("You kill yourself because you relize you only had one shot")
elif user_choice == "n":
print("you save your shot")
print("you figure out you only have one shot")
print("when you wake up you hear and see a helicopter")
print("You shoot your flare gun and the helicopter comes down")
print("Do you get on? (y/n)")
user_choice = input()
if user_choice == "n":
print("you kill your self because you didn't get on the helicopter")
elif user_choice == "y":
print("you get on the helicopter and leave the island")
print("YOU WIN")
|
6415717d86462c5c0e2d68b41a49f0fb97489f87 | aimuch/AITools | /PreProcess/video2pic1.py | 4,141 | 3.5 | 4 | # -*- coding: utf-8 -*-
### Author : Andy
### Last modified : 2019-05-15
### This tool is used to split videos into images(video_folder/video.h264)
### ----------------EXAMPLE-------------------
### python3 video2pic1.py \
### home/andy/data/train/video_folder \
### home/andy/data/train/output_folder --cuts 1 --show False --interval 10
### -----------------Video Folder Tree---------------------
### The tree of video_folders:
### video_folder:
### -- video1.avi
### -- video2.avi
### -- video3.avi
import os
import cv2
import sys
import shutil
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('video_dir', help='video files directory', type=str)
parser.add_argument('output_dir', help='output images directory ', type=str)
parser.add_argument('--interval', help='take one in every interval frames', default=10, type=int)
parser.add_argument('--cuts', help='num camera in one video', default=1, type=int)
parser.add_argument('--show', help='num camera in one video', default=False, type=bool)
args = parser.parse_args()
return args
def video2pic(video_path, output_dir, interval, cuts=1, show=False):
# folder_info = os.path.split(video_path) # [文件夹, 视频]
video_name = os.path.basename(video_path) # video.avi
video_infor = video_name.split(".") # [video, avi]
# print(folder_info)
# print(video_name)
# print(video_infor)
if video_infor[-1] != "h264" and video_infor[-1] != "mkv" and video_infor[-1] != "mp4" and video_infor[-1] != "avi":
print("文件夹下有非视频文件,请检查!")
return
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print("Create video folder: ", output_dir)
## set dst video folder
output_folder = os.path.join(output_dir, video_infor[0])
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
os.makedirs(output_folder)
cap = cv2.VideoCapture(video_path)
fps = cap.get(5) # CV_CAP_PROP_FPS
print("Frame per second : %s , interval : %s"%(fps, interval))
retval, frame = cap.read()
frame_num = 0
count = 0
rows = []
if cuts > 1:
step = frame.shape[0] // cuts
print("Cut step = ", step)
for i in range(cuts):
rows.append(i*step)
rows.append(frame.shape[0])
print("Cuts list = ", rows)
while retval:
if frame_num%interval == 0:
count += 1
if cuts == 1:
pic_name = video_infor[0] + "_" +str(count).zfill(5) + ".jpg"
# pic_name = video_infor[0] + "_" +str(count).zfill(5) + ".png"
pic_path = os.path.join(output_folder, pic_name)
cv2.imwrite(pic_path, frame)
if show:
win = cv2.namedWindow('Clip Show', flags=cv2.WINDOW_AUTOSIZE)
cv2.imshow('Clip Show', frame)
cv2.waitKey(5)
else:
for i in range(cuts):
pic_name = video_infor[0] + "_" +str(count).zfill(5) + "_" + str(i) + ".jpg"
# pic_name = video_infor[0] + "_" +str(count).zfill(5) + "_" + str(i) + ".png"
pic_path = os.path.join(output_folder, pic_name)
cv2.imwrite(pic_path, frame[rows[i]:rows[i+1], :])
if show:
win = cv2.namedWindow('Clip Show', flags=cv2.WINDOW_AUTOSIZE)
cv2.imshow('Clip Show', frame[:, :, i])
cv2.waitKey(5)
frame_num +=1
retval, frame = cap.read()
if show:
cv2.destroyAllWindows()
cap.release()
print(video_path, " done!")
if __name__ == '__main__':
args = parse_args()
video_dir = args.video_dir
output_dir = args.output_dir
cuts = args.cuts
interval = args.interval
if not os.path.exists(video_dir):
print("Error !!! %s is not exists, please check the parameter"%video_dir)
sys.exit(0)
video_list = os.listdir(video_dir)
video_num = len(video_list)
for i, video in enumerate(os.listdir(video_dir)):
video_path = os.path.join(video_dir, video)
print(">>> {}/{}".format((i+1), video_num), end=", ")
video2pic(video_path, output_dir, interval, cuts, False)
|
f21d46f6627e29b6421470569b5ee2a7ec92b955 | flcavqueiroz/caelum | /jogos/forca.py | 4,414 | 3.5 | 4 | import random
def jogar():
titulo()
palavra_secreta = carrega_palavra_secreta()
letra_acertada = inicializa_letra_acertada(palavra_secreta)
print(letra_acertada)
acertou = False
errou = False
num_erros = 0
while(not errou and not acertou):
chute = pede_chute()
if chute in palavra_secreta:
marca_chute_correto(chute, letra_acertada, palavra_secreta)
else:
num_erros += 1
desenha_forca(num_erros)
errou = num_erros == 7
acertou = '_' not in letra_acertada
print(letra_acertada)
if acertou:
imprime_mensagem_vencedor()
else:
imprime_mensagem_perdedor(palavra_secreta)
#print(palavra_secreta)
""" acertou = '_' not in letra_acertada
errou = num_erros == len(letra_acertada)
print(letra_acertada)
if (acertou):
print('Você acertou!')
else:
print('Você atingiu o limite de tentativas!')
print('Fim do Jogo') """
def titulo():
print('*' * 30)
print(' ' * 7, 'Jogo da Forca')
print('*' * 30)
def carrega_palavra_secreta():
with open('palavra.txt', 'r') as arquivo:
palavras = [l.strip() for l in arquivo]
"""for l in arquivo:
palavras.append(l.strip()) """
num = random.randrange(0, len(palavras))
palavra_secreta = palavras[num].lower()
return palavra_secreta
def inicializa_letra_acertada(palavra_secreta):
return ['_' for l in palavra_secreta]
def pede_chute():
chute = input('Digite uma letra: ').lower()
return chute
def marca_chute_correto(chute, letra_acertada, palavra_secreta):
posicao = 0
for letra in palavra_secreta:
if letra == chute:
#print(f'Encontrei a letra {letra} na posicao {posicao}')
letra_acertada[posicao] = letra
posicao += 1
def imprime_mensagem_perdedor(palavra_secreta):
print('Puxa, você foi enforcado!')
print(f'A palavra era {palavra_secreta}')
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
def imprime_mensagem_vencedor():
print('Parabéns, você ganhou!')
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
def desenha_forca(num_erros):
print(" _______ ")
print(" |/ | ")
if(num_erros == 1):
print(" | (_) ")
print(" | ")
print(" | ")
print(" | ")
if(num_erros == 2):
print(" | (_) ")
print(" | \ ")
print(" | ")
print(" | ")
if(num_erros == 3):
print(" | (_) ")
print(" | \| ")
print(" | ")
print(" | ")
if(num_erros == 4):
print(" | (_) ")
print(" | \|/ ")
print(" | ")
print(" | ")
if(num_erros == 5):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | ")
if(num_erros == 6):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if (num_erros == 7):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
|
bec2b42406ca14abccfe079908f6de82b0650598 | emmelles/cs101_into-comp-sci | /14-04_freq_analysis.py | 466 | 3.5625 | 4 | #!/usr/bin/env python
alphabet=list("abcdefghijklmnopqrstuvwxyz")
def freq_analysis(message):
freq_list=[]
for x in alphabet:
freq_list.append(list(message).count(x)*1.0/len(list(message)))
return freq_list
#Tests
print freq_analysis("abcd")
#>>> [0.25, 0.25, 0.25, 0.25, 0.0, ..., 0.0]
print freq_analysis("adca")
#>>> [0.5, 0.0, 0.25, 0.25, 0.0, ..., 0.0]
print freq_analysis('bewarethebunnies')
#>>> [0.0625, 0.125, 0.0, 0.0, ..., 0.0]
|
37d57210f6dc895094b3728cc632d09eeb028b28 | Katy-katy/titanic_machine_learing_python_pandas_sklearn | /work.py | 14,241 | 3.640625 | 4 | """ Working skript for the project "Titanic"
Author : Ekaterina Tcareva
Date : 8rd March 2016
Our goal is to build a prediction on surviving Titanic passengers.
We have some information about passengers (train.csv):
PassengerId -- A numerical id assigned to each passenger.
Survived -- Whether the passenger survived (1), or didn't (0). We'll be making predictions for this column.
Pclass -- The class the passenger was in -- first class (1), second class (2), or third class (3).
Name -- the name of the passenger.
Sex -- The gender of the passenger -- male or female.
Age -- The age of the passenger. Fractional.
SibSp -- The number of siblings and spouses the passenger had on board.
Parch -- The number of parents and children the passenger had on board.
Ticket -- The ticket number of the passenger.
Fare -- How much the passenger paid for the ticker.
Cabin -- Which cabin the passenger was in.
Embarked -- Where the passenger boarded the Titanic.
"""
import pandas
import numpy as np
from sklearn.cross_validation import KFold
from sklearn import cross_validation
from sklearn import linear_model
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from matplotlib import pyplot as plt
from matplotlib import style
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.ensemble import GradientBoostingClassifier
# Data cleanup
# TRAIN DATA
titanic = pandas.read_csv("train.csv")
# Fill NAN
titanic['Age'] =titanic['Age'].fillna(titanic['Age'].median())
titanic['Parch'] =titanic['Parch'].fillna(titanic['Parch'].median())
titanic['SibSp'] =titanic['SibSp'].fillna(titanic['SibSp'].median())
titanic['Sex'] = titanic['Sex'].fillna('male')
# Replace all the occurences of male with the number 0, female 1.
titanic.loc[titanic["Sex"] == "male", "Sex"] = 0
titanic.loc[titanic["Sex"] == "female", "Sex"] = 1
titanic["Embarked"] = titanic["Embarked"].fillna('S')
titanic.loc[titanic["Embarked"]=='S', "Embarked"] = 0
titanic.loc[titanic["Embarked"]=='C', "Embarked"] = 1
titanic.loc[titanic["Embarked"]=='Q', "Embarked"] = 2
#Now we try different models and check which one is the best fit
#We started with Logistic regression using cross validation (3 folders) from “sklearn”:
#we are using almost all features except “name”, “cabin”, and “ticket” since we have too much NA
# for “cabin” and we do not know what the numbers of “ticket” and letters mean
alg =linear_model.LogisticRegression(random_state=1)
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
# Take the mean of the scores (because we have one for each fold)
print("Logistic reg with cross validation using [Pclass, Sex, Age, SibSp, Parch, Fare, Embarked]")
print(scores.mean())
# 0.787878787879
# now let's try same predictors but without cross validation (we use whole dataset to fit the algorithm)
alg.fit(titanic[predictors], titanic["Survived"])
predictions = alg.predict_proba(titanic[predictors].astype(float))[:,1]
predictions[predictions <= .5] = 0
predictions[predictions > .5] = 1
accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)
print("Logistic reg WITHOUT cross validation using [Pclass, Sex, Age, SibSp, Parch, Fare, Embarked]")
print(accuracy)
# 0.799102132435
#Since 0.799 is bigger than 0.788 we suggest that we have some overfitting. Thus, we can try to use few features.
#Next we wanted to explore which of the features are more correlated with the labels.
# We used Logistic regression for only one feature with cross validation.
scores = cross_validation.cross_val_score(alg, titanic[["Pclass"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Pclass only")
print(scores.mean())
#0.679012345679
scores = cross_validation.cross_val_score(alg, titanic[["Sex"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Sex only")
print(scores.mean())
#0.786756453423
scores = cross_validation.cross_val_score(alg, titanic[["Age"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Age only")
print(scores.mean())
#0.616161616162
scores = cross_validation.cross_val_score(alg, titanic[["Embarked"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Embarked only")
print(scores.mean())
#0.594837261504
scores = cross_validation.cross_val_score(alg, titanic[["Fare"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Fare only")
print(scores.mean())
#0.672278338945
scores = cross_validation.cross_val_score(alg, titanic[["SibSp"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using SibSp only")
print(scores.mean())
#0.616161616162
scores = cross_validation.cross_val_score(alg, titanic[["Parch"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using Parch only")
print(scores.mean())
#0.607182940516
#We can see that logistic regression with only “Sex” feature gives us almost the same accuracy as with all features!
#“Pclass” and “Fare” gave us almost the same prediction and hence we can suggest that they are very closely related to each other.
# Thus, we decided to check their relation. We tried to predict “Fare” using logistic regression and “Pclass” feature:
scores = cross_validation.cross_val_score(alg, titanic[["Fare"]], titanic["Pclass"], cv=3)
print("Logistic reg to predict Pclass using only Fare feature with cross validation")
print(scores.mean())
#0.693573836191 It was surprising, but they do not have a strong correlation. Hence we could use them both.
#Remember - we had overfitting when we used
#predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
#To avoid overfitting we run logistic regression using only three features:
predictors = ["Pclass", "Sex", "Fare"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using [Pclass, Sex, Fare]")
print(scores.mean())
#0.780022446689
# now let's try same predictors but without cross validation (we use whole dataset to fit the algorithm)
alg.fit(titanic[predictors], titanic["Survived"])
predictions = alg.predict_proba(titanic[predictors].astype(float))[:,1]
predictions[predictions <= .5] = 0
predictions[predictions > .5] = 1
accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)
print("Logistic reg WITHOUT cross validation using [Pclass, Sex, Fare]")
print(accuracy)
#0.785634118967 the results with and without cross validation is almost same. Thus, now we avoid overfitting using few features.
#At the beginning of our work we decided to create a new feature “famillySize”. Thus, we are creating it:
titanic["FamilySize"] = titanic["SibSp"] + titanic["Parch"]
scores = cross_validation.cross_val_score(alg, titanic[["FamilySize"]], titanic["Survived"], cv=3)
print("Logistic reg with cross validation using FamilySize only")
print(scores.mean())
#0.612794612795 So, this new feature is not very related with our labels.
#Next we tried Naive Bayes since we can suggest that most of the features in the data set are independent
# (we did not use “Fare” since we will be using “Pclass”):
alg = GaussianNB()
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Embarked"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("Naive Bayes with cross validation using [Pclass, Sex, Age, SibSp, Parch, Embarked]")
print(scores.mean())
#0.765432098765
predictors = ["Pclass", "Sex", "Age"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("Naive Bayes with cross validation using [Pclass, Sex, Age]")
print(scores.mean())
#0.777777777778 The result is worser than the result we got using Logistic Regression.
# So, we decided to not explore this model deeper.
#Random Forest
alg = RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=4, min_samples_leaf=2)
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "FamilySize"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("Random Forest with cross validation using [Pclass, Sex, Age, SibSp, Parch, Fare, Embarked, FamilySize]")
print(scores.mean())
#0.817059483726
alg.fit(titanic[predictors], titanic["Survived"])
predictions = alg.predict_proba(titanic[predictors].astype(float))[:,1]
predictions[predictions <= .5] = 0
predictions[predictions > .5] = 1
accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)
print("Random Forest WITHOUT cross validation using [Pclass, Sex, Age, SibSp, Parch, Fare, Embarked, FamilySize]")
print(accuracy)
#0.918069584736 It is better than using logistic regression, but it is clear that we have overfitting again.
# Thus, we need to use fewer features.
# Also we think that we need to split the “Age” feature into some groups. For example: 0 -13, 13-17, 18-25, 26-50, 51-80.
# To find the best split we use matplotlib to plot the data:
survivedByAge = titanic.groupby('Age')['Survived'].sum()
numberPasByAge = titanic.groupby('Age')['Survived'].count()
numberDiedByAge = numberPasByAge - survivedByAge
a = numberPasByAge.index.values.tolist()
d = numberDiedByAge.values.tolist()
s = survivedByAge.values.tolist()
# now we can plot d and c vs. age
style.use('ggplot')
x = a
y = s
x2 = a
y2 = d
plt.figure(1)
plt.plot(x,y,'bo', label = 'Survived')
plt.plot(x2,y2,'rx', label ='Died')
plt.legend(loc='upper left')
plt.title('Survived vs. Died')
plt.ylabel('Number of people')
plt.xlabel('Age')
#plt.show()
#Looking at this graph we decided to split the “Age” into three groups: <15, 16-30, >31
#Then we created a new feature “AgeGroup”: 0 for persons < 16, 1 for persons between 16 and 31,
# and 2 for persons older than 31.
titanic.loc[titanic['Age'] < 16, 'AgeGroup'] = 0
titanic.loc[titanic['Age'] >= 16,'AgeGroup'] = 1
titanic.loc[titanic['Age'] >= 31,'AgeGroup'] = 2
# Now we can try SelectKBest in from to find the best features:
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked", "FamilySize", "AgeGroup"]
# Perform feature selection
selector = SelectKBest(f_classif, k=5)
selector.fit(titanic[predictors], titanic["Survived"])
# Get the raw p-values for each feature, and transform from p-values into scores
scores = -np.log10(selector.pvalues_)
# Plot the scores. See how "Pclass", "Sex", "Title", and "Fare" are the best?
plt.figure(2)
plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
#plt.show()
#From the graph we see that Sex, Pclass, and Fare are the most important features!
#And we realised that “AgeGroup” is less important than age.
#Using this information we tried some combinations of features and got the best result using:
predictors = ["Pclass", "Sex", "Age", "Parch", "Fare", "Embarked"]
scores = cross_validation.cross_val_score(alg, titanic[predictors], titanic["Survived"], cv=3)
print("Random Forest with cross validation using [Pclass, Sex, Age, Parch, Fare, Embarked]")
print(scores.mean())
#0.82379349046
#Next, to improve our model, we used GradientBoostingClassifier (we used the random forest with the same set of features).
algorithms = [
[GradientBoostingClassifier(random_state=1, n_estimators=25, max_depth=3), predictors],
[RandomForestClassifier(random_state=1, n_estimators=150, min_samples_split=4, min_samples_leaf=2), predictors]]
# Initialize the cross validation folds
kf = KFold(titanic.shape[0], n_folds=3, random_state=1)
predictions = []
for train, test in kf:
train_target = titanic["Survived"].iloc[train]
full_test_predictions = []
# Make predictions for each algorithm on each fold
for alg, predictors in algorithms:
alg.fit(titanic[predictors].iloc[train,:], train_target)
# Select and predict on the test fold.
test_predictions = alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]
full_test_predictions.append(test_predictions)
test_predictions = (full_test_predictions[0] + full_test_predictions[1]) / 2
test_predictions[test_predictions <= .5] = 0
test_predictions[test_predictions > .5] = 1
predictions.append(test_predictions)
predictions = np.concatenate(predictions, axis=0)
accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)
print("GradientBoostingClassifier with cross validation using [Pclass, Sex, Age, Parch, Fare, Embarked]")
print(accuracy)
#0.824915824916 The result is slightly better than the result we got by just using Random Forest with the same parameters.
#We submitted this result on Kaggle and it gave us 2392nd/3616 and about 0.777 accuracy.
# We realized we had overfitting again! Hence we decided to try the same algorithms with few features:
predictors = ["Pclass", "Sex", "Fare", "Embarked"]
predictions = []
for train, test in kf:
train_target = titanic["Survived"].iloc[train]
full_test_predictions = []
# Make predictions for each algorithm on each fold
for alg, predictors in algorithms:
alg.fit(titanic[predictors].iloc[train,:], train_target)
# Select and predict on the test fold.
test_predictions = alg.predict_proba(titanic[predictors].iloc[test,:].astype(float))[:,1]
full_test_predictions.append(test_predictions)
test_predictions = (full_test_predictions[0] + full_test_predictions[1]) / 2
test_predictions[test_predictions <= .5] = 0
test_predictions[test_predictions > .5] = 1
predictions.append(test_predictions)
predictions = np.concatenate(predictions, axis=0)
accuracy = sum(predictions[predictions == titanic["Survived"]]) / len(predictions)
print("GradientBoostingClassifier with cross validation using [Pclass, Sex, Fare, Embarked]")
print(accuracy)
#0.824915824916
# We submitted submitted.py file which used this algorithm and this set of features.
# We got 891st/3661 (0.79904 accuracy)
#https://www.kaggle.com/etcareva/results
|
0deb240a7d0b582e9615a067cfd0cdab4ad0a1f7 | JerryHu1994/LeetCode-Practice | /Solutions/82-Remove-Duplicates-from-Sorted-List-II/python.py | 1,008 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
if head == None: return None
curr = dummy
right = dummy.next
currval = right.val
currcount = 1
while right.next != None:
right = right.next
if currval == right.val:
currcount += 1
else:
if currcount == 1:
curr = curr.next
else:
curr.next = right
currcount = 1
currval = right.val
# in the end, if the last run has counts larger than one, end it
if currcount > 1:
curr.next = None
return dummy.next
|
d01713b1064b03b26b9be3b08ffb55fcde97bf28 | vladimir713/Fibonnachi | /main.py | 791 | 3.90625 | 4 | #!/usr/bin/env python3
#----------------------------------------------------------------
# Вычисление ряда четных чисел Фибоначи тремя разными способами
#-----------------------------------------------------------------
def f(n):
a = [0, 1]
for i in range(2, 3*n):
a.append(a[i-2]+a[i-1])
return [i for i in a if i%2 == 0]
def f2(n):
a, b = 0, 1
for __ in range(n):
yield a
a,b = b, a+b
def f3(n):
fib = [0]
a, b = 0, 1
def ff(n, a, b):
a, b = b, a + b
fib.append(a)
if n:
ff(n-1, a, b)
ff(n*3-2, a, b)
return [i for i in fib if i%2 == 0]
items = 8 #Количество выводимых четных значений
print (f(items))
print ([i for i in list(f2(items*3)) if not(i%2)])
print(f3(items)) |
0a167778505ac8c7a38d727ff4cec68dbd82fab0 | shahpranaf/python-blockchain | /assignment/assignment1.py | 328 | 3.71875 | 4 | name = "Pranav"
age = 29
def print_data() :
print("My name is: " + name + " age is: " + str(age))
def print_data_arg(name, age) :
print("My name is: " + name + "-" + str(age))
def decades_calc(time) :
#return time//10
return int(int(age)/10)
print_data()
print_data_arg("abc", 20)
print(decades_calc(32.32)) |
8f173acfa5bbe93895862b5d8882a43e9db7e757 | stacygo/2021-01_UCD-SCinDAE-EXS | /04_Regular-Expressions-in-Python/04_ex_1-12.py | 377 | 4 | 4 | # Exercise 1-12: Replacing negations
movies = "the rest of the story isn't important because all it does is serve as a mere backdrop for the two stars to share the screen ."
# Replace negations
movies_no_negation = movies.replace("isn't", "is")
# Replace important
movies_antonym = movies_no_negation.replace("important", "insignificant")
# Print out
print(movies_antonym)
|
8352e19238706a429c4d9822742554af4200b576 | chinitacode/Python_Learning | /Tencent_50/46_Longest_Common_Prefix.py | 7,222 | 3.921875 | 4 | '''
14. Longest Common Prefix [Easy]
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
[Method 1]: 取input list里最后一个字符串作为比较的reference,
从其第一位字符开始,比较剩下list里每个字符串相应的位数,只要出现问题(位数不够)或者结果不相等,
就立刻返回prefix字符串。
Time: O(m(n-1)), m为input list里最后一个字符串的长度,n为input list里元素个数;
Space: O(1)
Runtime: 40 ms, faster than 72.36% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.7 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.
'''
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) < 1: return ''
prefix = ''
refer = strs[-1]
strs.pop()
i = 0
for char in refer:
for word in strs:
if i > len(word) - 1 or char != word[i]: return prefix
prefix += char
i += 1
return prefix
'''
[Optimization]: 选取input list里面长度最短的字符串作为比较的参照,然后对每个字符串相应位数进行比较。
Time: O(m + mn), m为最短字符串长度,n为字符串个数;
Space: O(1)
Runtime: 36 ms, faster than 91.36% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.7 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.
'''
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) < 1: return ''
prefix = ''
refer = min(strs, key = len)
for i, char in enumerate(refer):
for word in strs:
if char != word[i]: return prefix
prefix += char
return prefix
'''
[Method 2]: Divide and Conquer
Time: O(mn),最坏情况下,我们有n个长度为m的相同字符串,每两个字符串都需要比较;
如果input是9个字符串,那么实际上会进行8次比较,每次比较都会比较m个字符(最坏)。
Space: O(mn)
Runtime: 44 ms, faster than 40.31% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.6 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.
'''
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ''
if len(strs) == 1: return strs[0]
if len(strs) == 2:
prefix = ''
for (s1,s2) in zip(strs[0],strs[1]):
if s1 != s2: return prefix
prefix += s1
return prefix
left = self.longestCommonPrefix(strs[:len(strs)//2])
right = self.longestCommonPrefix(strs[len(strs)//2:])
return self.longestCommonPrefix([left, right])
#或者不用slicing:
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs == []:
return ''
def comparetwo(a,b):
result = ''
for m,n in zip(a,b):
if m == n:
result += m
else:
return result
return result
def divide(start,end):
mid = int((start + end)/2)
if mid == start and mid == end:
return strs[mid]
elif mid == start and mid != end:
return comparetwo(strs[start],strs[end])
else:
a = divide(start,mid)
b = divide(mid+1,end)
return comparetwo(a,b)
return divide(0,len(strs)-1)
'''
[Method 3] Python zip() and set()
【第一行】每次都取各个字符串的同一列字符,放进 set,set 中不会储存重复元素,所以长度为1代表各个字符都是相同的,此时 == 会让它变成 True
【第二行】index 搜索第一个 0 的位置,0 与 False 在值上是等价的,相当于搜索第一个 False 的位置也就是公共前缀的长度
Time: O(m(nm)), set()需要O(m),m为input list里字符串个数,zip()则需要O(mn),n为最短字符串的长度。
[Note]: 关于zip()的时间复杂度:
1.可以将它看作一个循环,向zip添加一个参数将在每次迭代中添加O(1),
或者在所有n迭代中添加O(n)。(假设最小参数的大小为n)
例如,对于zip(X1,X2,...,Xm),您正在做O(mn)的工作,
但是m是常量,所以它是O(n)。(再次假设参数的最小大小为n)
2.zip(*args)的运行时间为O(len(args) * min(len(a) for a in args)。
如果没有对参数(例如,列表的数量(len(args))是常量)的特定假设,就不能将其归结为O(n))。
如果列表的长度都相同,那么可以使用单个长度n来代替最小长度的计算,
并使用m来表示列表的数量,并将其写成O(m * n)。
如果列表的数量不变,那么m的因数是一个常量,可以删除,只留下O(n)。
Runtime: 36 ms, faster than 91.30% of Python3 online submissions for Longest Common Prefix.
Memory Usage: 13.9 MB, less than 6.67% of Python3 online submissions for Longest Common Prefix.
'''
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = [len(set(chars)) == 1 for chars in zip(*strs)] + [0]
return strs[0][:res.index(0)] if strs else ''
'''
把代码展开相当于:
'''
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ""
for tmp in zip(*strs):
tmp_set = set(tmp)
if len(tmp_set) == 1:
res += tmp[0]
else:
break
return res
'''
[Method 4]:
按字典排序数组,比较第一个,和最后一个单词,有多少前缀相同。
如['flower', 'flow', 'flight'],按字典序排序后变成了['flight', 'flow', 'flower'],
列表首位和末位为差别最大的两个字符串,只需要比较这两个即可。
Time: O(nlogn + m)
'''
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ''
strs.sort()
a = strs[0]
b = strs[-1]
prefix = ''
for (c1,c2) in zip(a,b):
if c1 != c2: break
prefix += c1
return prefix
#或者不用zip()
class Solution:
def longestCommonPrefix(self, s: List[str]) -> str:
if not s:
return ""
s.sort()
n = len(s)
a = s[0]
b = s[n-1]
res = ""
for i in range(len(a)):
if i < len(b) and a[i] == b[i]:
res += a[i]
else:
break
return res
|
23d8562ec8a10caa237d4544bb07cfefbb6fcd7f | harjothkhara/computer-science | /Sprint-Challenge--Data-Structures-Python/names/binary_search_tree.py | 2,610 | 4.1875 | 4 |
class BinarySearchTree: # a single node is a tree
def __init__(self, value): # similar to LL/DLL
self.value = value # root at each given node
self.left = None # left side at each given node
self.right = None # right side at each given node
# Insert the given value into the tree
def insert(self, value):
# compare the root value to the new value being added
# if the value is less than the root, move left
if value < self.value:
# if no child on that side insert
if self.left is None:
# creating a new class instance
self.left = BinarySearchTree(value) # a single node is a tree
# else keep moving left and call insert method again (on left) and do the check again until no child, and you can insert value to the tree
else:
self.left.insert(value)
# if the value is greater than the root, move right
elif value >= self.value:
# if no child on that side insert
if self.right is None:
# creating a new class instance
self.right = BinarySearchTree(value) # a single node is a tree
# else keep moving right and call insert method again (on right) and do the check again until no child, and you can insert value to the tree
else:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# look at root and compare it to the target
# if the target is less than the current node value,
if target < self.value:
# move left, if value exists repeat
if self.left is not None:
# recurse left side until target is found
return self.left.contains(target)
else:
return False
# if target is greater than the current node value, move right and repeat
elif target > self.value:
# move right, if value exists repeat
if self.right is not None:
# recurse right side until target is found
return self.right.contains(target)
else:
return False
# if the target equals the value return True - basecase
elif target == self.value:
return True
bst = BinarySearchTree(1)
bst.insert(8)
bst.insert(5)
bst.insert(7)
bst.insert(6)
bst.insert(3)
bst.insert(4)
bst.insert(2)
# bst.in_order_print(print)
# bst.dft_print(print)
# bst.bft_print(print)
|
d72640be1a32dbc51ebc7266e4f921b314a19c0c | Ebuyuktas/python-3-Hafta-Odev | /soru2.py | 633 | 3.765625 | 4 | #3. Hafta 2. Soru
#Sayı Tahmin Programı
sayi = 15
tahmin = 0
deneme_sayisi = 0
while sayi != tahmin:
try:
tahmin = int(input("Tahmininizi söyleyin(1-100 arası): "))
deneme_sayisi += 1
if tahmin > 100 or tahmin < 0:
print("Lütfen doğru aralıkta tahmin giriniz.")
elif tahmin > sayi:
print("Fazla attın, azalt")
elif tahmin < sayi:
print("Artır, çok az geldi")
else:
print("Bildin.")
except:
print("Hata oluştu. Lütfen sayı giriniz")
print(deneme_sayisi, ". denemede bildiniz.", sep="")
|
16fec28fb80d03b58f3d0bb6edf90323339e7819 | sachinlalms/python | /venv/Scripts/methodoverhiding.py | 624 | 4.09375 | 4 | #Inheritance
class BaseClass:
def __init__(self):
print("Base Init")
def set_name(self,name):
self.name=name
print("Base Class Set_name")
class Subclass(BaseClass):
def __init__(self):
super().__init__()
print("Sub class init") #constuctor over_riding
def set_name(self,name):
self.name=name #method over
super().set_name(name)
print("Sub Class Set_name")
def welcome(self):
print("Welcome")
def dispaly_name(self):
print("Name:"+self.name)
y=Subclass()
y.welcome()
y.set_name("Sachin")
y.dispaly_name() |
3b1398758f13f3dfa5b312e3e4029cc659bdc215 | nicksmd/leet-code | /Lets-code/566. Reshape the Matrix.py | 974 | 3.5625 | 4 | class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
n = len(nums)
m = len(nums[0])
if n*m != r*c:
return nums
else:
one_d_array = [item for row in nums for item in row]
new_array = []
print one_d_array
count = 0
for i in range(0,r):
new_array.append([])
for j in range(0,c):
new_array[len(new_array)-1].append(one_d_array[count])
count+=1
return new_array
s = Solution().matrixReshape([[1,2],[3,4]],1,4)
print s
s = Solution().matrixReshape([[4,3,0],[0,2,1]],3,4)
print s
s = Solution().matrixReshape([[4,3,1,2]],2,2)
print s
s = Solution().matrixReshape([[4,3,1,2]],4,1)
print s
s = Solution().matrixReshape([[4,3],[1,2]],1,4)
print s
|
5bfcc5d8111b437bb000b126d49cf7ec9e218af0 | septyandy08/basic_python | /break_test.py | 222 | 4.03125 | 4 | text = input()
while True:
if text == "start":
print("Starting program...")
elif text == "stop":
print("Program has stopped...")
break
print("text: {}".format(text))
text = input()
|
a71cac88bc7ffd231e8a54b91b951d0348feab6d | Jason-Custer/100-days-of-code | /basic-calculator/basic-calculator.py | 1,143 | 4.25 | 4 | # Calculator Program
# Variables:
x = 1
y = 1
# Functions:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
functions = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
}
def calculator():
from art import logo
print(logo)
# Input the first number in the calculator:
x = float(input("What is the first number? "))
# Choose the type of operator:
another_calculation = True
while another_calculation == True:
for symbol in functions:
print(symbol)
operator = input("Select the operator:\n")
y = float(input("What is the next number? "))
calculation = functions[operator]
result = calculation(x, y)
print(f"{x} {operator} {y} = {result}")
response = input(f"Type 'y' to continue with {result} or 'n' to calculate something else: ")
if response == "y":
another_calculation = True
x = result
else:
another_calculation = False
calculator()
calculator()
|
126909f88af62f2c36a64448f815f04172e2b4a9 | samisaf/Learning-Data-Science | /Machine Learning - Coursera/models.py | 4,656 | 3.71875 | 4 | import numpy as np
import scipy.io
import scipy.optimize
def LogisticRegression(X, y, theta0=None, reg=0, optimizer='builtin', niter=100):
"""
RETURNS theta/weights by fitting a logistic model using X (sample, features), and y labels.
INPUT
X: 2D array of m rows, and n cols (m, n) representing model samples and features
y: 1D array of length m (m, ) representing labels
theta: 1D array of length n (n, ) representing model weights
reg: a number representing a regularization constant
"""
# check if this is a binary or multi-class regression model
if len(np.unique(y)) == 2:
return logistic_fit_binary(X, y, theta0, reg)
else:
return logistic_fit_multi(X, y, theta0, reg)
def logistic_fit_binary(X, y, theta0=None, reg=0, optimizer='builtin', niter=100):
"""
fits a binary classification logistic model. This is an internal function called
by LogisticRegression
"""
# generates theta0 if not given
m, n = X.shape
if theta0 == None: theta0 = np.zeros(n + 1) # add 1 for the intercept
# adds a column at the start for the intercept
X = padwOnes(X)
# calculate the weights
# choose the optimizer
optimizer = scipy.optimize.fmin_cg
# define the cost and gradient as functions of theta
# note that cost and gradient are functions since logistic_cost, and logistic gradient are partial functions
cost = logistic_cost(X, y, reg)
gradient = logistic_gradient(X, y, reg)
# run the optimizer
theta_optimum = optimizer(cost, theta0, fprime=gradient, maxiter=niter, disp=0)#,
return theta_optimum
def sigmoid(z):
"""
RETURN the sigmoid value(s) for a given number or array
"""
return 1 / (1 + np.exp(-z))
def logistic_hypothesis(X, theta):
"""
RETURNS the hypothesis/probability in a logistic model (number 0-1). This is a vectorized function.
INPUT
X: 2D array of m rows, and n cols (m, n) representing model samples and features
theta: 1D array of length n (n, ) representing model weights
"""
return sigmoid(X.dot(theta))
def logistic_cost(X, y, reg=0):
"""
RETURNS the cost for a logistic model (number) at a given theta/weight. This is a vectorized partial function.
INPUT
X: 2D array of m rows, and n cols (m, n) representing model samples and features
y: 1D array of length m (m, ) representing labels
theta: 1D array of length n (n, ) representing model weights
reg: a number representing a regularization constant
"""
# (hypo==0) & (y==1)
epsilon = 1e-100
m, n = X.shape
def on(theta):
hypo = logistic_hypothesis(X, theta)
costs = -y * np.log(hypo + epsilon) - (1 - y) * np.log(1 - hypo + epsilon)
#costs = np.log(hypo.where((hypo!=0) & (y==1))) - np.log(1 - hypo.where((hypo!=1) & (y==0)))
#costs = sum(np.log(hypo[y==1 and hypo!=0])) + sum(np.log(1-hypo[y==0] and hypo!=1))
#costs = -y * np.log(hypo) - (1 - y) * np.log(1 - hypo)
penalties = 0.5 * reg * theta[1:]**2
return (sum(costs) + sum(penalties)) / m
return on
def logistic_gradient(X, y, reg=0):
"""
RETURNS the gradient for a logistic model (number) at a given theta/weight. This is a vectorized partial function.
INPUT
X: 2D array of m rows, and n cols (m, n) representing model samples and features
y: 1D array of length m (m, ) representing labels
theta: 1D array of length n (n, ) representing model weights
reg: a number representing a regularization constant
"""
def on(theta):
m, n = X.shape
hypo = logistic_hypothesis(X, theta)
gradients = X.T.dot(hypo - y) / m
penalties = np.append(0, reg * theta[1:]) / m
return gradients + penalties
return on
def padwOnes(X):
"""
RETURNS the given array padded with a column of ones on the left side
INPUT a two dimentional array X
"""
m, n = X.shape
ones = np.ones((m, 1))
return np.append(ones, X, axis=1)
def test_binary():
# load the data where X are the scores of two exams, and y is if the candidate was admitted to college
data = np.genfromtxt('ex2data1.txt', delimiter=',')
X = data[:, :2]
y = data[:, 2]
# run the model
theta = LogisticRegression(X, y)
# print theta to screen
print('theta:')
print(' %s \n' % theta)
print('Expected theta (approx):')
print(' -25.161 0.206 0.201\n')
theta_expected = np.array([-25.161, 0.206, 0.201])
threshold = 0.1
assert sum(abs(theta -theta_expected)) < threshold
def test():
test_binary()
if __name__=="__main__": test() |
d06bfc23f9b3fb4fab5d91e6767c443d05528f8f | VaibhavDhaygonde7/Coding | /Python Projects/P75MathsFunction.py | 770 | 3.984375 | 4 | class Math():
@staticmethod
def squrt(n):
return n * n
@staticmethod
def cuberoot(n):
return n * n * n
class Square(Math):
def __init__(self, side):
self.side = side
def areaofsquare(self):
return Math.squrt(self.side)
class Rectangle(Math):
def __init__(self, length, height):
self.length = length
self.height = height
def areaofrectangle(self):
return self.length * self.height
sq1 = Square(int(input("Enter the side of the square: ")))
rec1 = Rectangle(int(input("Enter the length of the rectangle: ")), int(input("Enter the height of the rectangle: ")))
print("The area of the square is", sq1.areaofsquare())
print("The area of the rectangle is", rec1.areaofrectangle()) |
c58386ffcd94ddf39a7c892837c493b4d517f75e | PhucNguyen12038/PythonLearning | /School-works/sessions/session17/final2.py | 1,287 | 3.796875 | 4 | fname = 'concert.txt'
#fn = input("Please enter filename: ")
cl = input("What is your class? ")
nt = int(input("How many tickets do you want? "))
dic = {}
array = []
ffile = open("concert.txt")
i = 0
for line in ffile:
spl = line.strip().split(" ")
place = spl[0]
seat = spl[1]
list_seat = list(seat)
array.append(list_seat)
dic.update({place:i})
i = i + 1
ffile.close()
i = 0
for k,v in dic.items():
dic[k] = i
i = i + 1
def find_seat(dic,cl):
if cl in dic:
v = dic[cl]
row = array[v]
print(row)
for i in range(len(row)-(nt-1)):
c = 0
for j in range(nt-1):
#print(i,j)
if row[i+j] == '-' and row[i+j+1] == '-':
c += 1
if c == (nt-1):
return i
return -1
else:
return -1
if find_seat(dic,cl) == -1:
print("Sorry but there are no suitable seats available")
else:
strings = "Your seats are "
print(strings,end=" ")
r = dic[cl]
for i in range(nt):
s = find_seat(dic,cl) + i
if i != nt-1:
st = "(row {}, seat {}),".format(r+1,s+1)
else:
st = "(row {}, seat {})".format(r+1,s+1)
print(st,end=" ")
|
0d00cf5415800c8f94ffd3337e82a9801747a407 | iewaij/algorithm | /Assignment/exam/sample_question/fibonacci_leq.py | 679 | 4.34375 | 4 | """
Given a positive number, print out all Fibonacci numbers smaller or equal to that number. For example, given the number 11 the program should print out: 1 1 2 3 5 8. The next Fibonacci number would be 13 which is already larger than 11.
"""
fibonacci_dict = {1:0, 2:1, 3:1}
def fibonacci_saved(n: int) -> list:
if n not in fibonacci_dict:
fibonacci_dict[n] = fibonacci_saved(n-2) + fibonacci_saved(n-1)
return fibonacci_dict[n]
def fibonacci_leq(n: int) -> list:
i = 1
while True:
if fibonacci_saved(i) <= n:
i += 1
else:
fibonacci_list = list(fibonacci_dict.values())
return fibonacci_list[:-1]
|
7ef903f6ce906d807faf28a7f8988a92af7c2c45 | MartinCastellano/training | /hackerrank/Quartiles.py | 379 | 3.765625 | 4 | from statistics import median
n = input()
lista = list(map(int, input().split(" ")))
lista.sort()
q2 = median(lista)
listaq1 = []
listaq3 = []
for i in range(len(lista)):
if lista[i] < q2:
listaq1.append(lista[i])
if lista[i] > q2:
listaq3.append(lista[i])
q1 = median(listaq1)
q3 = median(listaq3)
print (int(q1))
print (int(q2))
print (int(q3)) |
85a04c61a8c552237b296840a94af3b13c0d9117 | bucknercd/exception | /binmath.py | 1,526 | 3.734375 | 4 |
from Errors import OperatorException
import sys
def binmath(b1,op,b2):
valid_len1 = len(b1)
valid_len2 = len(b2)
count1 = 0
count2 = 0
valid = '01'
valid_ops = ['+','-','*','^']
for i in b1:
if i in valid:
count1+=1
for i in b2:
if i in valid:
count2+=1
if valid_len1 != count1 or valid_len2 != count2:
raise ArithmeticError('this is not valid binary')
elif op not in valid_ops:
raise OperatorException('this is not a valid operator')
else:
d1 = int(b1,2)
d2 = int(b2,2)
if op == '+':
ans = d1 + d2
elif op == '-':
ans = d1 - d2
elif op == '*':
ans = d1 * d2
elif op == '^':
ans = d1 ** d2
ans = bin(ans)
if ans.startswith('-'):
ans = ans[0:1] + ans[3:]
else:
ans = ans[2:]
return ans
while True:
try:
line = raw_input('Enter a binary operation or q to exit.\n>').strip()
except EOFError as e:
sys.exit()
try:
option = line[0]
if line == 'q' or line == 'Q' or line == 'quit'or line == 'exit':
sys.exit()
except IndexError as e:
print e
print 'You must enter something.'
continue
try:
var1, operation, var2 = line.split(' ')
except ValueError as e:
print e
continue
try:
ans = binmath(var1, operation, var2)
except ArithmeticError as e:
print e
continue
except OperatorException as e:
print e
continue
print '{0} {1} {2} = {3}\n'.format(var1, operation, var2, ans)
|
3c7b7f63f4c72841a0280fa4baae51f91eae1410 | danamulligan/APTsPython | /ps2/Pancakes.py | 1,650 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 18:34:23 2018
@author: danamulligan
"""
"""
def minutesNeededs(numCakes, capacity):
nice = 0
time = 0
if capacity > numCakes:
nice = numCakes % capacity - 1
for n in range(nice-1):
time += 5
for k in range(numCakes - nice):
time += 5
if numCakes == 0:
time = 0
return time
"""
def minutesNeededs(numCakes, capacity):
time = 0
remaining = numCakes % capacity
print(remaining)
perfect = numCakes - remaining
print('new', numCakes//capacity)
print('perf', perfect)
full_sets = perfect // capacity
print(full_sets)
for k in range(full_sets):
time += 10
print('full', time)
#if remaining < capacity:
#if remaining > 0 and remaining % 2 == 0:
# time += 10
# print('even', time)
#elif remaining > 0 and remaining % 2 == 1:
# time += 5
# print('odd', time)
#elif remaining > capacity:
if remaining <= capacity / 2 and remaining != 0:
time += 5
elif remaining > capacity / 2 and remaining != 0:
time += 10
if numCakes <= capacity and numCakes != 0:
time = 10
elif numCakes == 0:
time = 0
return time
def minutesNeeded(numCakes, capacity):
rem = numCakes % capacity
full = numCakes // capacity
time = full * 10
if numCakes == 0:
time = 0
elif numCakes < capacity and numCakes != 0:
time = 10
elif rem <= capacity / 2 and rem != 0:
time += 5
elif rem > capacity / 2 and rem != 0:
time += 10
return time |
f605a0033a6bd08a53ac0b48e83c04336200f318 | sreyansb/Codeforces | /codeforces1102A.py | 76 | 3.53125 | 4 | n=int(input())
sumi=(n*(n+1))>>1
if sumi&1:
print(1)
else:
print(0)
|
0bb916cf5958dbc4dd12ef479c10f9db0a202dfb | cthurmond/Python-Practice | /dictdiff.py | 1,081 | 3.5625 | 4 | # *** MY CODE ***
# Fixed brackets after looking at his code.
def dictdiff(d1, d2):
diffdict = {}
error_dict = ""
for key in d1:
try:
if d1[key] != d2[key]:
diffdict[key] = [d1[key], d2[key]]
except KeyError:
diffdict[key] = [d1[key], "none"]
for key in d2:
if key not in d1:
diffdict[key] = ["none", d2[key]]
return diffdict
# *** HIS CODE ***
#def dictdiff(d1, d2):
#output = {}
#all_keys = sert(d1.keys())
#all_keys.update(d2.keys())
#for key in all_keys:
#if d1.get(key) != d2.get(key):
#output[key] = [d1.get(key), d2.get(key)]
#return output
d1 = {"a":1, "b":2, "c":3}
d2 = {"a":1, "b":2, "c":4}
print ("First Test")
print (dictdiff(d1, d1))
print ("\n")
print ("Second Test")
print (dictdiff(d1, d2))
print ("\n")
d1 = {"a":1, "b":2, "d":3}
d2 = {"a":1, "b":2, "c":4}
print ("Third Test")
print (dictdiff(d1, d2))
print ("\n")
d1 = {"a":1, "b":2, "c":3}
d2 = {"a":1, "b":2, "d":4}
print ("Fourth Test")
print (dictdiff(d1, d2)) |
ba97ad138cd4905e2f4f017060b68a61f8464543 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/joshua-bone/lesson9/mailroom_oo.py | 3,344 | 3.671875 | 4 | # Joshua Bone - UW Python 210 - Lesson 9
# 03/01/2019
# Assignment: Mailroom, Object Oriented
from donors import Donors
from formatter import Formatter
MAIN_MENU = ("Welcome to the Mailroom!",
"",
"Please select from the following options:",
"(S)end a Thank You",
"(C)reate a Report",
"(M)ail Letters to Everyone",
"(Q)uit")
TY_MENU = ("Send a Thank You",
"",
"At the prompt you can either:",
"\tEnter a donor name,",
"\tType 'list' to display all existing donors,",
"\tType 'q' to go back to main menu.")
NOT_UNDERSTOOD = "Input not understood. Please try again."
PROMPT = "Your selection: "
donors = Donors()
formatter = Formatter(donors)
def display(lines):
print('-' * 80)
if isinstance(lines, str):
print(lines)
else:
for line in lines:
print(line)
print("\n")
def display_donors():
display(["Existing Donors:", ""] + donors.names)
def display_report():
display(formatter.report_header())
display(formatter.sorted_report_body())
def mail_all_donors():
donor_list = donors.get_all()
for d in donor_list:
with open(d.name + ".txt", "w") as f:
f.write("\n".join(formatter.format_ty(d.name, d.donations)))
display(f"Mailed {len(donor_list)} letters.")
def send_ty(name):
display("Sending a thank you to " + name)
amt = None
while amt is None:
try:
amt = float(input("Enter amount: "))
except ValueError:
display("Error: Could not parse input. Please try again.")
donors.add_donation(name, amt)
display(formatter.format_ty(name, [amt]))
def do_ty_menu():
i = get_menu_input(TY_MENU)
fns = ty_dict.get(i.lower(),
[lambda: send_ty(i),
do_main_menu])
for fn in fns:
fn()
def do_main_menu():
i = get_menu_input(MAIN_MENU)
fns = main_dict.get(i.lower(),
[lambda: display(NOT_UNDERSTOOD),
do_main_menu])
for fn in fns:
fn()
def get_menu_input(menu, prompt=PROMPT):
display(menu)
return input(prompt)
def do_main_menu():
i = get_menu_input(MAIN_MENU)
fns = main_dict.get(i.lower(),
[lambda: display(NOT_UNDERSTOOD),
do_main_menu])
for fn in fns:
fn()
ty_dict = {'list': [display_donors, do_ty_menu],
'q': [lambda: display("Returning to Main Menu."), do_main_menu]}
main_dict = {'s': [do_ty_menu],
'c': [display_report, do_main_menu],
'm': [mail_all_donors, do_main_menu],
'q': [lambda: display("Exiting...")]}
if __name__ == "__main__":
donors.add_donation("William Gates, III", 456456.22)
donors.add_donation("William Gates, III", 197328.27)
donors.add_donation("Mark Zuckerberg", 4567.97)
donors.add_donation("Mark Zuckerberg", 7521.42)
donors.add_donation("Mark Zuckerberg", 4306.71)
donors.add_donation("Jeff Bezos", 877.33)
donors.add_donation("Paul Allen", 150.00)
donors.add_donation("Paul Allen", 450.00)
donors.add_donation("Paul Allen", 108.42)
donors.add_donation("Sergey Brin", 956755.89)
donors.add_donation("Sergey Brin", 123.89)
donors.add_donation("Sergey Brin", 34732.22)
do_main_menu()
|
7063e537dc951dc39526a7082fa79c75b421409c | jay6413682/Leetcode | /Sliding_Window_Maximum_239.py | 12,554 | 3.578125 | 4 | import heapq
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
""" 暴力法 brutal force, sliding window
超出时间限制
这道题最暴力的方法就是 2 层循环,时间复杂度 O(n * K)O(n∗K)。
空间复杂度:o(n)
"""
res = []
i = 0
n = len(nums)
while i < n - k + 1:
max_val = max(nums[i:i + k])
res.append(max_val)
i += 1
return res
class Solution1:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
""" priority queue, heapq, heap, 堆,滑动窗口sliding window
类似解 https://leetcode-cn.com/problems/sliding-window-maximum/solution/hua-dong-chuang-kou-zui-da-zhi-by-leetco-ki6m/
时间复杂度:O(n \log n)O(nlogn),其中 nn 是数组 \textit{nums}nums 的长度。在最坏情况下,数组 \textit{nums}nums 中的元素单调递增,那么最终优先队列中包含了所有元素,没有元素被移除。由于将一个元素放入优先队列的时间复杂度为 O(\log n)O(logn),因此总时间复杂度为 O(n \log n)O(nlogn)。
空间复杂度:O(n)O(n),即为优先队列需要使用的空间。这里所有的空间复杂度分析都不考虑返回的答案需要的 O(n)O(n) 空间,只计算额外的空间使用。(在最坏情况下,数组 \textit{nums}nums 中的元素单调递增,那么最终优先队列中包含了所有元素)
解释的更清楚:https://leetcode-cn.com/problems/sliding-window-maximum/solution/you-xian-dui-lie-zui-da-dui-dan-diao-dui-dbn9/
"""
# 注意 Python 默认的优先队列是小根堆
priority_queue = [(-num, i) for (i, num) in enumerate(nums[:k])]
heapq.heapify(priority_queue)
res = [-priority_queue[0][0]]
for i in range(k, len(nums)):
num = nums[i]
heappush(priority_queue, (-num, i))
while priority_queue[0][1] <= i - k:
heapq.heappop(priority_queue)
res.append(-priority_queue[0][0])
return res
'''
# or like below
priority_queue = [(-num, i) for (i, num) in enumerate(nums[:k])]
heapq.heapify(priority_queue)
res = [-priority_queue[0][0]]
for i in range(k, len(nums)):
num = nums[i]
# print(priority_queue)
while priority_queue and priority_queue[0][1] <= i - k:
heapq.heappop(priority_queue)
print(priority_queue)
heappush(priority_queue, (-num, i))
res.append(-priority_queue[0][0])
return res
'''
class Solution3:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
""" 单调队列,monotonic queue, 双端队列, deque,double-ended queue, 滑动窗口sliding window
monotonic/monotone queue vs monotonic/monotone stack: https://blog.csdn.net/Hanx09/article/details/108434955
https://www.google.com/search?q=monotonic+queue+vs+monotonic+stack&oq=monotonic+stack+vs+monotonic+que&aqs=chrome.1.69i57j0i22i30.12688j1j7&sourceid=chrome&ie=UTF-8
应用 区间最小(最大)值问题。
解 https://leetcode-cn.com/problems/sliding-window-maximum/solution/hua-dong-chuang-kou-zui-da-zhi-by-leetco-ki6m/
图解: https://leetcode-cn.com/problems/sliding-window-maximum/solution/you-xian-dui-lie-zui-da-dui-dan-diao-dui-dbn9/
在上述滑动窗口形成及移动的过程中,我们注意到元素是从窗口的右侧进入的,然后由于窗口大小是固定的,因此多余的元素是从窗口左侧移除的。 一端进入,另一端移除,这不就是队列的性质吗?所以,该题目可以借助队列来求解。
至此,该题目的求解思路就清晰了,具体如下:
1. 遍历给定数组中的元素,如果队列不为空且当前考察元素大于等于队尾元素,则将队尾元素移除。直到,队列为空或当前考察元素小于新的队尾元素;
2. 当队首元素的下标小于滑动窗口左侧边界left时,表示队首元素已经不再滑动窗口内,因此将其从队首移除。
3. 由于数组下标从0开始,因此当窗口右边界right+1大于等于窗口大小k时,意味着窗口形成。此时,队首元素就是该窗口内的最大值。
:
https://leetcode.cn/problems/sliding-window-maximum/solution/dong-hua-yan-shi-dan-diao-dui-lie-239hua-hc5u/
时间复杂度:O(n)O(n),其中 nn 是数组 \textit{nums}nums 的长度。每一个下标恰好被放入队列一次,并且最多被弹出队列一次,因此时间复杂度为 O(n)O(n)。
空间复杂度:O(k)O(k)。与方法一不同的是,在方法二中我们使用的数据结构是双向的,因此「不断从队首弹出元素」保证了队列中最多不会有超过 k+1k+1 个元素,因此队列使用的空间为 O(k)O(k)。
"""
# index monotonic queue
monotonic_queue = deque()
res = []
n = len(nums)
'''
# initialize the queue(头大尾小), it's required because the first k - 1 element shouldn't be in the res
for i in range(k):
# pop tails until no smaller val compared to curr
while monotonic_queue and nums[i] > nums[monotonic_queue[-1]]:
monotonic_queue.pop()
monotonic_queue.append(i)
res.append(nums[monotonic_queue[0]])
# print(res, monotonic_queue)
for i in range(k, n):
# pop tails until no smaller val compared to curr
while monotonic_queue and nums[i] > nums[monotonic_queue[-1]]:
monotonic_queue.pop()
monotonic_queue.append(i)
# the head (largest val) is out of the queue, pop out the head
if monotonic_queue[0] <= i - k:
monotonic_queue.popleft()
res.append(nums[monotonic_queue[0]])
'''
for i in range(n):
# pop tails until no smaller val compared to curr
while monotonic_queue and nums[i] > nums[monotonic_queue[-1]]:
monotonic_queue.pop()
monotonic_queue.append(i)
# the head (largest val) is out of the queue, pop out the head
if monotonic_queue[0] <= i - k:
monotonic_queue.popleft()
# only put the head in res when we moved the right pointer to the end of the first full window
if i >= k - 1:
res.append(nums[monotonic_queue[0]])
return res
from collections import deque
class MonoDecQueue(object):
""" 单调递减队列 implementation 1:https://leetcode.cn/problems/sliding-window-maximum/solution/dan-diao-dui-lie-by-labuladong/ push and pop value
为什么pop 不用 while loop : slyfox1201: pop:在元素入队时,是按照下标i入队的,因此队列中剩余的元素,其下标一定是升序的。窗口大小不变,最先被排除出窗口的,一直是下标最小的元素,设为r。元素r在队列中要么是头元素,要么不存在。(栈是单减队列,输入的数组如果前面的数比后面的数小,就会被压出队列;如果前面的数>= 后面的数,后面的数入队列。所以如果window 向右移动,当要检查左边出window 的数是不是在队列中时,它只可能在队头,不可能在队列的其他地方,因为否则已经被压出队列了)
为什么 self.queue[-1] < val, 而不是<=
daping3:恰恰相反,能安全地pop_front是因为窗口中的最大值有重复时保留重复,哪里唯一了...
Alexhanbing:比当前小的元素才继续往下压扁,大于等于的都会继续压,会存在重复元素,所以是单调队列,不是严格单调
这样做的话,push时如果self.queue[-1] == val,self.queue[-1] 会保留在queue 当中,因为它现在还在window当中,只有当它不在window中时(pop的时候),再把它pop
避免栈中前面的相同元素被过早弹出,下一次window要move out of 前面的相同元素时,把栈中后面的相同元素弹出
"""
def __init__(self):
self.queue = deque()
def push(self, val):
while self.queue and self.queue[-1] < val:
self.queue.pop()
self.queue.append(val)
def max(self):
return self.queue[0]
def pop(self, val):
if self.queue and self.queue[0] == val:
self.queue.popleft()
class MonoDecQueue2(object):
""" 单调递减队列 implementation 2:https://www.jianshu.com/p/e59d51e1eef5 和 https://leetcode.cn/problems/sliding-window-maximum/solution/dan-diao-dui-lie-by-labuladong/ push and pop index
这个更好理解,pop用了while loop
为什么 self.queue[-1] < val, 而不是<=
daping3:恰恰相反,能安全地pop_front是因为窗口中的最大值有重复时保留重复,哪里唯一了...
Alexhanbing:比当前小的元素才继续往下压扁,大于等于的都会继续压,会存在重复元素,所以是单调队列,不是严格单调
这样做的话,push时如果self.queue[-1] == val,self.queue[-1] 会保留在queue 当中,因为它现在还在window当中,只有当它不在window中时(pop的时候),再把它pop
"""
def __init__(self, nums):
self.nums = nums
self.queue = deque()
def push(self, i):
while self.queue and self.nums[self.queue[-1]] < self.nums[i]:
self.queue.pop()
self.queue.append(i)
def max(self):
return self.nums[self.queue[0]]
def pop(self, i):
# 从队列中弹出所有输入数组中 i 和 它左侧的 数:self.queue[0] == i 的时候 也会被弹出
# if or while 都可以,<= or == 都可以
while self.queue and self.queue[0] <= i:
self.queue.popleft()
class Solution4:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
""" 最好理解,把window实时压入单调递减队列,然后取队列max值(queue[0]]) """
res = []
'''
q = MonoDecQueue()
for i, num in enumerate(nums):
if i < k - 1:
q.push(num)
else:
q.push(num)
res.append(q.max())
q.pop(nums[i - k + 1])
#print(q.queue)
'''
q = MonoDecQueue2(nums)
# print(q.queue)
for i, num in enumerate(nums):
if i < k - 1:
q.push(i)
else:
q.push(i)
res.append(q.max())
q.pop(i - k + 1)
#print(q.queue)
return res
class Solution5:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# my solution, 单调队列: https://blog.csdn.net/Hanx09/article/details/108434955
# 非严格单调递减
mono_queue = deque()
res = []
for i, num in enumerate(nums):
#'''
# solution 1
if i <= k - 1:
# push
while mono_queue and mono_queue[-1] < num:
mono_queue.pop()
mono_queue.append(num)
# add to window max if i == k - 1
if i == k - 1:
res.append(mono_queue[0])
else:
# pop
if mono_queue and mono_queue[0] == nums[i - k]:
mono_queue.popleft()
# push
while mono_queue and mono_queue[-1] < num:
mono_queue.pop()
mono_queue.append(num)
# add window max
res.append(mono_queue[0])
#'''
'''
# solution 2
if i < k - 1:
# push when window not full yet
while mono_queue and mono_queue[-1] < num:
mono_queue.pop()
mono_queue.append(num)
else:
# push
while mono_queue and mono_queue[-1] < num:
mono_queue.pop()
mono_queue.append(num)
# add window max
res.append(mono_queue[0])
# pop first before next push
if mono_queue and mono_queue[0] == nums[i + 1 - k]:
mono_queue.popleft()
'''
return res
|
45da857b688fcb9edee9dde7cadbe0e289dc648b | digital-diplomat/Project-Eurler | /is_prime.py | 328 | 3.6875 | 4 | import math
def is_prime(n):
if n == 2:
retuen True
if n % 2 == 0:
return False
else:
t = math.sqrt(n)
for i in range(2, int(t)+1):
if n % i == 0:
return False
return True
# assert is_prime(2) == True # This this assertion fails!
#mfixed it
|
eebe39bb4c56822dafb04d67e05d43870a2bdf69 | polyglotm/coding-dojo | /coding-challange/leetcode/easy/~2022-02-28/1967-number-of-strings-that-appear-as-substrings-in-word/1967-number-of-strings-that-appear-as-substrings-in-word.py | 809 | 3.9375 | 4 | """
1967-number-of-strings-that-appear-as-substrings-in-word
leetcode/easy/1967. Number of Strings That Appear as Substrings in Word
Difficulty: easy
URL: https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/
"""
from typing import List
class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return sum([1 for i in patterns if i in word])
def test():
patterns = ["a", "abc", "bc", "d"]
word = "abc"
output = 3
assert Solution().numOfStrings(patterns, word) == output
patterns = ["a", "b", "c"]
word = "aaaaabbbbb"
output = 2
assert Solution().numOfStrings(patterns, word) == output
patterns = ["a", "a", "a"]
word = "ab"
output = 3
assert Solution().numOfStrings(patterns, word) == output
|
6cfb86f079559d29b50cc6e9a19ab946f55fdb47 | naomatheus/daily-interview | /number_of_cousins.py | 737 | 4.1875 | 4 | # Given a binary tree and a given node value, return all of the node's cousins.
# Two nodes are considered cousins if they are on the same level of the tree with different parents. You can assume that all nodes will have their own unique value.
Here's some starter code:
class Node(object):
def __init__(self, value, left=N):
self.value = value
self.left = left
self.right = right
class Solution(object):
def list_cousins(self, tree, val
# Fill this in.
# 1
# / \
# 2 3
# / \ \
# 4 6 5
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.right = Node(6)
root.right = Node(3)
root.right.right = Node(5)
print(Solution().list_cousins(root))
# [4, 6]
|
d1989b88aa280ff822400b25149e2a96b4f616e5 | balamurugan2405/python | /Day-2 operaters & contitional statement/numeric to alphabet.py | 359 | 3.859375 | 4 | n=int(input("Enter the number"))
if(n==1):
print("one")
elif(n==2):
print("Two")
elif(n==3):
print("Three")
elif(n==4):
print("Four")
elif(n==5):
print("Five")
elif(n==6):
print("Six")
elif(n==7):
print("Seven")
elif(n==8):
print("Eight")
elif(n==9):
print("nine")
else:
print("Invalid input")
|
4bf64aee181afa563809e3a3bd650e7b8be1f72f | AhmedRaafat14/CodeForces-Div.2A | /510A - FoxAndSnake.py | 1,771 | 4.03125 | 4 | '''
Fox Ciel starts to learn programming. The first task is drawing a fox!
However, that turns out to be too hard for a beginner, so she decides to
draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as
(r, c). The tail of the snake is located at (1, 1), then it's body extends
to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.
Your task is to draw this snake for Fox Ciel: the empty cells should
be represented as dot characters ('.') and the snake cells should be
filled with number signs ('#').
Consider sample tests in order to understand the snake pattern.
============================
Input
The only line contains two integers: n and m (3 ≤ n, m ≤ 50).
n is an odd number.
============================
Output
Output n lines. Each line should contain a string consisting of m characters.
Do not output spaces.
============================
Sample test(s)
Input
3 3
Output
###
..#
###
Input
3 4
Output
####
...#
####
Input
5 3
Output
###
..#
###
#..
###
Input
9 9
Output
#########
........#
#########
#........
#########
........#
#########
#........
#########
'''
## Running Time ===>>> 124 ms
data = input().split()
N, M = int(data[0]), int(data[1])
one_hash_count = 1
snake = []
## Just the even rows contains a dot
for i in range(0, N):
if (i+1)%2 == 0 and one_hash_count%2 != 0:
snake.append([('.'*(M-1)) + '#'])
one_hash_count += 1
continue
elif (i+1)%2 == 0 and one_hash_count%2 == 0:
snake.append(['#' + ('.'*(M-1))])
one_hash_count += 1
continue
elif (i+1)%2 != 0:
snake.append(['#'*M])
continue
print("\n".join(" ".join(map(str, line)) for line in snake))
|
24fe8b3a3f880ab645926bbf1863a6af775284c0 | scottOrban/HW24 | /HW24.py | 5,345 | 3.984375 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next = None
class linkedList:
def __init__(self):
self.head = None
def append(self, data):
newNode=Node(data)
if self.head==None:
self.head=newNode
return
else:
lastNode=self.head
while lastNode.next != None:
lastNode=lastNode.next
lastNode.next=newNode
def prepend(self, data):
newNode=Node(data)
if self.head==None:
self.head=newNode
return
else:
newNode.next=self.head
self.head=newNode
def insertAfterNode(self,prevNode,data):
newNode=Node(data)
newNode.next=prevNode.next
prevNode.next=newNode
def printList(self):
curNode=self.head
while curNode!= None:
print(curNode.data)
curNode=curNode.next
def deleteNode(self, key):
curNode=self.head
if curNode!=None and curNode.data==key:
self.head=curNode.next
curNode=None
return
else:
prev=None
while curNode != None and curNode.data != key:
prev=curNode
curNode=curNode.next
if curNode==None:
print('The data is not found in the list')
return
else:
prev.next=curNode.next
curNode=None
def deleteAtPos(self,pos):
curNode=self.head
if pos==0:
self.head= curNode.next
curNode=None
return
else:
cnt=0
prev=None
while curNode != None and cnt != pos:
prev=curNode
curNode=curNode.next
cnt+=1
if curNode==None:
print("The node doesn't exist")
return
else:
prev.next=curNode.next
curNode=None
def len_iterative(self):
cnt=0
curNode=self.head
while curNode != None:
curNode=curNode.next
cnt+=1
return cnt
def len_recursive(self,headNode):
if headNode is None:
return 0
else:
return 1+self.len_recursive(headNode.next)
def swapNode(self,key1,key2):
if key1==key2:
print('The two nodes are the same nodes, cannot be swapped')
return
else:
prev1=None
curNode1=self.head
while curNode1 != None and curNode1.data != key1:
prev1=curNode1
curNode1=curNode1.next
prev2=None
curNode2=self.head
while curNode2 != None and curNode2.data != key2:
prev2=curNode2
curNode2=curNode2.next
if curNode1==None or curNode2==None:
print("The nodes don't exist in the list")
return
else:
if prev1==None:
self.head=curNode2
prev2.next=curNode1
elif prev2==None:
self.head=curNode1
prev1.next=curNode2
else:
prev1.next=curNode2
prev2.next=curNode1
temp1=curNode1.next
temp2=curNode2.next
curNode1.next=temp2
curNode2.next=temp1
def reverse_iterative(self):
prev=None
curNode=self.head
while curNode!=None:
nxt_temp=curNode.next
curNode.next=prev
prev=curNode
curNode=nxt_temp
self.head=prev
def remove_duplcates(self):
prev=None
curNode=self.head
data_freq=dict()
while curNode !=None:
if curNode.data not in data_freq:
data_freq[curNode.data]=1
prev=curNode
curNode=curNode.next
else:
prev.next=curNode.next
curNode=None
curNode=prev.next
def print_nth_from_last(self,n):
total_len=len_iterative(self)
distance=total_len-1
curNode=self.head
while curNode != None:
if distance == n-1:
print(curNode.data)
return curNode
else:
distance-=1
curNode=curNode.next
def occurences(self,data):
cnt=0
curNode=self.head
while curNode != None:
if curNode.data==data:
cnt+=1
curNode=curNode.next
return cnt
def rotate(self,k):
p=self.head
q=self.head
prev=None
cnt=0
while p!=None and cnt<k:
prev=q
q=q.next
q=prev
self.head=q.next
p.next=self.head
p.next=None
def tail_to_head(self):
lastNode=self.head
secondLast=None
while lastNode!=None:
secondLast=lastNode
lastNode=lastNode.next
lastNode.next=self.head
self.head=secondLast.next
secondLast.next=None
|
04e5b42a2cdde2a3b8d0e3dcb686459e726b99a1 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /char_code_calculation.py | 806 | 4 | 4 | # ---------------------------------------------------------------------------------------------
# Find all ASCII code from string characters, add them, change 7 for 1, substract both amount
# and return is final result
# Made with ❤️ in Python 3 by Alvison Hunter - March 30th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# ---------------------------------------------------------------------------------------------
def calc(x):
total1 ="".join(str(ord(elem)) for elem in x)
total2 =total1.replace('7','1')
print(sum(int(num) for num in total1) - sum(int(num2) for num2 in total2))
return sum(int(num) for num in total1) - sum(int(num2) for num2 in total2)
calc('ABC')
calc('abcdef')
calc('ifkhchlhfd')
calc('aaaaaddddr')
calc('jfmgklf8hglbe')
calc('jaam')
|
cb27999583e43ff68bb6ad131f9318454e85fb15 | Matth0s/Lista-2 | /Exercicio 2.py | 1,270 | 4.375 | 4 | '''
Esse programa calcula os numeros impares da sequencia de Fibonacci
Aluno: Matheus Moreira do Nascimento
DRE: 119042060
Curso: Matemática Aplicada
Disciplina: Topicos da Matemática Aplicada A
'''
print("................................................................................\n")
print("Esse programa calcula a soma dos numeros impares de uma sequencia de Fibonacci")
print("cujo valor dos termos na sequência não excedam um parametro escolhido por tu")
print('Pra começar, escolhe um limite para os valores da sequência \n')
print("................................................................................\n")
while True:
a=float(input("Fala ai o valor limite da sequência "))
b=1
c=2
e=1
d=0
while d<a:
d=b+c
b=c
c=d
if d%2!=0:
e=e+d
print("")
print("A soma de todos os impares de uma sequencia de Fibonacci cujos valor dos")
print("termos não excedam",int(a),"é:")
print("........................")
print(e)
print("........................\n")
print("Se tu quiser calcular com outra restrição")
f=str(input("digita 'sim', se não quiser, digita 'não' "))
if f!=str('sim'):
break
print("")
print("")
print("Suave")
print("É nós")
|
3341d459cfa048dea63da945d0857e19588e636d | DanayaDarling/cs114 | /spacedungeon02d.py | 2,563 | 4 | 4 | import random
print(' ~~~~~~~~~****** Welcome Traveler ******~~~~~~~~~')
print(' ~~~~~~~~~~~****** to Space Dungeon ******~~~~~~~~~~~')
print('')
print(" Who dares to enter the dungeon?")
name = input()
print(" Foolish " + str(name) + " you will soon meet your end!")
print(" Tell me, are you a *hunter*, *thief*, *magician*, or *warrior*?")
class1 = input()
print(" If you are a " + str(class1) + " like you say you are, how much damage can you do?")
attack_points = int(input())
if attack_points >= 100:
print(" I know you are not that powerful, you can't have over 100 points! Try again!")
attack_points = int(input())
magic_points = int(100 - attack_points)
print(" Alright, since you can only have 100 points at this level, you have left yourself with" , str(magic_points) , "magic points")
print('')
print(" Well " + str(name) + " you may enter the dungeon.")
print('')
print(' Hopefully a ' + str(class1) + ' like yourself can survive with only ' + str(attack_points) + ' attack points, and ' + str(magic_points) + ' magic points.')
print('')
print(' There is an enemy!! Do you wish to *attack* or *cast a spell*?')
print('')
offense = input()
print('')
if offense == 'cast a spell':
while magic_points >= 10:
print('Your spell has hit the enemy!')
magic_points -= random.randint(1, 10)
print('You have ' + str(magic_points) + ' magic points left.')
print('')
print('~~You magic does not seem to faze the beast. To survive you must attack!~~')
print('')
while attack_points >= 10:
print('You hit the enemy!')
attack_points -= random.randint(1, 10)
print('You have ' + str(attack_points) + ' attack points left.')
print('The monster has still shown no sign of weakness...')
elif offense == 'attack':
while attack_points >= 10:
print('You hit the enemy!')
attack_points -= random.randint(1, 10)
print('You have ' + str(attack_points) + ' attack points left.')
print('')
print('~~You attack does not seem to faze the beast. To survive you must use your magic!~~')
print('')
while magic_points >= 10:
print('Your spell has hit the enemy!')
magic_points -= random.randint(1, 10)
print('You have ' + str(magic_points) + ' magic points left.')
print('The monster has still shown no sign of weakness...')
print('')
print(' Despite all your efforts, the beast looks unfazed. Your future does not look bright.')
print('')
|
87a785d30626b09cabe2acb498918b70cae5dfc6 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/201_BitwiseANDofNumbersRange.py | 900 | 3.609375 | 4 | """
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
"""
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
"""
Method 1: Brute Force
The algorithm works. But, produces a Time Limit Exceeded Error
for large inputs
"""
res = m
ele = m+1
while ele < n+1:
res = res&ele
ele += 1
if res == 0:
return 0
return res
"""
Method 2: Bit Manipulation
Your runtime beats 62.55 % of python submissions
"""
ele = 0
while m != n:
m >>= 1
n >>= 1
ele += 1
return n << ele |
48fbf337e42f2a0a79b9bb235b04083b9b66c48d | GnarGnar/cst205 | /fizzbuzz.py | 236 | 4.15625 | 4 | number = int =0
for number in range(0,100):
if(number%3==0 and number%5==0):
print(number)
print("FizzBuZZ")
elif(number%3==0):
print(number)
print("Fizz")
elif(number%5 ==0):
print(number)
print("Buzz")
|
ee643fb4b87d155386285ca1fca14a14757a64c8 | Ryan-Brooks-AAM/cleverprogrammer | /Learn-Python/exercise8_dict.py | 808 | 4.25 | 4 | phone_book = {"John": "444-222-4444", "Billy": "444-222-1111"}
# get johns number
print(phone_book['John'])
# get billys number
print(phone_book['Billy'])
movies = {"Shawshank Redemption": 9.7, "The God Father": 8.0}
for k in movies.keys():
print(f"{k} received a score {movies[k]}")
fruit = {
"banana": 1.00,
"apple": 1.53,
"kiwi": 2.00,
"avocado": 3.23,
"mango": 2.33,
"pineapple": 1.44,
"strawberries": 1.95,
"melon": 2.34,
"grapes": 0.98
}
for f in fruit.keys():
print(f"{f} costs exactly {fruit[f]} with tax.")
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
for p in people.keys():
print(f"{people[p]['name']} is {people[p]['age']} years old. Sex is {people[p]['sex']}")
|
ef0c993d803d31f8d75407cdb951ad7111266e24 | Church-17/python_tools | /goldbachConjecture.py | 906 | 3.546875 | 4 | def prime(n: int):
if n == 2 or n == 5:
return True
if n%2 == 0 or n%5 == 0:
return False
sqrt = int(n**.5) + 1
for div in range(3, sqrt, 10):
if n%div == 0:
return False
for div in range(7, sqrt, 10):
if n%div == 0:
return False
for div in range(11, sqrt, 10):
if n%div == 0:
return False
for div in range(19, sqrt, 10):
if n%div == 0:
return False
return True
def goldbach(n: int):
if n < 2:
return False, False
if n == 2:
return 2, 2
for p in range(3, n, 2):
q = 2*n - p
if prime(p) and prime(q):
return p, q
from time import time
i = int(input('Inserire un numero: '))
start = time()
p1, p2 = goldbach(i)
print('= (', p1, '+', p2, ') / 2')
print('Time:', time() - start, 'seconds') |
3674ee24d236b3948c5b0943106efab86ef0046d | danrodaba/Python_PixelBlack | /Python_PixelBlack/Aprende con Alf/02 Condicionales/03division.py | 748 | 4.09375 | 4 | '''
Escribir un programa que pida al usuario dos números y
muestre por pantalla su división. Si el divisor es cero el programa debe mostrar un error.
'''
try:
dividendo = int(input('Introduce el dividendo (número entero): '))
divisor = int(input('Introduce el divisor (número entero): '))
if divisor == 0:
print('Verás amigo, aquí hacemos matemáticas normales, sin irnos al infinito, ni nada por el estilo.')
else:
cociente = dividendo // divisor
resto = dividendo % divisor
print('Dividendo: {0} \n Divisor: {1} \n Cociente: {2} \n Resto: {3}'.format(dividendo, divisor, cociente, resto))
except:
print('Solo tenías un puto trabajo, el programa hace lo demás: pon números enteros.')
|
1f273bd983bac04963a4a2710346b0bc21a731b2 | Skylake101/Python-Practice-2-Attack-of-the-Turtle | /CarlsonLProject2.py | 5,771 | 4.1875 | 4 | """
Author: Luke Carlson
Python has a built in turtle you can use to draw simple objects, I experiment with it here
"""
import turtle
turtle.speed(9999999)
"""
I made turtle ludicrously fast for my own amusement
"""
turtle.width(5)
turtle.penup()
turtle.goto(250,-220) #This is the start of the right snowman
turtle.pendown()
turtle.circle(85) #85 60 and 40
turtle.penup()
turtle.goto(250,-50)
turtle.pendown()
turtle.circle(60)
turtle.penup()
turtle.goto(250,70)
turtle.pendown()
turtle.circle(40)
turtle.penup()
turtle.goto(-250,-220) #This is the start of the left snowman
turtle.pendown()
turtle.circle(85) #85 60 and 40
turtle.penup()
turtle.goto(-250,-50)
turtle.pendown()
turtle.circle(60)
turtle.penup()
turtle.goto(-250,70)
turtle.pendown()
turtle.circle(40)
turtle.penup()
if (5 + 5 == 12) : #This is my way of adding the square into a if statement, this occurs over 3 times
turtle.speed(2)
else :
y=2 #'y' is added as a '1 run' disposable variable to make the while loop work.
while(y == 2 ) : #This adds a nested whileloop
sides = 0
"""The variable 'sides' shows up many times in my code, it is what tells the box when to stop making sides.
It is incredibly vital for the box to be colored in."""
turtle.color("cyan") #Big cyan box
fward = 240
""" It may have seemed unusual to use 'fward' instead of forward, I did this
because when I proof read my code I want it to be obvious that this was a variable
I designed, not a python command. """
turtle.goto(-120,120)
turtle.pendown()
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
while(sides < 40) :
"""This while loop is vital for the square to be colored in, it is essentially like a giant game of snake
where you can only turn right. Before the line hits a wall, it turns right until the entire inside of
the box is colored in."""
fward = fward - 1 #Once the first 3 sides have been made, the 4th is one pixel shorter
turtle.forward(fward) #The 5th side runs 1 pixel below the 1st side, effectively coloring it in.
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
fward = fward - 1 #On this command, the side length must be reduced by one pixel yet again.
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
sides = sides + 1
y = y - 1
if (5 < 3) :
"""This box, and the white box are identical to the last one, they just have shorter sides and
the starting x,y coordinate is smaller. (To compensate for the smaller box size.)"""
turtle.speed(500)
else :
y=2
while(y == 2 ) :
sides = 0
turtle.color("orchid") #Small pink box
fward = 160
turtle.penup()
turtle.goto(-80,80)
turtle.right(90)
turtle.pendown()
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
while(sides < 35) :
fward = fward - 1
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
fward = fward - 1
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
sides = sides + 1
y = y - 1
if (1 >= 2) :
turtle.speed(500)
else :
y=2
while(y == 2 ) :
sides = 0
turtle.color("ghostwhite") #Small white box
fward = 80
turtle.penup()
turtle.goto(-40,40)
turtle.right(90)
turtle.pendown()
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
while(sides < 50) :
fward = fward - 1
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
fward = fward - 1
turtle.forward(fward)
turtle.right(90)
turtle.forward(fward)
turtle.right(90)
sides = sides + 1
y = y - 1
snowflakesides = 4 # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< PLEASE READ ME <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
"""
I designed the above snowflake sides to be modular. Type in any number of sides you want above, and
the program will print a snowflake of that number of sides.
"""
turtle.color("black") #This starts the snowflake part
sides = 0 #This time, sides is actually used for the lines of the snowflake
while(sides < snowflakesides) :
"""What is really cool about this code, is that if you change sides from 4 to something else, and you
"""
turtle.penup()
turtle.goto(0,0)
turtle.pendown()
turtle.right(0)
turtle.forward(50)
turtle.right(180)
turtle.forward(100)
turtle.goto(0,0)
turtle.right(180 / snowflakesides)
sides = sides + 1 #This adds 1 to sides, because 1 line has been drawn.
turtle.penup() #This starts the Sally's Snow Cones logo
turtle.goto(-120,150)
turtle.write("Sally's Snow Cones", font=("Harrington", 20, "bold")) #Harrington, font, size 20, bold
turtle.color("white")
turtle.goto(0,250)
turtle.done()
|
1675e0d47312cc48810f1c31556ad1509d3c25ce | aslam7825/python | /beginner/Sum of Natural numbers.py | 72 | 3.625 | 4 | i=int(input(""))
sum=0
while(i > 0):
sum=sum+i
i=i-1
print(sum)
|
cffb4ff6b4206574c31fb0206cc3882b6816d114 | srinidhi136/python-app | /Anonymous_Functions.py | 123 | 3.890625 | 4 | ##lambda function is called inline function Also called as anonymous function
f= lambda x: x*2
#print(f())
print(f(2))
|
1a6018aa994b7a32f7a3e2a78b84449a48e6c09a | vic111/python | /find_name.py | 564 | 3.953125 | 4 | #一个用于查找你的姓名是否在表中
#进行姓名的补全
name = {'Adam','Alex','Amy','Bob','Boom',
'Candy','Chris','David','Jason',
'Jasonstatham','Bill'}
while(1):
i_name = input ('请输入你的姓名').title()
fname = []
for i in name:
if i[0:len(i_name)] == i_name:
fname.append (i)
if len (fname) == 0:
print ('数据库没有找到你的姓名')
elif len(fname)==1:
print('用户',fname,'你好!')
exit ()
else:
print ('你的姓名可能是',fname)
|
46ef39be63e41ee5cbfb89067bb09585b4b6bb68 | tttgm/code-snippets | /python-basics/using_jupyter_for_slides.py | 554 | 3.53125 | 4 | ### USING JUPYTER NOTEBOOK AS SLIDES ###
"""
To create a slideshow using a jupyter notebook is easy.
First, prepare notebook as slides via View -> Cell Toolbar -> Slideshow.
Then, mark each cell as a 'slide', 'sub-slide', 'note', or to be skipped (i.e. not shown).
Save notebook.
"""
# To initiate slideshow (presentation) in the browser, run the following command in Terminal:
jupyter nbconvert documents\jupyter-notebook-file.ipynb --to slides --post serve
# Where 'documents\jupyter-notebook-file.ipynb' is just the notebook dir address/name!
|
57338d20fddb3759b2ec32fcf084638186df11db | chadleytan/Projects | /automated puzzle solving/word_ladder_puzzle.py | 4,968 | 3.875 | 4 | from puzzle import Puzzle
class WordLadderPuzzle(Puzzle):
"""
A word-ladder puzzle that may be solved, unsolved, or even unsolvable.
"""
def __init__(self, from_word, to_word, ws):
"""
Create a new word-ladder puzzle with the aim of stepping
from from_word to to_word using words in ws, changing one
character at each step.
@type from_word: str
@type to_word: str
@type ws: set[str]
@rtype: None
"""
(self._from_word, self._to_word, self._word_set) = (from_word,
to_word, ws)
# set of characters to use for 1-character changes
self._chars = "abcdefghijklmnopqrstuvwxyz"
# TODO
# implement __eq__ and __str__
# __repr__ is up to you
def __eq__(self, other):
"""
Return whether WordLadderPuzzle self is equivalent to other.
@type self: WordLadderPuzzle
@type other: WordLadderPuzzle | Any
@rtype: bool
>>> from_word1 = "cost"
>>> to_word1 = "save"
>>> ws1 = set(["cast", "case", "cave"])
>>> wl1 = WordLadderPuzzle(from_word1, to_word1, ws1)
>>> from_word2 = "cost"
>>> to_word2 = "save"
>>> ws2 = set(["cast" , "case", "cave"])
>>> wl2 = WordLadderPuzzle(from_word2, to_word2, ws2)
>>> wl1 == wl2
True
>>> from_word3 = "cost"
>>> to_word3 = "save"
>>> ws3 = set(["cast", "case", "cave", "have"])
>>> wl3 = WordLadderPuzzle(from_word3, to_word3, ws3)
>>> wl1 == wl3
False
"""
return (type(self) == type(other) and
self._from_word == other._from_word and
self._to_word == other._to_word and
self._word_set == other._word_set)
def __str__(self):
"""
Return a human-readable string representation of WordLadderPuzzle
self.
>>> from_word = "cost"
>>> to_word = "save"
>>> ws = set(["cast", "case", "cave"])
>>> w = WordLadderPuzzle(from_word, to_word, ws)
>>> print(w)
Current: cost
Goal: save
"""
return ("Current: {}\nGoal: {}".format(self._from_word,
self._to_word))
# TODO
# override extensions
# legal extensions are WordPadderPuzzles that have a from_word that can
# be reached from this one by changing a single letter to one of those
# in self._chars
def extensions(self):
"""
Return a list of extensions of GridPegSolitairePuzzle self.
@type self: GridPegSolitairePuzzle
@rtype: list[GridPegSolitairePuzzle]
>>> from_word = "cost"
>>> to_word = "save"
>>> ws = set(["cast", "most", "case", "cave"])
>>> w = WordLadderPuzzle(from_word, to_word, ws)
>>> W1 = list(w.extensions())
>>> for i in W1: print(i)
Current: most
Goal: save
Current: cast
Goal: save
"""
extensions = []
#convenient names
from_word, to_word = self._from_word, self._to_word
#Goes through every word possibility for from_word
for i in range(len(from_word)):
#Change letter at position i to all letters
for letter in self._chars:
word = list(from_word)
word[i] = letter
word = "".join(word)
#Found word in word set
if word in self._word_set:
extensions.append(WordLadderPuzzle(word, to_word,
self._word_set - {word}))
return extensions
# TODO
# override is_solved
# this WordLadderPuzzle is solved when _from_word is the same as
# _to_word
def is_solved(self):
"""
Return whether GridPegSolitairePuzzle self is solved.
@type self: GridPegSolitairePuzzle
@rtype: bool
"""
return (self._from_word == self._to_word)
if __name__ == '__main__':
import doctest
doctest.testmod()
from puzzle_tools import breadth_first_solve, depth_first_solve
from time import time
with open("words", "r") as words:
word_set = set(words.read().split())
w = WordLadderPuzzle("same", "cost", word_set)
start = time()
sol = breadth_first_solve(w)
end = time()
print("Solving word ladder from same->cost")
print("...using breadth-first-search")
print("Solutions: {} took {} seconds.".format(sol, end - start))
start = time()
sol = depth_first_solve(w)
end = time()
print("Solving word ladder from same->cost")
print("...using depth-first-search")
print("Solutions: {} took {} seconds.".format(sol, end - start))
|
158a5c4174cd6cec3ca49069f0402fbfdf927315 | Xitog/teddy | /teddypy/layeredmap.py | 11,551 | 3.671875 | 4 | """A map with different layers."""
import json
from traceback import print_exc
from sys import stdout
def pretty_json(data, level=0, indent=4):
"Pretty print some JSON."
content = ''
if isinstance(data, dict):
content += '{\n'
level += 1
count = 0
for key, val in data.items():
content += ' ' * indent * level + '"' + str(key) + '": '
content += pretty_json(val, level, indent)
count += 1
if count == len(data):
level -= 1
content += '\n'
content += ' ' * indent * level + '}'
else:
content += ',\n'
if len(data) == 0:
level -= 1
content += ' ' * indent * level + '}'
elif isinstance(data, list):
list_in_list = False
for val in data:
if isinstance(val, list):
list_in_list = True
break
content += '['
level += 1
count = 0
if list_in_list:
content += '\n'
for val in data:
if list_in_list:
content += ' ' * indent * level
content += pretty_json(val, level)
count += 1
if count == len(data):
level -= 1
if list_in_list:
content += '\n' + ' ' * indent * level
content += ']'
else:
content += ', '
if list_in_list:
content += '\n'
if len(data) == 0:
level -= 1
content += ' ' * indent * level + ']'
elif isinstance(data, str):
content += '"' + data + '"'
elif isinstance(data, bool):
content += "true" if data else "false"
elif isinstance(data, int):
content += str(data)
elif isinstance(data, float):
content += str(data)
else:
raise Exception('Type unknown: ' + data.__class__.__name__)
return content
class Obj:
def __init__(self, name, attributes):
self.name = name
self.attr = attributes
def __str__(self):
return f"<Obj {self.name}>"
class Layer:
"A class representing a layer of the map."
@staticmethod
def create_matrix(max_col: int, max_row: int, default: int = 0):
"Static method for creating a matrix, a list of rows."
matrix = []
for _ in range(max_row):
row = []
for _ in range(max_col):
row.append(default)
matrix.append(row)
return matrix
def __init__(self, mymap: str, name: str, default: int, obj : Obj = None):
self.map = mymap
self.name = name
self.default = default
self.content = Layer.create_matrix(self.map.width,
self.map.height,
default)
self.prototype = obj
self.objects = []
def is_object_layer(self):
"This layer is an object layer."
return self.prototype is not None
def resize(self):
"Resize a layer."
old = self.content
self.content = Layer.create_matrix(self.map.width,
self.map.height,
self.default)
for row in range(min(len(old), self.map.height)):
for col in range(min(len(old[0]), self.map.width)):
self.content[row][col] = old[row][col]
def get(self, row: int, col: int):
"Return int at row, col."
return self.content[row][col]
def set(self, val, row: int, col: int):
"Set val at row, col. val can be int or dict"
prev = self.content[row][col]
if not isinstance(prev, int):
self.objects.remove(prev)
self.content[row][col] = val
if not isinstance(val, int):
self.objects.append(val)
return {'name': self.name, 'row': row, 'col': col,
'prev': prev, 'next': val}
def to_json(self):
"Return a JSON representation of the layer."
res = {
"default": self.default
}
if self.is_object_layer():
res['object'] = self.prototype.name
res['content'] = self.objects
else:
res['content'] = self.content
return res
class Map:
"A class representing a map/level/floor."
@staticmethod
def get_mod(filepath):
"Get the mod of a map from a JSON file."
file = open(filepath, mode='r', encoding='utf8')
data = json.load(file)
file.close()
return data['mod']
@staticmethod
def from_json(app, filepath):
"Load a map from a JSON file."
file = open(filepath, mode='r', encoding='utf8')
data = json.load(file)
file.close()
a_map = Map(app, data["name"], data["width"], data["height"])
for name, lay in data["layers"].items():
obj = None
if 'object' in lay:
obj = app.mod.layers[name].obj
a_map.add_layer(name, lay["default"], obj)
if 'object' in lay:
# populate with the objects
for obj in lay['content']:
a_map.layers[name].content[obj['y']][obj['x']] = obj
a_map.layers[name].objects.append(obj)
else:
# replace with the content saved
a_map.layers[name].content = lay["content"]
a_map.filepath = filepath
a_map.modcode = data["mod"]
return a_map
def __init__(self, app, name: str, max_col: int, max_row: int):
self.app = app
self.modcode = app.mod.code if app is not None and \
app.mod is not None else 'undefined'
self.name = name
self.layers = {}
self.width = max_col
self.height = max_row
self.filepath = None
def resize(self, width, height):
"Resize a map and all its layers."
self.width = width
self.height = height
for _, lay in self.layers.items():
lay.resize()
def info(self):
"Display info on the map."
print(repr(self))
if len(self.layers) == 0:
print('No layer in map')
return
for name, lay in self.layers.items():
print('<' + name + '>')
if lay.object is not None:
print(" type =", lay.object)
print(" ido =", lay.ido)
print(' ', end='')
print(*lay.content, sep='\n ')
if lay.object is not None:
for key, value in lay.objects.items():
print(f"{key:5d} : {value}")
def add_layer(self, name, default: int = 0, obj: str = None):
"Add a layer to a map."
if not isinstance(default, int):
msg = f'[ERROR] Only integer value not {default.__class__.__name__}'
raise Exception(msg)
if name in self.layers:
msg = f'[ERROR] Layer {name} already exists.'
raise Exception(msg)
self.layers[name] = Layer(self, name, default, obj)
def has_objects(self, name):
"The layer name is an object layer."
return self.layers[name].is_object_layer()
def check(self, row, col, layer=None):
"Check row, col and layer if not None."
if layer is not None and layer not in self.layers:
return False
#raise Exception(f"[ERROR] Layer {layer} not defined.")
if not 0 <= row < self.height:
return False
#raise Exception(f"[ERROR] Out of row: {row} / {self.height}")
if not 0 <= col < self.width:
return False
#raise Exception(f"[ERROR] Out of col: {col} / {self.width}")
return True
def get(self, row, col, layer=None):
"Get value at row, col in layer."
self.check(row, col, layer)
if layer is not None:
return self.layers[layer].get(row, col)
res = {}
for _, lay in self.layers.items():
res[lay.name] = lay.get(row, col)
return res
def set(self, val, row, col, layer):
"Set value at row, col in layer."
self.check(row, col, layer)
return self.layers[layer].set(val, row, col)
def set_name(self, name):
"Set the name of the map."
self.name = name
def __repr__(self):
mod_name = self.app.mod.code if self.app is not None and \
self.app.mod is not None else ''
return f"{self.name} {self.width}x{self.height}" + \
f"[{len(self.layers)}]{mod_name}"
def to_json(self):
"Return a JSON representation of the map."
data = {
"name": self.name,
"width": self.width,
"height": self.height
}
data["mod"] = self.app.mod.code if self.app is not None and \
self.app.mod is not None else ''
data["layers"] = {}
for _, lay in self.layers.items():
data["layers"][lay.name] = lay.to_json()
return data
def save(self, filepath):
"Save to a file."
file = open(filepath, mode='w', encoding='utf8')
file.write(pretty_json(self.to_json()))
file.close()
try:
file = open(filepath, mode='r', encoding='utf8')
json.load(file)
file.close()
except json.JSONDecodeError:
print('Something went wrong when trying to load map. Map may be corrupted.')
print('Stack info:')
print_exc(file=stdout)
self.filepath = filepath
if __name__ == '__main__':
# Create matrix tests
L5X10 = Layer.create_matrix(5, 10)
print(*L5X10, sep='\n')
# Map and layer tests
A_MAP = Map(None, "A map", 4, 4)
A_MAP.info()
A_MAP.add_layer('ground', 0)
A_MAP.info()
A_MAP.set(5, 3, 3, 'ground')
A_MAP.info()
A_MAP.resize(7, 7)
A_MAP.info()
# Pretty json tests
A_DICT = {'a': 5, 'b': True, 'c': 3.14}
print("1:")
print(pretty_json(A_DICT))
A_LIST = [1, 2, 3, 4, 5]
print("2:")
print(pretty_json(A_LIST))
A_MIXED = [True, [1, 2, 3], "hello"]
print("3:")
print(pretty_json(A_MIXED))
A_MATRIX = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("4:")
print(pretty_json(A_MATRIX))
A_COMBINED = {
"layers": {
"ground": [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
]
}
}
print(pretty_json(A_COMBINED))
print("5:")
A_DICT_OF_DICT = {"dA1": {"dB1": 5}, "dA2": [1, 2, 3, "hello"], "dA3": True}
print(pretty_json(A_DICT_OF_DICT))
print("Final:")
print(pretty_json(A_MAP.to_json()))
A_MAP.save("saved.map")
A_NEW_MAP = Map.from_json(None, "saved.map")
A_NEW_MAP.save("saved2.map")
print("With Unit:")
Unit = {'name': 'Content_Name', 'player': 'Meta_Player'}
A_MAP.add_layer('unit', 0, Unit)
A_MAP.set({"name": "kbot", "player": 1, "val": 28}, 3, 3, "unit")
A_MAP.info()
|
2dcf550070ecb3685b7988334da9a67c4c3b306f | stupidchen/leetcode | /src/leetcode/P117.py | 903 | 3.921875 | 4 | # Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def __add_new_node(self, queue, tail, new_node, depth):
if new_node is not None:
queue.append((new_node, depth))
return tail + 1
return tail
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root is None:
return
queue = [(root, 0)]
h = 0
t = 0
while h <= t:
this, depth = queue[h]
if h < t and queue[h + 1][1] == depth:
this.next = queue[h + 1][0]
t = self.__add_new_node(queue, t, this.left, depth + 1)
t = self.__add_new_node(queue, t, this.right, depth + 1)
h += 1 |
87dd68fff4fa625ff895bdabb33ad40c62a23abb | alanlucena/python-basic | /desafios/num_double_triple_expo.py | 392 | 4.15625 | 4 | #Algoritmo para ler um número e mostrar seu dobro, triplo e raiz quadrada
number = int(input('Escolha o número: '))
double= numero*2
triple= numero*3
expo= numero**0.5
print('\nO número escolhido foi: {}\n'
'O dobro do valor do número escolhido é: {}\n'
'O triplo do valor do número escolhido é {}\n'
'A raiz quadrada do número escolhido é {}\n'.format(number,double,triple,expo)) |
22cc7357bb63e4cae5bc752e3bd7f27f132f2053 | dgarciag1/practicanumerico | /NumSolutions/public/methods/cubic_spline.py | 3,607 | 3.59375 | 4 |
import math
import numpy as np
import sympy as sm
import sys
import strToMatrix
def cubic_spline(table):
try:
table = strToMatrix.strToMatrix(table)
x_vector = table[0].tolist()
y_vector = table[1].tolist()
except:
print("Error: check type of input values")
sys.exit(1)
try:
n = len(x_vector)
x = sm.symbols('x')
# we implement the steps of cubic splines
m = 4*(n-1)
matrix = np.zeros((m,m))
b = y_vector
#interpolation
matrix[0][0] = math.pow(x_vector[0], 3)
matrix[0][1] = math.pow(x_vector[0], 2)
matrix[0][2] = x_vector[0]
matrix[0][3] = 1
for i in range(1,n):
matrix[i][4*(i)-4] = math.pow(x_vector[i], 3)
matrix[i][4*(i)-3] = math.pow(x_vector[i], 2)
matrix[i][4*(i)-2] = x_vector[i]
matrix[i][4*(i)-1] = 1
#continuity
for i in range(1, n-1):
matrix[n-1+i][4*i-4] = math.pow(x_vector[i], 3)
matrix[n-1+i][4*i-3] = math.pow(x_vector[i], 2)
matrix[n-1+i][4*i-2] = x_vector[i]
matrix[n-1+i][4*i-1] = 1
matrix[n-1+i][4*i] = -math.pow(x_vector[i], 3)
matrix[n-1+i][4*i+1] = -math.pow(x_vector[i], 2)
matrix[n-1+i][4*i+2] = -x_vector[i]
matrix[n-1+i][4*i+3] = -1
b.append(0)
#smoothness
for i in range(1, n-1):
matrix[2*n-3+i][4*i-4] = 3 * math.pow(x_vector[i], 2)
matrix[2*n-3+i][4*i-3] = 2 * x_vector[i]
matrix[2*n-3+i][4*i-2] = 1
matrix[2*n-3+i][4*i-1] = 0
matrix[2*n-3+i][4*i] = -3 * math.pow(x_vector[i], 2)
matrix[2*n-3+i][4*i+1] = -2 * x_vector[i]
matrix[2*n-3+i][4*i+2] = -1
matrix[2*n-3+i][4*i+3] = 0
b.append(0)
#concavity
for i in range(1, n-1):
matrix[3*n-5+i][4*i-4] = 6 * x_vector[i]
matrix[3*n-5+i][4*i-3] = 2
matrix[3*n-5+i][4*i-2] = 0
matrix[3*n-5+i][4*i-1] = 0
matrix[3*n-5+i][4*i] = -6 * x_vector[i]
matrix[3*n-5+i][4*i+1] = -2
matrix[3*n-5+i][4*i+2] = 0
matrix[3*n-5+i][4*i+3] = 0
b.append(0)
#border
matrix[m-2][0] = 6 * x_vector[0]
matrix[m-2][1] = 2
b.append(0)
matrix[m-1][m-4] = 6 * x_vector[n-1]
matrix[m-1][m-3] = 2
b.append(0)
matrix = np.array(matrix)
x_vector = np.linalg.inv(matrix).dot(b)
splines_coef = []
iteration = 0
# we add the coefficients
while iteration < len(x_vector)-1:
i = []
i.append('{:.6f}'.format(x_vector[iteration]))
i.append('{:.6f}'.format(x_vector[iteration+1]))
i.append('{:.6f}'.format(x_vector[iteration+2]))
i.append('{:.6f}'.format(x_vector[iteration+3]))
iteration = iteration + 4
splines_coef.append(i)
# we form the tracers
splines = []
for i in range(len(splines_coef)):
splines.append((float(splines_coef[i][0])*(x**3))+(float(splines_coef[i][1])*(x**2))+(float(splines_coef[i][2])*x)+float(splines_coef[i][3]))
print("Tracer coefficients: ")
print(f"{splines_coef}\n")
print("Tracers: ")
print(f"{splines}\n")
except:
print("Error: Initial data error, try again")
sys.exit(1)
np.set_printoptions(precision=7)
#table = [[-1,0,3,4],[15.5,3,8,1]]
cubic_spline(sys.argv[1]) |
e844ae0b889e6b908e46d6f760d59492f4ee4354 | Gluke92/python-practice | /algorithm-practice/Algorithm-types/linked-lists.py | 269 | 3.890625 | 4 | # Linked List exploration
obj1 = {'a': True}
obj2 = obj1
obj1['a']= 'booya'
del obj1
obj2 = 'hello'
# print(obj1)
print(obj2)
#Python is garbage collected.
#if we delete the value the pointer is pointing to,
#the objects will be undefined and need
#to be reassigned
|
7492b254dac117f1c0a01e9d0099a024d84eb607 | mindcurry/InterviewBit | /Level 2/Arrays/Spiral Order Matrix II.py | 1,355 | 3.875 | 4 | '''
Given an integer A, generate a square matrix filled with elements from 1 to A2 in spiral order.
Input Format:
The first and the only argument contains an integer, A.
Output Format:
Return a 2-d matrix of size A x A satisfying the spiral order.
Constraints:
1 <= A <= 1000
Examples:
Input 1:
A = 3
Output 1:
[ [ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ] ]
Input 2:
4
Output 2:
[ [1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7] ]
'''
class Solution:
def generateMatrix(self, A):
B = [[0] * A for _ in range(A)]
L = T = 0
R = C = A - 1
d = 0
j = 1
while L <= R and T <= C:
if d == 0:
for i in range(L, R + 1):
B[T][i] = j
j += 1
T += 1
elif d == 1:
for i in range(T, C + 1):
B[i][R] = j
j += 1
R -= 1
elif d == 2:
for i in range(R, L - 1, -1):
B[C][i] = j
j += 1
C -= 1
elif d == 3:
for i in range(C, T-1, -1):
B[i][L] = j
j += 1
L += 1
d = (d + 1) % 4
return B |
3ae36b41307f1f23f8e9d1dc02a6f8448dc97933 | hiteshpindikanti/Coding_Questions | /LeetCode/water_trap.py | 1,744 | 3.578125 | 4 | def maximum(arr, start, end) -> int:
max_val = 0
index = start
if start < end:
while start < end:
if arr[start] > max_val:
index = start
max_val = arr[start]
start += 1
elif end < start:
while start > end:
if arr[start] > max_val:
index = start
max_val = arr[start]
start -= 1
return index
def addition(arr, start, end, h) -> int:
s = 0
while start < end:
s += arr[start] if arr[start] < h else h
start += 1
return s
total_water = 0
height = [5, 4, 1, 2]
i = maximum(height, 0, len(height))
j = i
while i > 0:
# left_index = height[:i].index(max(height[:i]))
left_index = maximum(height, 0, i)
# water = height[left_index] * (i - left_index - 1) - sum(height[left_index + 1:i])
water = height[left_index] * (i - left_index - 1) - addition(height, left_index + 1, i, height[left_index])
total_water += water
print("LEFT: i = {}, left_index = {}, water = {}".format(i, left_index, water))
i = left_index
while j < len(height) - 1:
# right_index = j + 1 + (len(height) - j) - 2 - height[j + 1::][::-1].index(max(height[j + 1:]))
right_index = maximum(height, len(height) - 1, j + 1)
# water = height[right_index] * (right_index - j - 1) - sum(height[j + 1:right_index])
water = height[right_index] * (right_index - j - 1) - addition(height, j + 1, right_index, height[right_index])
total_water += water
print("RIGHT: j = {}, right_index = {}, water = {}".format(j, right_index, water))
j = right_index
print("total_water = {}".format(total_water))
# height = [0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 7, 5, 3, 1, 0, 0]
|
88f8aea2cfaef6ac6d12259dffda88e9a48a9607 | MeghaSHooli/Python | /Import_KT.py | 1,356 | 4.0625 | 4 | """
Demonstration of some of the features of the import
"""
import datetime
# Create some dates
print("Creating Dates")
print("==============")
date1 = datetime.date(1999, 12, 31)
date2 = datetime.date(2000, 1, 1)
# Today's date
today = datetime.date.today()
print(date1)
print(date2)
print("")
# Compare dates
print("Comparing Dates")
print("===============")
print(date1 < date2)
print("")
# Subtracting dates
print("Subtracting Dates")
print("=================")
diff = date2 - date1
print(diff)
print(diff.days)
print("")
print("Implementing Practice Project")
#from datetime import datetime
now = datetime.datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
"""
Implementing Practice Project
"""
def name_to_number(name):
"""
Take string name as input (rock-Spock-paper-lizard-scissors)
and returns integer (0-1-2-3-4)
"""
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
print(name_to_number("myname")) # output - 0
print(name_to_number("Spock")) # output - 1
print(name_to_number("paper")) # output - 2
print(name_to_number("lizard")) # output - 3
print(name_to_number("scissors")) # output - 4 |
55b15715733d8b941a95f9d5653f8de933a1f0f1 | Saswati08/Data-Structures-and-Algorithms | /LinkedList/detect_loop_in_linked_list.py | 547 | 3.71875 | 4 | class node:
def __init__(self, val):
self.data = val
self.next = None
def detectLoop(head):
#code here
if head == None:
return False
if head.next == None:
return False
slow = head
fast = head.next
while(fast != None and fast.next != None):
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
nw = node(1)
nw.next = node(2)
nw.next.next = node(4)
nw.next.next.next = node(5)
nw.next = None
print(detecLoop(nw))
|
87165f7e10563baa2168a1b86d9158d23791fb14 | TwitterDataMining/TopicBasedSimilarity | /data_preprocessing/read_data.py | 6,851 | 3.546875 | 4 | """
read date for a tv show and prepare for topic modelling, uses the collections for specific show ie.
input : collection name, path to unique users list
process : reads from collection
output :
- csv file of preprocessed tweets - one line per user
- csv file of preprocessed tweets - one line = username- single tweet
"""
from pymongo import MongoClient
import argparse
import os
import logging
import datetime
import numpy as np
import nltk
from nltk.stem.snowball import SnowballStemmer
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
from functools32 import lru_cache
import re
TWEET_PER_USER = 1000
# Input arguments
PROGRAM_DESCRIPTION = "Read tweets from collection"
parser = argparse.ArgumentParser(description=PROGRAM_DESCRIPTION)
parser.add_argument('collection_name', type=str, help='collection_to_read_tweets')
parser.add_argument('directory', type=str, help='directory to store')
parser.add_argument('unique_user_file', type=str, help='path to unique user list in csv')
parser.add_argument('prefix', type=str, help='used in output file name eg hashtag')
args = vars(parser.parse_args())
# initializing lemmatizer
stemmer = SnowballStemmer("english")
wordnet_lemmatizer = WordNetLemmatizer()
lemmatize = lru_cache(maxsize=50000)(wordnet_lemmatizer.lemmatize)
def main():
collection_name = args['collection_name']
dir = args['directory']
unique_user_file = args['unique_user_file']
DIRECTORY = args['prefix']
try:
os.stat(dir)
except:
os.mkdir(dir)
log_file = dir + '/' + DIRECTORY + "_log.log"
logging.basicConfig(filename=log_file, level=logging.DEBUG, format='%(asctime)s %(message)s')
logging.debug("reading users fof topic modelling: {0} for hashtags : {1}".format(datetime.date.today(), collection_name))
coll = get_mongo_connection()[collection_name]
user_list = get_unique_users_fromfile(unique_user_file)
total_users = 0
discarded= 0
with open(dir + '/' + DIRECTORY + '_raw_username.csv', 'w') as raw_u,\
open(dir + '/' + DIRECTORY + '_username.csv', 'w') as f,\
open(dir + '/' + DIRECTORY + '_text.csv', 'w') as ftext, \
open(dir + '/' + DIRECTORY + '_s_username.csv', 'w') as fs, \
open(dir + '/' + DIRECTORY + '_s_text.csv', 'w') as fstext:
for user in user_list:
total_users +=1
if total_users % 50 ==0:
logging.debug("User processed : {0}".format(total_users))
tweets, u_tweets = get_tweet_preprocessed(coll, user)
if len(tweets) < 6:
discarded += 1
continue
for tweet, u_tweet in zip(tweets, u_tweets):
raw_u.write(str(user).encode('utf-8') + ",")
raw_u.write(u_tweet.encode('utf-8') + '\n')
fs.write(str(user) + ",")
fs.write(tweet + '\n')
fstext.write(tweet + '\n')
f.write(str(user) + ",")
text = " ".join(tweets)
f.write(text + "\n")
ftext.write(text + "\n")
logging.debug("Total unique users : {0}".format(total_users))
logging.debug("discarded tweets < 10 : {0}".format(discarded))
def get_tweet_preprocessed(coll, user):
query ={}
query['user_id'] = user
query['lang'] = 'en'
projection = {'user_id' : 1, 'text': 1}
tweets = coll.find(query, projection)
print("user {0} tweets {1}".format(user, tweets.count()))
tweet_list = []
unprocessed_tweets = []
count = 0
for tweet in tweets:
count += 1
unprocessed_tweets.append(remove_puct(tweet['text']))
if count >= TWEET_PER_USER:
break
tweet_list = preprocess(unprocessed_tweets)
return tweet_list, unprocessed_tweets
def remove_puct(text):
text = remove_urls(text)
text = remove_non_ascii(text)
text = text.replace(',', '')
text = re.sub(r"""[\'\"]""", '', text)
text = ' '.join(text.split())
return text
def preprocess(tweet_list):
return_list = []
stop_words = stop_words_list()
for tweet in tweet_list:
return_list.append(tokenize_and_lemmatize(tweet, stop_words))
return return_list
def get_unique_users(coll):
return coll.distinct('user_id')
def get_unique_users_fromfile(filename):
users = []
with open(filename, 'rb') as f:
users = map(int, f.readlines())
print users
return users
def get_mongo_connection(host="localhost", port=27017, db_name="stream_store"):
return MongoClient(host=host, port=port)[db_name]
def remove_non_ascii(s):
return "".join(i for i in s if ord(i) < 128)
def stop_words_list():
"""
A stop list specific to the observed timelines composed of noisy words
This list would change for different set of timelines
"""
stop_words = ['bc', 'http', 'https', 'co', 'com','rt', 'one', 'us', 'new',
'lol', 'may', 'get', 'want', 'like', 'love', 'no', 'thank', 'would', 'thanks',
'good', 'much', 'low', 'roger']
stoplist = set( nltk.corpus.stopwords.words("english") + stop_words)
return stoplist
def remove_urls(text):
text = re.sub(r"(?:\@|http?\://)\S+", "", text)
text = re.sub(r"(?:\@|https?\://)\S+", "", text)
return text
def get_wordnet_pos(treebank_tag):
if treebank_tag.startswith('J'):
return 'a'
elif treebank_tag.startswith('V'):
return 'v'
elif treebank_tag.startswith('N'):
return 'n'
elif treebank_tag.startswith('R'):
return 'r'
else:
return None
def tokenize(text):
"""
helper function to readTweets() removes url and tokenizes text
:param text
"""
text = remove_urls(text)
text = remove_non_ascii(text)
text = re.sub(r"""[\'\"]""",'', text)
regexps = (
r"""(?:[\w_]+)""", # regular word
r"""(?:[a-z][a-z'\-_]+[a-z])""" # word with an apostrophe or a dash
)
tokens_regexp = re.compile(r"""(%s)""" % "|".join(regexps),
re.VERBOSE | re.I | re.UNICODE)
return tokens_regexp.findall(text)
def tokenize_and_lemmatize(text, stop_words):
# get the tokens, lowercase - replace acronym
tokens = [item.strip().lower() for item in tokenize(text)]
tokens_pos = pos_tag(tokens)
words = []
for token in tokens_pos:
pos = get_wordnet_pos(token[1])
# if verb, noun, adj or adverb include them after lemmatization
if pos is not None and token[0] not in stop_words and len(token[0]) > 3:
try:
tok = lemmatize(token[0], pos)
words.append(tok)
except UnicodeDecodeError:
pass
# print words
return " ".join(words)
if __name__ == "__main__":
main()
|
19b19f260fbfbba1cebdb23d18d8e521bce30582 | leobang17/algorithms-assignment | /Algorithms_Midterm/Algorithms_Midterm.py | 8,000 | 3.8125 | 4 |
import random
import time
import matplotlib.pyplot as plt
import sys
N1 = 100
N2 = 1000
N3 = 10000
def random_array_creator(arr1, arr2, arr3):
arr1.append(random.sample(range(1, N1 + 1), N1))
arr2.append(random.sample(range(1, N2 + 1), N2))
arr3.append(random.sample(range(1, N3 + 1), N3))
return arr1[0], arr2[0], arr3[0]
def bubble_sort(arr):
for i in range(len(arr) - 1):
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
return arr
def insertion_sort(arr):
for i in range(len(arr) - 1):
key = arr[i + 1]
for j in range(i, -1, -1):
if arr[j] > key:
arr[j + 1] = arr[j]
arr[j] = key
else:
break
return arr
def merge_sort_merge(left_arr, right_arr):
if not (len(left_arr) and len(right_arr)):
return left_arr or right_arr
temp = []
i = 0
j = 0
while (len(temp) < len(left_arr) + len(right_arr) ):
if i == len(left_arr) or j == len(right_arr):
temp.extend(left_arr[i:] or right_arr[j:])
elif left_arr[i] < right_arr[j]:
temp.append(left_arr[i])
i += 1
else:
temp.append(right_arr[j])
j += 1
return temp
def merge_sort_divide(arr):
middle = len(arr) // 2
right_arr = arr[:middle]
left_arr = arr[middle:]
if len(arr) <= 1:
return arr
return merge_sort_merge(merge_sort_divide(right_arr), merge_sort_divide(left_arr))
def quicksort(a, start, end):
if start < end:
pivot = a[start]
count = start + 1
for i in range(start, end):
if pivot > a[i + 1]:
if (end - start == 1):
count += 1
break
temp = a[count]
a[count] = a[i + 1]
a[i + 1] = temp
count += 1
a[start] = a[count - 1]
a[count - 1] = pivot
quicksort(a, start = start, end = count - 2)
quicksort(a, start = count, end = end)
return a
def find_max_min(arr):
small = arr[0]
big = arr[0]
for i in range(1, len(arr)):
if small > arr[i]:
small = arr[i]
if big < arr[i]:
big = arr[i]
return small, big
def radix_sort(arr):
big = find_max_min(arr)[1]
decimal_count = 1
stop = big
temp = arr
while(1):
if (stop < 10):
break
else:
stop = stop // 10
decimal_count += 1
for count in range(0, decimal_count):
bucket = [[], [], [], [], [], [], [], [], [], []]
for i in range(len(arr)):
index = (temp[i] // (10 ** count) ) % 10
bucket[index].append(temp[i])
temp = []
for i in range(10):
for j in range(len(bucket[i])):
temp.append(bucket[i][j])
# print("count", count + 1, "\n", temp)
return temp
def bucket_sort(arr, bucket_number):
small, big = find_max_min(arr)
bucket_size = (big - small + 1) // bucket_number
bucket = []
temp = []
for i in range(bucket_number):
bucket.append([i])
print(bucket)
for i in range(len(arr)):
if arr[i] % bucket_size == 0:
index = (arr[i] // bucket_size) - 1
else:
index = (arr[i] // bucket_size)
bucket[index].append(arr[i])
for i in range(bucket_number):
bucket[i] = bucket[i][1:]
quicksort(bucket[i], 0, bucket_size - 1)
for i in range(bucket_number):
for j in range(bucket_size):
temp.append(bucket[i][j])
return temp
def check_execution_time(func_number, arr):
if func_number == 1:
start_time = time.time()
arr = bubble_sort(arr)
execution_time = time.time() - start_time
elif func_number == 2:
start_time = time.time()
arr = insertion_sort(arr)
execution_time = time.time() - start_time
elif func_number == 3:
start_time = time.time()
arr = merge_sort_divide(arr)
execution_time = time.time() - start_time
elif func_number == 4:
start_time = time.time()
arr = radix_sort(arr)
execution_time = time.time() - start_time
elif func_number == 5:
start_time = time.time()
arr = quicksort(arr, 0, len(arr) - 1)
execution_time = time.time() - start_time
elif func_number == 6:
bucket_num = 10
if len(arr) == 1000:
bucket_num = 20
elif len(arr) == 10000:
bucket_num = 50
start_time = time.time()
arr = bucket_sort(arr, bucket_num)
execution_time = time.time() - start_time
return execution_time
def plot_execution_times(time_bubble, time_insertion, time_merge, time_radix, time_quick, time_bucket):
input_size = [N1, N2, N3]
plt.figure(figsize = (10, 8))
plt.title("execution times of sorting algorithms")
plt.plot(input_size, time_bubble, '-', color = "blue", label = "bubble sort")
plt.plot(input_size, time_insertion, '-', color = "red", label ="insertion sort")
plt.plot(input_size, time_merge, '-', color = "green", label = "merge sort")
plt.plot(input_size, time_radix, '-', color = "yellow", label = "radix sort")
plt.plot(input_size, time_quick, '-', color = "purple", label = "quick sort")
plt.plot(input_size, time_bucket, '-', color = "orange", label = "bucket sort")
plt.xlabel("input size: 100, 1000, 10000")
plt.ylabel("execution time")
plt.legend(loc = 2)
plt.grid(True)
plt.tight_layout()
plt.show()
def run():
arr1 = []
arr2 = []
arr3 = []
arr1, arr2, arr3 = random_array_creator(arr1, arr2, arr3)
temp1, temp2, temp3 = arr1, arr2, arr3
# bubble sort
time_bubble = []
time_bubble.append(check_execution_time(1, temp1))
time_bubble.append(check_execution_time(1, temp2))
time_bubble.append(check_execution_time(1, temp3))
# insertion sort
temp1, temp2, temp3 = arr1, arr2, arr3
time_insertion = []
time_insertion.append(check_execution_time(2, temp1))
time_insertion.append(check_execution_time(2, temp2))
time_insertion.append(check_execution_time(2, temp3))
# merge sort
temp1, temp2, temp3 = arr1, arr2, arr3
time_merge = []
time_merge.append(check_execution_time(3, temp1))
time_merge.append(check_execution_time(3, temp2))
time_merge.append(check_execution_time(3, temp3))
# radix sort
temp1, temp2, temp3 = arr1, arr2, arr3
time_radix = []
time_radix.append(check_execution_time(4, temp1))
time_radix.append(check_execution_time(4, temp2))
time_radix.append(check_execution_time(4, temp3))
# quick sort
temp1, temp2, temp3 = arr1, arr2, arr3
time_quick = []
time_quick.append(check_execution_time(5, temp1))
time_quick.append(check_execution_time(5, temp2))
# time_quick.append(check_execution_time(5, temp3))
time_quick.append(1)
# bucket sort
temp1, temp2, temp3 = arr1, arr2, arr3
time_bucket = []
time_bucket.append(check_execution_time(6, temp1))
time_bucket.append(check_execution_time(6, temp2))
time_bucket.append(check_execution_time(6, temp3))
plot_execution_times(time_bubble, time_insertion, time_merge, time_radix, time_quick, time_bucket)
sys.setrecursionlimit(4000)
run() |
4cbe4f038d3f425eb7669b782f5c53058e2dce65 | ferdi-oktavian/Python | /TURTLE/turtle2.py | 725 | 3.578125 | 4 | import turtle
import random
from turtle import *
fer = turtle.Turtle()
fer.speed(0)
fer.width(5)
colors = ['red', 'green', 'blue', 'purple', 'pink']
def up():
fer.setheading(90)
fer.forward(100)
def down():
fer.setheading(270)
fer.forward(100)
def left():
fer.setheading(180)
fer.forward(100)
def right():
fer.setheading(0)
fer.forward(100)
def clickleft(x,y):
fer.color(random.choice(colors))
def clickright(x,y):
fer.stamp()
turtle.listen()
turtle.onscreenclick(clickleft, 1)
turtle.onscreenclick(clickright, 3)
turtle.onkey(up, 'Up')
turtle.onkey(down, 'Down')
turtle.onkey(left, 'Left')
turtle.onkey(right, 'Right')
turtle.mainloop() |
d0174ee39ca9a736fa7e7df94667a7a47714a5c3 | EgorPopelyaev/pystudy | /projects/skeleton/FirstProject/firstCalc.py | 439 | 3.859375 | 4 | from sys import argv
script, value1, value2 = argv
def add(val1, val2):
return int(val1) + int(val2)
def dif(val1, val2):
int_val1 = int(val1)
int_val2 = int(val2)
if (int_val1 > int_val2):
return int_val1 - int_val2
else:
return int_val2 - int_val1
addition = add(value1, value2)
print "The sum of input values: %d" % addition
difference = dif(value1, value2)
print "The difference between input values: %d" % difference
|
f4deb01d9afb80c69e91ed5d68ccaa4a9e315946 | shri-datta-madhira/LeetCode | /Sum of All Odd Length Subarrays.py | 542 | 3.953125 | 4 | """
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr.
"""
class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
s = 0
for i in range(len(arr)):
# j = i
for j in range(i, len(arr), 2):
# print(arr[i:j+1])
# j += 2
s += sum(arr[i:j + 1])
# break
return s
|
9fe5ec2bf4b8dcb7ec2d04ca5fd5c1590a2724e1 | bunnyxx/python | /password fetcher.py | 860 | 4.1875 | 4 | #! python3
# pw.py - password program
import pyperclip
password = {"email": "homura", "discord": "kyouko", "youtube": "madoka"}
accountName = str(input("Account name? "))
def passwordObtainer(account):
if account == "quit":
print("Thank you for using pwmanager")
elif account in password:
pyperclip.copy(password[account])
pyperclip.paste()
print("Password:",password[account],"was pasted to the clipboard!")
else:
print("There is no account named",account+".")
adder = input("Add one? (y/n) ")
if adder == "y":
print("Account name",account)
newPw = str(input('What is the password?: '))
password[account] = newPw
print("Account",account,"was added to the password database.")
newAccName = str(input("Account name?: "))
passwordObtainer(newAccName)
passwordObtainer(accountName)
|
2bfe84dacf7afff99e123e448444d01c2c61df05 | insomn14/CTFtime2020 | /TAMUctf_2020/Reversing/RUSTY_AT_REVERSING/solve.py | 347 | 3.734375 | 4 | def decrypt(a1):
v3 = 228
for i in range(len(a1)):
v2 = v3
v3 = a1[i]
a1[i] = chr(a1[i]^v2)
return a1
flag = [0x83, 0xea, 0x8d, 0xe8, 0x85, 0xfe, 0x93, 0xe1, 0xbe, 0xcd, 0xb9, 0xd8, 0xaa, 0xc1, 0x9e, 0xf7, 0xa8, 0xce, 0xab, 0xce, 0xa2, 0xfd, 0x8f, 0xfa, 0x89, 0xfd, 0x84, 0xf9]
print(''.join(decrypt(flag)))
|
5b96b3ddcc2765aafbb02d61bec76bd8d23d15cd | sachinjose/Coding-Prep | /CTCI/Tree & Graph/q.4.11.py | 1,381 | 3.8125 | 4 | import random
class Node:
def __init__(self,item):
self.item = item
self.left = None
self.right = None
self.size = 1
def get_size(self):
return self.size
def get_item(self):
return self.item
def getRandomNode(self):
if(self.left):
leftSize = self.left.get_size();
else:
leftSize = 0
index = random.randint(0,self.get_size())
if(index < leftSize):
if(self.left):
return self.left.getRandomNode()
else:
return self.item
elif (index == leftSize):
return self.item
else:
if (self.right):
return self.right.getRandomNode()
else:
return self.item
def insertInOrder(self,item):
if(item<self.item):
if(self.left):
self.left.insertInOrder(item)
else:
self.left = Node(item)
else:
if(self.right):
self.right.insertInOrder(item)
else:
self.right = Node(item)
self.size+=1
def find(self,value):
if self.item == value:
return self
elif (value <= self.item):
if(self.left):
self.left.find(value)
else:
return None
elif(value >= self.item):
if(self.right):
self.right.find(value)
else:
return None
else:
return None
root = Node(10)
root.insertInOrder(5)
root.insertInOrder(-3)
root.insertInOrder(3)
root.insertInOrder(2)
root.insertInOrder(11)
root.insertInOrder(3)
root.insertInOrder(-2)
root.insertInOrder(1)
print(root.getRandomNode())
|
65b988532fa8eb321d2e8342f7bf2fc0b635f5dd | huangbow/INF553 | /Assignment2/Huang_Bowen_multiply.py | 1,007 | 3.59375 | 4 | import MapReduce
import sys
mr=MapReduce.MapReduce()
def mapper(record):
#get matrix, string
key=record[0]
#get i
x=record[1]
#get j
y=record[2]
#get value
val=record[3]
for k in range(5):
if key=="a":
mr.emit_intermediate((x,k),(key,y,val))
elif key=="b":
mr.emit_intermediate((k,y),(key,x,val))
def reducer(key,list_of_value):
#store the list of the row in matrix A
a_elm=[]
#store the list of the column in matrix B
b_elm=[]
#the value of (i,k) in the solution of A(i,j)*B(j,k)
total=0
#the structure of the element in list_of_value:(matrix,row or column,val)
#make the value lists for matrix A and B separately
for v in list_of_value:
#decide whether matrix is a
if v[0]=="a":
a_elm.append((v[1],v[2]))
elif v[0]=="b":
b_elm.append((v[1],v[2]))
#matrix multiplication
for a in a_elm:
for b in b_elm:
if a[0]==b[0]:
total+=a[1]*b[1]
mr.emit((key,total))
if __name__ == '__main__':
inputdata=open(sys.argv[1])
mr.execute(inputdata,mapper,reducer) |
ab8b86f7a59bc1fb3999fcd17172e73cfe586747 | gabriellaec/desoft-analise-exercicios | /backup/user_020/ch152_2020_04_13_20_16_20_476223.py | 284 | 3.5625 | 4 | def verifica_preco(nome, livros, cores):
nome = input("Insira o nome do livro: ")
livros = {}
cores = {}
if nome in livros:
nome = livros[nome]
print('{0}' .format(cores))
else:
print("O livro {0} não existe!" .format(nome))
|
3cd4958c717d440738bb03decddcf49a9077de39 | learner-wming/mypython_leaning | /判断和循环.py | 2,881 | 3.546875 | 4 | # for i in range(1,10):
# for j in range(1,i+1):
# print(i,"X",j,"=",i*j,end=" ")
# print()
# #九九乘法表
# for h in range(1,4):
# print("黄红绿")
# h=h+1
# for r in range(4,31):
# print(" 红绿")
# r=r+1
# for g in range(31,36):
# print(" 绿")
# g=g+1
# # #打印红绿灯 黄灯3次 红灯30次 绿灯35次 注意缩进
# light = {"黄灯":3,"红灯":30,"绿灯":35}
# for i in light:
# for j in range(light[i]):
# print(i,"还有",light[i]-j,"秒")
# c=1
# p=1
# xinxi = {}
# while c:
# username = input("账号:")
# if len(username)>=5 and len(username)<=8:
# if username[0] in "qwertyuioplkjhgfdsazxcvbnm":
# xinxi["账号"]=username
# while p: #多谢一个循环
# password = input("密码:")
# if len(password)>=6 and len(password)<=12:
# xinxi["密码"]=password
# print("注册成功",xinxi)
# exit()
# else:
# print("请输入6-12位密码") #问题出现在这个地方
# p=1 #这里调回到第二个while 而不是之前的c=1(调回第一个while)
# else:
# print("账号必须以小写字母开头")
# c=1
# else:
# print("请输入5-8账号")
# c=1
# exit() #最后的成功
#现在有一个问题就是 账号输入符合的时候 如果密码不符合的话 一直输到密码合适 但是此时又会进入新的账号输入 此前的密码前功尽弃
#哇 经过一番琢磨 我出来结果啦哈哈哈哈哈哈哈 为了让上一步成功的账号能够保存
# 一定要让密码这一步 跳会到账号正确之后的代码块 而不是直接回到原地的while
#新的问题就是 不知道为什么成功之后 还跳回第一个循环
#好了 我在和第一个while的平级 的最后加了一个exit() 成功了!
# #老师的
# u= input("账号:")
# p= input("密码:")
# if len(u)>=5 and len(u)<=8:
# if u[0] in "qwertyuioplkjhgfdsazxcvbnm":
# if len(p)>=6 and len(p)<=12:
# print("注册成功",{u:p})
# else:
# print("请输入6-12位密码")
# else:
# print("账号必须是小写字母开头")
# else:
# print("账号必须是5-8为")
# def checkname(u):
# if len(u)>=5 and len(u)<=8:
# if u[0] in "qwertyuioplkjhgfdsazxcvbnm":
# print("ok")
# else:
# print("账号必须是小写字母开头")
# else:
# print("账号必须是5-8为")
# checkname("qjfosn")
# # 两个数相加
# def jia(a,b):
# c=a+b
# print("两个数的和是",c)
# yi=int(input("请输入第一个数:"))
# er=int(input("请输入第二个数:"))
# jia(yi,er)
|
e2e0a21b8ca9b6fa66a087ade8de453fcdc6e6f6 | BasharOumari/ddmin-algorithm | /ddmin_alg/ddmin.py | 3,103 | 3.53125 | 4 | import itertools as iters
import argparse
n = 2
checkNValues = []
parser = argparse.ArgumentParser(description="`\n Usage python ddmin.py -s <sequence> -f <fail_input>")
parser.add_argument("-s", type=list, dest="sequence", help="ints or chars sequence ")
parser.add_argument("-f", dest="fail", help="The expected fail input")
parsed_args = parser.parse_args()
def main():
try:
s = parsed_args.sequence
f = parsed_args.fail
ddmin(s, f)
except Exception:
print(parser.description)
exit(0)
def ddmin(sequence, fail):
if len(sequence) == 1:
return sequence
else:
print(Test(sequence, fail))
# chunkIt()
# Takes a sequence as list and the failing input and runs the core of the algorithm
def Test(sequence, fail):
global n
global checkNValues
boolList = []
slicedList = chunkIt(sequence, n)
removedChunckAndMergedList = removeChunckAndMergeRest(slicedList)
removedChunckRevesed = removedChunckAndMergedList[:: -1]
alist = countDuplicates(removedChunckRevesed, fail)
checkNValues.append(n)
print("n = ", n)
for i in range(len(removedChunckRevesed)):
if not 0 <= alist[i] <= 1:
boolList.append(False)
print(removedChunckRevesed[i], "==> FAIL")
else:
boolList.append(True)
print(removedChunckRevesed[i], "==> PASS")
if len(checkNValues) >= 4 and checkNValues[-1] == 2 and checkNValues[-2] == 2:
print("Can't split anymore n =", n)
print(removedChunckRevesed)
exit()
if n == 8 and all(boolList):
print(removedChunckRevesed)
print("Can't split anymore n =", n)
exit()
if all(boolList):
n = min(2 * n, len(sequence))
Test(sequence, fail)
else:
n = max(n - 1, 2)
for i in range(len(slicedList)):
if not boolList[i]:
Test(removedChunckRevesed[i], fail)
# Chuncks the sequence into small sublists of the same length
def chunkIt(seq, num):
if num == 0:
return seq
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
# Gives combinations of the cuncked lists of lists the sublists.
# And deletes chunck 1..len(seq) and cmbine them
def removeChunckAndMergeRest(a_list):
removedChunck = []
list_of_tuples_combinations = list(iters.combinations(a_list, len(a_list) - 1))
list_of_lists_combinations = [list(elem) for elem in list_of_tuples_combinations]
for elem in list_of_lists_combinations:
joinSublists = list(iters.chain.from_iterable(elem))
removedChunck.append(joinSublists)
return removedChunck
# Counts the duplicates of each sublist for a given number
def countDuplicates(sequence, fail):
a = list(map(lambda x: x.count(fail), sequence))
return a
# Flattens a list
def toList(alist):
flat_list = [item for sublist in alist for item in sublist]
return flat_list
if __name__ == '__main__':
main()
|
0684b6121c8e514a72c8a3cb3a4db9a7e061f76a | Kanres-GH/Pokolenie-Python-Stepik | /Условный оператор/Логические операции/Ход короля (X).py | 191 | 3.796875 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if (x1+1==x2 or x1-1==x2 or x1==x2) and (y1+1==y2 or y1-1==y2 or y1==y2):
print('YES')
else:
print('NO') |
caa7be05c568257af04df61927bcdc32a081a5cb | guhaiqiao/SmartCar | /Smartcar_PC/extdata.py | 1,958 | 3.59375 | 4 | ########################
# 此模块包含读取外部数据文件的相关类
########################
class Graph:
def __init__(self):
self.x = []
self.y = []
self.line = []
self.point_num = 0
def read(self, file):
self.line = []
f = open(file, 'r')
info = f.readlines()
self.point_num = len(info)
for i in range(self.point_num):
line = [0 for _ in range(self.point_num)]
if i != (len(info) - 1):
info[i] = info[i][:-1]
info[i] = [int(x) for x in info[i].split()]
self.x.append(info[i][1])
self.y.append(info[i][2])
for j in info[i][3:]:
line[j - 1] = 1
self.line.append(line)
class Traffic:
def __init__(self, point_num=0):
self.line = []
self.original_data = ''
self.point_num = point_num
for i in range(point_num):
self.line.append([0 for _ in range(point_num)])
def read(self, file):
self.line = []
f = open(file, 'r')
self.original_data = f.read()
f.seek(0)
lines = f.readlines()
self.point_num = len(lines)
for i in range(0, self.point_num):
line = []
for k in range(0, self.point_num):
line.append(0)
if i != (len(lines) - 1):
lines[i] = lines[i][:-1]
lines[i] = [int(x) for x in lines[i].split()]
for j in range(1, len(lines[i]), 2):
line[lines[i][j] - 1] = lines[i][j + 1]
self.line.append(line)
class Team:
def __init__(self):
self.team_names = []
self.team_macs = []
def read(self, file):
f = open(file)
for name in f:
self.team_names.append(name.strip('\n').split(' ')[0])
self.team_macs.append(name.strip('\n').split(' ')[1])
f.close()
|
b47e7b5bd3b221619f8a9ef3b589f0a7b2890be9 | alvinoum/project1_count | /name7.py | 1,540 | 4 | 4 | # Ask for user's name and display is back
# Ask user for a number input n, then count from 0 to n on the screen
# Learn and use the best practice coding standards and conventions
# Modify the program to count by 2s or some other incrment
# Sanitize all input and test to verify!
# And error-checking and graceful error handling
# Naming conventions are all in lowercase due to multiple programs
# Do not name the folder the same as the program...
# Save as new versions and consider a changelog
person = input ('Enter your name: ')
print ('Hello ', person)
# Alphabet p
while True:
try:
input = int(person('Enter your name using only the Alphabet. '))
# Check if input uses only Alphabet
if input in range (a,z):
break
else:
print ('Please use only the Alphabet.')
except:
print ('That is not in the Alphabet!')
# filter only letters in input
def person(input):
valids = []
for character in input:
if character in letters:
valid.append( character)
return (valids)
a = 0
b = 1
count = 0
#maxNum = 100
print ('Enter numbers to count by.')
print ('Enter 0 to quit.')
#converted string to integer
maxNum = int(input('Please enter a number over 0: '))
#Need to add validation and sani
#Nothing lower then 0
#while count < max_count:
# count = count +
#while a != 0:
# while s < 100:
# print ('Count by:', s)
# s = a + s
# print (a)
for i in range(0, maxNum, 2):
print(i) |
b7b65f2b16d791e431a749ef923a3886c642a97a | OnsJannet/holbertonschool-web_back_end | /0x00-python_variable_annotations/2-floor.py | 203 | 3.90625 | 4 | #!/usr/bin/env python3
'''
takes a float n as argument
and returns the floor of the float as an int
'''
import math
def floor(n: float) -> int:
''' Return floor of n.'''
return math.floor(n)
|
19f725d96b264e36cf979735636ea2fae87848b5 | mikaav/Learn-Python | /For10.py | 207 | 3.828125 | 4 | # Дано целое число N (> 0). Найти сумму 1 + 1/2 + 1/3 + ... + 1/N (вещественное число).
n = int(input())
s = 0
for i in range(1, n + 1):
s += 1 / i
print(s)
|
91f101e7c55e1bed760e22b33919cdf4c96ec59e | Palheiros/Python_exercises | /elif_categ_preco.py | 452 | 3.84375 | 4 | # Programa 4.7 - Categoria x Preço usando elif
categoria = int(input("Digite a categoria do produto (1 a 5): "))
if categoria == 1:
preço = 10
elif categoria == 2:
preço = 18
elif categoria == 3:
preço = 23
elif categoria == 4:
preço = 26
elif categoria == 5:
preço = 31
else:
print("Categoria inválida, digite um valor entre 1 e 5!")
preço = 0
print(f"O preço do produto é: R${preço:.2f}")
|
55dc54610d53dfc091415c60e8b663887a8a7185 | greenfox-zerda-lasers/bednayb | /week-03/day-04/43.py | 351 | 3.859375 | 4 | filename = 'alma.txt'
# create a function that prints the content of the
# file given in the input
fname = "cv-anakin.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
print(line)
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
|
708e46fc404c1f65edfadf4eede6627242b35b10 | LizzieDeng/kalman_fliter_analysis | /docs/cornell CS class/lesson 25. Advanced Error/demos/read5.py | 703 | 4.1875 | 4 | """
A simple application to show off try-except
This one shows off putting an error into a variable.
Author: Walker M. White (wmw2)
Date: October 28, 2017 (Python 3 Version)
"""
def main():
"""
Get some input from the user
"""
try:
value = input('Number: ') # get number from user
x = float(value) # convert string to float
print('The next number is '+repr(x+1))
if x > 10:
assert 1 == 2
except ValueError as e:
print(e.args[0])
print('Hey! That is not a number!')
except AssertionError:
print('That is out of bounds')
print('Program is done')
# Script Code
if __name__ == '__main__':
main() |
64dbc6a1c55d6d975b718184b2dac5addba130cc | oybektoirov/Project-Euler | /P7_10001st_prime.py | 404 | 3.765625 | 4 | def n_prime(limit):
num = 7
prime_list = [2, 3, 5]
while True:
if is_prime(num, prime_list):
prime_list.append(num)
if len(prime_list) == limit:
return prime_list[-1]
num += 2
def is_prime(num, prime_list):
for i in prime_list:
if num % i == 0: return False
return True
print n_prime(10001)
|
7d7964ed6704e81c532f13430df28dc8ca1a11b7 | hualuohuasheng/AutomationTestFramework_appium | /testspace/matplotlib/die.py | 302 | 3.578125 | 4 | # -*- coding:utf-8 -*-
from random import randint
class Die():
def __init__(self,num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1,self.num_sides)
die = Die()
results = []
for roll_num in range(100):
results.append(die.roll())
print(results) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.