blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
7ad07e51fefa4c5118192f6bab9b52c4fe3aa542 | mouyang2001/SOFTENG-284 | /assignment-1/task1.py | 748 | 3.609375 | 4 | # Author: Matthew Ouyang
# Task: find the maximum profit from a list of stock prices
# Commands to execute code:
# > python3 task1.py < canvas.in > myout1.txt
# > diff myout1.txt canvas.out1
import sys
# more efficient solution O(n)
def find_max_profit(prices, length):
max_profit = prices[1] - prices[0]
min_price = prices[0]
for i in range(1,length):
if (prices[i] - min_price > max_profit):
max_profit = prices[i] - min_price
if (prices[i] < min_price):
min_price = prices[i]
return max_profit
# driver code stdin/stdout
for line in sys.stdin:
prices = [int(s) for s in line.split() if s.isdigit()]
length = prices.pop(0)
if length >= 2:
sys.stdout.write(str(find_max_profit(prices, length)) + '\n')
|
53d7acce0c9cbdc2b171ede0a72f9207d7a19f01 | jaychsu/algorithm | /lintcode/611_knight_shortest_path.py | 1,336 | 4.03125 | 4 | """
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
V = (
(-2, -1),
( 2, 1),
(-2, 1),
( 2, -1),
(-1, -2),
( 1, 2),
(-1, 2),
( 1, -2),
)
"""
@param: G: a chessboard included 0 (false) and 1 (true)
@param: S: a point
@param: T: a point
@return: the shortest path
"""
def shortestPath(self, G, S, T):
if not G or not S or not T:
return -1
INFINITY = float('inf')
m, n = len(G), len(G[0])
min_steps = [[INFINITY] * n for _ in range(m)]
queue = [S]
_queue = None
_x = _y = steps = 0
while queue:
_queue = []
steps += 1
for P in queue:
for dx, dy in self.V:
_x = P.x + dx
_y = P.y + dy
if (0 <= _x < m and 0 <= _y < n and
not G[_x][_y] and
steps < min_steps[_x][_y]):
if _x == T.x and _y == T.y:
return steps
min_steps[_x][_y] = steps
_queue.append(Point(_x, _y))
queue = _queue
return -1
|
f6ca0ba07ae817412cd3c200e61d8cd4ca111b14 | hun-a/learn-the-python-basic | /src/03.list.py | 1,158 | 4.09375 | 4 | # https://wikidocs.net/14
# List
odd = [1, 3, 5, 7, 9]
a = []
b = [1, 2, 3]
c = ['Life', 'is', 'too', 'short']
d = [1, 2, 'Life', 'is']
e = [1, 2, ['Life', 'is']]
print(a, b, c, d, e)
# Indexing and slicing
print(b[0], b[1], b[2])
print(b[0] + b[1] + b[2])
print(b[-1])
a = [1, 2, 3, ['a', 'b', 'c']]
print(a[0])
print(a[-1])
print(a[3])
print(a[-1][0])
print(a[-1][1])
print(a[-1][2])
a = [1, 2, 3, 4, 5]
print(a[0:2])
a = '12345'
print(a[0:2])
a = [1, 2, 3, 4, 5]
b = a[:2]
c = a[2:]
print(b)
print(c)
# Calculate the list
a = [1, 2, 3]
b = [4, 5, 6]
print(a + b)
print(a * 3)
print(len(a))
# Mutate the list
a = [1, 2, 3]
a[2] = 4
print(a)
del a[1]
print(a)
a = [1, 2, 3, 4, 5]
del a[2:]
print(a)
# List functions
a = [1, 2, 3]
a.append(4)
print(a)
a.append([5, 6])
print(a)
a = [1, 4, 3, 2]
a.sort()
print(a)
a = ['a', 'c', 'b']
a.sort()
print(a)
a.reverse()
print(a)
print(a.index('a'))
print(a.index('b'))
a = [1, 2, 3]
a.insert(3, 5)
print(a)
a = [1, 2, 3, 1, 2, 3]
a.remove(3)
print(a)
a.remove(3)
print(a)
print(a.pop())
print(a)
print(a.pop(0))
print(a)
a = [1, 2, 3, 1]
print(a.count(1))
a.extend([4, 5])
print(a)
print(a + [4, 5]) |
6c741be9668e504c84b48a0d27aba7f6fe0a1d1b | Mandeep5138/Study | /PYTHON CODES/Rolling_Hash_String_compare.py | 646 | 3.71875 | 4 | text = "Python"
pattern='th'
X=len(text)
Y=len(pattern)
d=256 #positional base
#sum for pattern
sumP=0
for i in range(Y):
sumP=sumP+(ord(pattern[i])*(d**(Y-i-1)))
print(sumP)
#sum of text
sumT=0
flag=0
for i in range(Y):
sumT=sumT+(ord(text[i])*(d**(Y-i-1)))
if sumP==sumT:
print("Pattern is present in the text at",Y)
flag=1
#Rolling hash function
for i in range(Y,X):
sumT=(sumT-(ord(text[i-Y])*(d**(Y-1))))*d+ord(text[i])
if(sumP==sumT):
print("Pattern is present in the text at",Y-i+1)
flag=1
if flag==0:
print("Pattern is not present in the text")
|
5def0d88a071d4d836e66fbbeac357caa6ae7c5c | handabaldeep/leetcode | /arrays/two_sum.py | 392 | 3.546875 | 4 | # Link - https://leetcode.com/problems/two-sum/
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_idx_dict = {}
for i in range(len(nums)):
if target - nums[i] not in nums_idx_dict:
nums_idx_dict[nums[i]] = i
else:
return [nums_idx_dict[target - nums[i]], i]
|
6272690c68253082e2596ad3de8b375f7c9478cd | spacecase123/cracking_the_code_interview_v5_python | /18.4_number_of_2s.py | 881 | 3.953125 | 4 | '''
Write a method to count the number of 2s between0 and
'''
def num_2s_brute_force(n):
twos = 0
for i in range(2, n+1):
x = str(i)
for j in range(len(x)):
if x[j] == "2":
twos += 1
return twos
def num_2s(n):
if n < 2: return 0
twos = 0
#get 2s at the end
for i in range(2, n+1, 10):
if i <= n:
twos += 1
#20s,200s,2000
twenties = 20
multiplier = 10
#needs some recursive action here I think
#to get stuff like 120,220,2220
while n > twenties:
for j in range(multiplier):
if j + twenties < n:
twos += 1
twenties *= multiplier
multiplier *= multiplier
return twos
if __name__ == "__main__":
print num_2s(10)
print num_2s(30)
print num_2s(100)
print num_2s(230)
|
860dc28d80a0e9a631b3731afcc3a303fbaa6f3d | SATHANASELLAMUTHU/MYPROJECT | /B72.py | 171 | 3.734375 | 4 | n=input("Enter the sentence:")
c=0
for i in n:
if(i=="a" or i=="e" or i=="i" or i=="o" or i=="u"):
c=c+1
if c==0:
print("No")
else:
print("Yes")
|
ffc943eab1f639db284c2a79e3087344d1f8f076 | kagerman80/Recursion | /recursion.py | 455 | 4.125 | 4 | """Digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has more than one digit,
continue reducing in this way until a single-digit number is produced.
The input will be a non-negative integer."""
def calc_digits(x):
result = sum(list(map(int,str(x))))
if len(str(result))==1:
return result
else:
return calc_digits(result)
print(calc_digits(1234)) |
aa60daaec83b46ef58da28f6f6219701855c8e86 | kevinlondon/leetcode | /0000-0999/026_remove_duplicates_from_array_easy.py | 463 | 3.5625 | 4 | class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
unique_nums = sorted(list(set(nums)))
length = len(unique_nums)
print(unique_nums)
for index in range(len(nums)):
if index < length:
nums[index] = unique_nums[index]
else:
nums[index] = None
return length
|
5201720365f8967343fbe88a073f3c3ef654c665 | jonliu6/Programming | /PythonDemo/interests.py | 659 | 3.5625 | 4 | initialAmount = 100
annualAmount = 10
interests = 0.1
asset = 0
#for x in range(0,20):
# asset = (initialAmount + annualAmount * x) * (1 + interests) ** x
#asset = (initialAmount) * (1 + interests) ** x # with a fixed initial amount, no annual deposite
#print("year", x, ", asset=" , asset)
# print(asset)
def calcInterests(numOfYear, interestRate, amount, annualDeposit):
if numOfYear == 0:
return 1
else:
newAmount = (amount + annualDeposit) * (1+interestRate)
print(numOfYear, " ", newAmount)
return calcInterests(numOfYear-1, interestRate, newAmount, annualDeposit)
calcInterests(25, 0.05, 900, 1000)
|
e4a009b37ed9a3c8a625664d88d02e87c5044709 | asifbux/Python-Course-ENSF-592 | /Assignment4/A04_analyze_book1.py | 2,652 | 3.78125 | 4 | """This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
from Histogram import Histogram as hg
import string
def process_file(filename, skip_header):
"""Makes a histogram that contains the words from a file.
filename: string
skip_header: boolean, whether to skip the Gutenberg header
returns: Histogram object - map from each word to the number of times it appears.
"""
word_list = []
fp = open(filename)
if skip_header:
skip_gutenberg_header(fp)
for line in fp:
if line.startswith('world?'):
break
process_line(line, word_list)
# TODO: Create Histogram object from word_list
hist = hg()
hist.count(word_list)
return hist
def skip_gutenberg_header(fp):
"""Reads from fp until it finds the line that ends the header.
fp: open file object
"""
for line in fp:
if line.startswith('This two-year'):
break
def process_line(line, word_list):
"""Cleans the string in line and adds the words to word_list.
Cleaning steps:
1. replace '-' with ' '
2. strip punctuation and whitespace
3. convert to lowercase
Modifies word_list.
line: string
word_list: List containing individual words as elements
"""
# replace hyphens with spaces before splitting
line = line.replace('-', ' ')
strippables = string.punctuation + string.whitespace
for word in line.split():
# remove punctuation and convert to lowercase
word = word.strip(strippables)
word = word.lower()
# TODO: update the list
word_list.append(word)
def main():
hist = process_file('/Users/computer/Desktop/ensf592/Assignment4/feynman.txt', skip_header=False)
print('Total number of words:', hist.total_elements())
print('Number of different words:', hist.different_elements())
t = hist.most_common()
print('The most common words are:')
for freq, word in t[0:20]:
print(word, '\t', freq)
words = process_file('/Users/computer/Desktop/ensf592/Assignment4/words.txt', skip_header= False)
diff = hist - words #Subtract two Histogram objects
print("The words in the book that aren't in the word list are:")
for word in diff.keys():
print(word, end=' ')
print("\n\nHere are some random words from the book")
for i in range(100):
print(hist.random_element(), end=' ')
print('')
if __name__ == '__main__':
main()
|
e88b4192ce368b93ab88f978bc3649fd3d16b242 | psycho-pomp/CodeChef | /KS2.py | 270 | 3.703125 | 4 | # cook your dish here
def sum_digits(n): return sum(map(int, str(n)))
def findRoundNumber(order):
s = sum_digits(order) % 10
return order * 10 + (0 if s == 0 else (10 - s))
t=int(input())
for _ in range(t):
n=int(input())
print(findRoundNumber(n))
|
aa513a0a1b66b4f40a5dac8e83a14ee5767272ed | Nuttanan29445/Python-Daily | /Day028.py | 932 | 3.515625 | 4 | def readword(n):
read = ['soon','neung','song','sam','si','ha','hok','chet','paet','kao']
return read[n]
def to_Thai(n):
ans = ''
k = n
if k == 0 : ans+=readword(k)
else :
if len(str(n))>3:
p = k//1000
if p>0 :
ans+=readword(p)
ans+=' pun '
k%=1000
if len(str(n))>2:
p = k//100
if p>0 :
ans+=readword(p)
ans+=' roi '
k%=100
if len(str(n))>1:
p = k//10
if p>2 :
ans+=readword(p)+' sip '
elif p==1: ans+='sip '
elif p==2:
ans+='yi sip '
k%=10
if k==1 and len(str(n))>1 :
ans+='et'
elif k==0 :
pass
else :
ans+=readword(k)
return ans.strip()
x = int(input("Input Num: "))
print(to_Thai(x)) |
cba8fa8380a41c876bbd89f23cd134abfb40f731 | irina-baeva/algorithms-with-python | /data-structure/queue.py | 589 | 3.828125 | 4 | class Queue:
def __init__(self, head=None):
self.storage = [head]
def enqueue(self, new_element):
self.storage.append(new_element)
def peek(self):
return self.storage[0]
def dequeue(self):
return self.storage.pop(0)
# Setup
q = Queue(12)
q.enqueue(20)
q.enqueue(131)
# [1, 2, 3] 1- is oldest
print(q.peek())# 12
print(q.dequeue())# 12 is oldest dequeue
q.enqueue(4) #now [20, 131, 4]
print(q.dequeue())# 20 is oldest
print(q.dequeue()) #13 is the oldest
print(q.dequeue())# 4
q.enqueue(5) # now [5]
print(q.peek()) # 5 is head |
3abfb0c19e5398bab0b3b2618242d562ab9f6330 | IveDeletedYourPostAsItsADuplicate/codonPython | /codonPython/suppression.py | 1,381 | 3.9375 | 4 | def central_suppression_method(valuein: int, rc: str = "5", upper: int = 5000000000) -> str:
"""
Suppresses and rounds values using the central suppression method.
If value is 0 then it will remain as 0.
If value is 1-7 it will be suppressed and appear as 5.
All other values will be rounded to the nearest 5.
Parameters
----------
valuein : int
Metric value
rc : str
Replacement character if value needs suppressing
upper : int
Upper limit for suppression of numbers (5 billion)
Returns
-------
out : str
Suppressed value (5), 0 or rounded valuein if greater than 7
Examples
--------
>>> central_suppression_method(3)
'5'
>>> central_suppression_method(24)
'25'
>>> central_suppression_method(0)
'0'
"""
base = 5
if not isinstance(valuein, int):
raise ValueError("The input: {} is not an integer.".format(valuein))
if valuein < 0:
raise ValueError("The input: {} is less than 0.".format(valuein))
elif valuein == 0:
valueout = str(valuein)
elif valuein >= 1 and valuein <= 7:
valueout = rc
elif valuein > 7 and valuein <= upper:
valueout = str(base * round(valuein / base))
else:
raise ValueError("The input: {} is greater than: {}.".format(valuein, upper))
return valueout
|
60a87e5fbc228c7dcc0c2c4d303d9855c95e94ec | PedroPadilhaPortella/Curso-Em-Video | /Curso de Python Mundo 2/055-estatistica.py | 662 | 3.765625 | 4 | olderName = ''
older = 0
sumAges = 0
youngWomen = 0
for pessoa in range(1, 5):
print(f"-----{pessoa} PESSOA-----")
nome = input(f"Nome da Pessoa {pessoa}: ")
idade = int(input(f"Idade da Pessoa {pessoa}: "))
sexo = input(f"Sexo da Pessoa {pessoa} [M/F]: ").strip().upper()
sumAges += idade
if(idade > older and sexo == 'M'):
older = idade
olderName = nome
if(sexo == 'F' and idade <= 20):
youngWomen += 1
avgAges = sumAges / 4
print("Mais Velho: {}, com {} anos".format(olderName, older))
print("Media das Idades: {}".format(avgAges))
print("Quantidade de mulheres com menos de 20 anos: {}".format(youngWomen)) |
9bf8325a657b4848a1ec8330a19c74eb0e4ecae9 | patil16nit/algorithms | /algorithm/permutationPalindrom.py | 559 | 3.59375 | 4 |
def permutationPalindrom(msg, start, end):
if start == end:
print ''.join(msg)
else:
for i in xrange(start, end+1):
msg[start], msg[i] = msg[i], msg[start]
permutationPalindrom(msg, start+1, end)
msg[start], msg[i] = msg[i], msg[start]
def main():
message = raw_input("Enter the string for validation of permuation palindrom : ")
msg = list(message)
permutationPalindrom(msg, 0, len(message)-1)
if __name__ == "__main__":
import cProfile
cProfile.run("main()")
|
afee1c02dfa24cfa0350c399990dd1c047923107 | ww-tech/primrose | /primrose/transformers/categoricals.py | 6,727 | 3.546875 | 4 | """Module to run a basic decision tree model
Author(s):
Mike Skarlinski ([email protected])
"""
import pandas as pd
import numpy as np
import logging
from sklearn import preprocessing
from primrose.base.transformer import AbstractTransformer
class ExplicitCategoricalTransform(AbstractTransformer):
DEFAULT_NUMERIC = -9999
def __init__(self, categoricals):
"""initialize the ExplicitCategoricalTransform
Args:
categoricals: dictionary containing for each column to be transformed:
- transformations: list of strings to be executed on the data ('x' represents the current categorical variable)
- rename: if present, rename the current categorical variable to that name
- to_numeric: if true, attempt to apply to_numeric after previous transformations
"""
self.categoricals = categoricals
def fit(self, data):
pass
@staticmethod
def _process_transformations(data, input_data, categorical, x):
"""transform a column
Args:
data (dataframe): dataframe
input configuration (JSON): JSON categorical config for this variable
categorical (str): varible name
x (str): transformation string
Returns:
data (dataframe)
"""
if "transformations" in input_data.keys():
logging.info(
"Applying key {} to variable {}".format("transformations", categorical)
)
for transformation in input_data["transformations"]:
exec(transformation.format(x=x))
@staticmethod
def _process_rename(data, input_data, categorical):
"""rename a field
Args:
data (dataframe): dataframe
input configuration (JSON): JSON categorical config for this variable
categorical (str): varible name
Returns:
(tuple): tuple containing:
data (dataframe): dataframe
name (str): original name (if not "to_numeric": True), new_name otherwise
"""
if "rename" in input_data.keys():
logging.info("Applying key {} to variable {}".format("rename", categorical))
data = data.rename({categorical: input_data["rename"]}, axis="columns")
return data, input_data["rename"]
return data, categorical
@staticmethod
def _process_numeric(data, input_data, name):
"""convert column to numeric
Args:
data (dataframe): dataframe
input configuration (JSON): JSON categorical config for this variable
name (str): field name
Returns:
data with the colun converted to numeric
"""
if input_data.get("to_numeric", False):
logging.info("Applying key {} to variable {}".format("to_numeric", name))
# if there are errors converting to numerical values, we need to sub in a reasonable value
if sum(pd.to_numeric(data[name], errors="coerce").isnull()) > 0:
logging.info(
"Can't convert these entries in {}. Replacing with {}: {}".format(
name,
ExplicitCategoricalTransform.DEFAULT_NUMERIC,
np.unique(
data[name][
pd.to_numeric(data[name], errors="coerce").isnull()
].astype(str)
),
)
)
data[name][
pd.to_numeric(data[name], errors="coerce").isnull()
] = ExplicitCategoricalTransform.DEFAULT_NUMERIC
try:
data[name] = pd.to_numeric(data[name])
return data
except:
raise TypeError("Failed to convert feature {} to numeric".format(name))
else:
return data
def transform(self, data):
"""Transform categorical variables into one or more numeric ones, no need to separate testing & training data
Args:
data: dictionary containing dataframe with all categorical columns present
Returns:
data with all categorical columns recoded and/or deleted
"""
for categorical in self.categoricals.keys():
x = "data['{}']".format(categorical)
input_data = self.categoricals[categorical]
ExplicitCategoricalTransform._process_transformations(
data, input_data, categorical, x
)
data, new_name = ExplicitCategoricalTransform._process_rename(
data, input_data, categorical
)
data = ExplicitCategoricalTransform._process_numeric(
data, input_data, new_name
)
return data
class ImplicitCategoricalTransform(AbstractTransformer):
"""Class which implicitly transforms all string columns of a dataframe with sklearn LabelEncoder"""
def __init__(self, target_variable):
"""initialize this ImplicitCategoricalTransform
Args:
target_variable (str): target variable name
"""
self.target_variable = target_variable
self._encoder = {}
self.target_encoder = None
def fit(self, data):
"""encode the data as categorical labels
Args:
data (dataframe)
Returns:
dataframe (dataframe)
"""
logging.info("Fitting LabelEncoders on all string-based dataframe columns...")
data.is_copy = False
for column_name in data.columns:
if data[column_name].dtype == object:
logging.info("Fitting LabelEncoder for column {}".format(column_name))
self._encoder[column_name] = preprocessing.LabelEncoder()
self._encoder[column_name].fit(data[column_name])
if column_name == self.target_variable:
self.target_encoder = self._encoder[column_name]
else:
pass
return data
def transform(self, data):
"""Transform data into categorical variables using pre-trained label encoder
Args:
data (dataframe)
Returns:
dataframe (dataframe)
"""
data.is_copy = False
for column_name in data.columns:
if column_name in self._encoder:
logging.info("LabelEncoding column {}".format(column_name))
data[column_name] = self._encoder[column_name].transform(
data[column_name]
)
return data
|
c142babbbfdefbf54f5b53b511e7630aa3e726b4 | Mehedi-Hasan-NSL/Python | /bfs_shortest_reach.py | 2,208 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 17:09:46 2021
@author: DELL
"""
from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
self.dist = defaultdict()
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
self.graph[v].append(u)
# Function to print a BFS of graph
def BFS(self,n, s):
# Mark all the vertices as not visited
visited = {s}
# Create a queue for BFS
queue = [s]
self.dist[s] = 0
# Mark the source node as
# visited and enqueue it
#queue.append(s)
#visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
node = queue.pop(0)
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
#print(s,self.graph[s])
for neighbour in self.graph[node]:
print("node ",node)
if neighbour not in visited:
self.dist[neighbour] = self.dist[node] + 6
queue.append(neighbour)
visited.add(neighbour)
res = []
for i in range(1, n+1):
if i not in self.dist:
res.append(-1)
elif self.dist[i] != 0:
res.append(self.dist[i])
print(res)
q = int(input().strip())
for q_itr in range(q):
g = Graph()
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
edges = []
for _ in range(m):
#edges.append(list(map(int, input().rstrip().split())))
u, v = map(int, input().rstrip().split())
g.addEdge(u, v)
s = int(input().strip())
result = g.BFS(n,s)
|
b47e77a5dc42c5fd191af10f58195c9a6df2286c | ZunLayNwe12/GitSample | /Variable.py | 1,946 | 4.3125 | 4 | #21.12.2019
>>> text = "This is a string"
>>> text
'This is a string'
>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6) / 4
5.0
>>> round(5.0)
5
>>> 5.123456
5.123456
>>> round(5.123456,2)
5.12
>>> 17 / 3 # division returns a float
5.666666666666667
>>> 17 // 3 # discards the fraction
5
>>> 17 % 3 # returns the remainder
2
>>> 17 * 4 % 3 # 1st * 2nd %
2
>>>
7 ** 3
343
>>> 3 ** 2 # 3 to the power of 2
9
a = 1
a (variable) = (assign) 1 (value)
width = 20
height = 5 * 9
vol = width * height
vol
>>>4 * 3.75 - 1
14.0
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round (_, 2)
113.06
>>> sale = 30000
>>> tax = 5 / 100
>>> total_tax = sale * tax
>>> total_tax
1500.0
>>> total_price = sale + total_tax
>>> total_price
31500.0
>>>
print('spam eggs')
print('"Yes"')
print("\"Yes,\" they said.")
s = 'First line.\nSecond line.'
>>> print(s)
First line.
Second line.
>>>
# \n = new line
>>> print("""\
... Usage: thingy
... -a
... -b
... -c
... """)
Usage: thingy
-a
-b
-c
>>> 3 * 'un' + 'ium'
'unununium'
>>> 3 * 'A'
'AAA'
>>> 2 * 'BC' + 'DE'
'BCBCDE'
>>> 10 * 'GH' + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> 'GH' + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> 'GH' + '3'
'GH3'
>>> 10 + '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 2 * 'BC' - 'DE'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> 'Py' 'thon'
'Python'
>>>
word[3:5]
word[:5]
word[8:]
>>> word[8:]
'ing'
>>> word[-2:5]
''
>>> word[5:-3]
'amm'
>>> word[:2] + word[3:]
'Prgramming'
>>> List |
e67835f8263a0934afbb015f4eaf51f2479c0b98 | zaid-sayyed602/Python-Basics | /star patterns with for loop.py | 3,942 | 4 | 4 | n=int(input("Enter the number of lines you want\n:"))
print("1")
for i in range(n):
for j in range(i+1):
print("*",end="")
print()
print("\n")
print("\n")
print("2")
for i in range(n):
for j in range(n-i-1):
print(" ",end="")
for k in range(i+1):
print("*",end="")
print()
print("\n")
print("\n")
print("3")
for i in range(n):
for j in range(n-i):
print("*",end="")
print()
print("\n")
print("\n")
print("4")
for i in range(n):
for j in range(i+1):
print(" ",end="")
for k in range(n-i-1):
print("*",end="")
print()
print("\n")
print("\n")
print("5")
for i in range(n):
for j in range(n-i-1):
print(" ",end="")
for k in range(2*i+1):
print("*",end="")
print()
print("\n")
print("\n")
print("6")
for i in range(n):
for j in range(i):
print(" ",end="")
for k in range(2*n-2*i-1):
print("*",end="")
print()
print("\n")
print("\n")
print("7")
for i in range(n-1):
for j in range(n-i-1):
print(" ",end="")
for k in range(2*i+1):
print("*",end="")
print()
for i in range(n):
for j in range(i):
print(" ",end="")
for k in range(2*n-2*i-1):
print("*",end="")
print()
print("\n")
print("\n")
print("8")
for i in range(n):
for j in range(i+1):
print("*",end="")
print()
for i in range(n-1):
for j in range(n-i-1):
print("*",end="")
print()
print("\n")
print("\n")
print("9")
for i in range(n-1):
for j in range(n-i):
print(" ",end="")
for k in range(i+1):
print("*",end="")
print()
for i in range(n):
for j in range(i+1):
print(" ",end="")
for k in range(n-i):
print("*",end="")
print()
print("\n")
print("\n")
print("10")
for i in range(n):
for j in range(n-i):
print(" ",end="")
for k in range(n):
print("*",end="")
print()
print("\n")
print("\n")
print("11")
for i in range(n):
for j in range(i+1):
print(" ",end="")
for k in range(n):
print("*",end="")
print()
print("\n")
print("\n")
print("12")
for i in range(n-1):
for j in range(n-i):
print("*",end="")
print()
for i in range(n):
for j in range(i+1):
print("*",end="")
print()
print("\n")
print("\n")
print("13")
for i in range(n-1):
for j in range(i+1):
print(" ",end="")
for k in range(n-i):
print("*",end="")
print()
for i in range(n):
for j in range(n-i):
print(" ",end="")
for k in range(i+1):
print("*",end="")
print()
print("\n")
print("\n")
print("14")
for i in range(n-1):
for j in range(i+1):
print(" ",end="")
for k in range(n-i):
print("* ",end="")
print()
for i in range(n):
for j in range(n-i):
print(" ",end="")
for k in range(i+1):
print("* ",end="")
print()
print("\n")
print("\n")
print("15")
for i in range(n):
for j in range(i+1):
if(i==0 or j==0 or i==n-1 or j==i):
print("*",end="")
else:
print(" ",end="")
print()
print("\n")
print("\n")
print("16")
for i in range(n):
for k in range(n-i):
print(" ",end="")
for j in range(i+1):
if(i==0 or j==0 or i==n-1 or j==i):
print("*",end="")
else:
print(" ",end="")
print()
print("\n")
print("\n")
print("17")
for i in range(n-1):
for j in range(i):
print(" ",end="")
for k in range(2*n-2*i-1):
print("*",end="")
print()
for i in range(n):
for j in range(n-i-1):
print(" ",end="")
for k in range(2*i+1):
print("*",end="")
print()
|
e6cc8873afeac49f80de87d51e221dd982dea1f9 | roisinhanlon/hello-world | /whilecounter.py | 81 | 3.578125 | 4 | counter = 0
while counter < 5:
counter +=1
print(counter, 'test loop') |
4d1455a28a83758176391f13a392f9590d2c10ab | ahmedzaabal/Python-Demos | /functions.py | 796 | 3.984375 | 4 | from datetime import datetime
#this is a functions current date and time
#custom messages
# def print_time(task_name):
# print(task_name)
# print(datetime.now())
# print()
# first_name = "Ahmed"
# print_time("task is done")
# for x in range(0, 10):
# print(x)
# print_time("Task is done")
def get_initial(name, force_uppercase = True):
if force_uppercase:
initial = name[0:1].upper
else:
initial = name[0:1]
return initial
first_name = input("Enter your first name: ")
first_name_initial = get_initial(force_uppercase = False, name = first_name)
last_name = input("Enter your last name: ")
last_name_initial = get_initial(name = last_name, force_uppercase = True)
print('Your initials are: ' + first_name_initial + ' ' + last_name_initial) |
ae6c737b08c1eff5d4e169eef23c7db9455d737a | LeunamBk/MSC | /regmod/pcaPython/argvValidate.py | 314 | 3.734375 | 4 | # validate user input
import sys
def validateArgv(argv):
def is_intstring(s):
try:
int(s)
return True
except ValueError:
return False
for arg in argv:
if not is_intstring(arg):
sys.exit("All arguments must be integers. Exit.")
|
3254a02f11d8420fd64cc069f47a879d4108775c | sky-bot/Interview_Preparation | /LeetCode/Binary_tree_paths.py | 825 | 3.734375 | 4 | class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
all_paths = list()
if root.left is None and root.right is None:
return [str(root.val)]
self.inorder(root.left, str(root.val), all_paths)
self.inorder(root.right, str(root.val), all_paths)
return all_paths
def inorder(self, root, current_path, all_paths):
if not root:
return
if root.left is None and root.right is None:
all_paths.append(current_path+"->"+str(root.val))
return
else:
self.inorder(root.left, current_path+"->"+str(root.val), all_paths)
print(root.val)
self.inorder(root.right, current_path+"->"+str(root.val), all_paths)
return |
a4b9949e0c7e9e01bcd704589b6edcbdab540c0b | tzkcnm/test | /python_lecture_20161028/context_manager.py | 809 | 3.78125 | 4 | # -*- coding:utf-8 -*-
# class SkipMe(Exception):
# pass
SkipMe = type('SkipMe', (Exception,), {})
class ContextManager(object):
def __enter__(self):
print '=== START ==='
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is SkipMe:
return True
print '=== END ==='
def main():
# fp = open('/tmp/_', 'r')
# try:
# for line in fp:
# print line
# finally:
# fp.close()
# with open('/tmp/_', 'r') as fp:
# for x in fp:
# print x
text = '012?3'
for i, x in enumerate(text):
with ContextManager():
if i == 3:
raise SkipMe()
print int(x)
if __name__ == '__main__':
main()
|
8db2f626046f6cbcc3037e5e2fc513b9e8cf88d1 | lujin123/algorithms | /leetcode/python/remove_linked_list_elements.py | 1,315 | 3.875 | 4 | # Created by lujin at 3/3/
#
# 203. Remove Linked List Elements
#
# Description:
#
# Remove all elements from a linked list of integers that have value val.
#
# Example
# Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
# Return: 1 --> 2 --> 3 --> 4 --> 5
#
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
删除链表中节点值为指定元素的节点
:type head: ListNode
:type val: int
:rtype: ListNode
"""
while head and head.val == val:
head = head.next
if not head:
return head
p = head
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return head
def test(self):
a = [1, 2, 6, 3, 4, 6, 1]
# a = [6, 6, 1]
# a = [6]
# a = []
# a = [1, 6, 6, 1]
head = None
p = None
for i in a:
node = ListNode(i)
if head:
p.next = node
else:
head = node
p = node
self.removeElements(head, 6)
if __name__ == '__main__':
Solution().test()
|
6bfaf0fd0dc86d3d408d03319f2e2751e385706b | mfkiwl/Sanajeh | /src/call_graph.py | 7,927 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# Define Python call graph nodes' data structure
from typing import Set
# Block tree Node
class CallGraphNode:
node_count = 0
def __init__(self, node_name):
self.name: str = node_name # node name
self.declared_variables: Set[VariableNode] = set() # variables declared in this block
self.called_functions: Set[FunctionNode] = set() # functions called in this block
self.called_variables: Set[VariableNode] = set() # variables called in this block
self.is_device = False # if it is an __device__ node
self.id = CallGraphNode.node_count # node id
CallGraphNode.node_count += 1
# Mark this node
def MarkDeviceData(self):
q = [self]
while len(q) != 0:
nd = q[0]
if nd.is_device:
q.pop(0)
continue
nd.is_device = True
# if type(nd) is ClassNode:
# print("Class {}".format(nd.name))
# if type(nd) is FunctionNode:
# print("Function {}".format(nd.name))
for x in nd.called_variables:
x.MarkDeviceData()
for x in nd.declared_variables:
x.MarkDeviceData()
for x in nd.called_functions:
if x.is_device:
return
q.append(x)
q.pop(0)
# Tree node for class
class ClassNode(CallGraphNode):
def __init__(self, node_name, super_class):
super(ClassNode, self).__init__(node_name)
# functions declared in this class
self.declared_functions: Set[FunctionNode] = set()
self.super_class: str = super_class
# Find the function 'function_name' by recursion
def GetFunctionNode(self, function_name, class_name):
if class_name is None:
for x in self.declared_functions:
if x.name == function_name:
return x
for x in self.declared_functions:
if x.name == function_name and x.c_name == class_name:
return x
def GetVariableNode(self, variable_name, variable_type):
# find the variable in the class block
for x in self.declared_variables:
if x.name == variable_name:
if x.v_type == variable_type:
return x
else:
print("Variable '{}' has type '{}', not '{}'".format(
variable_name, x.v_type, variable_type
))
assert False
return None
def IsDeviceFunction(self, function_name, class_name):
for x in self.declared_functions:
if x.name == function_name and x.c_name == class_name:
return x.is_device
return None
# Tree node for function
class FunctionNode(CallGraphNode):
def __init__(self, node_name, class_name, return_type):
super(FunctionNode, self).__init__(node_name)
# arguments of the function
self.arguments: Set[VariableNode] = set()
self.ret_type = return_type
self.c_name = class_name
def GetVariableNode(self, variable_name, variable_type):
# find the variable in this function
for x in self.declared_variables:
if x.name == variable_name:
if x.v_type == variable_type:
return x
else:
print("Variable '{}' has type '{}', not '{}'".format(
variable_name, x.v_type, variable_type
))
assert False
return None
def GetVariableType(self, variable_name):
for x in self.declared_variables:
if x.name == variable_name:
return x.v_type
# find the variable in the arguments:
else:
for x in self.arguments:
if x.name == variable_name:
return x.v_type
# Tree node for variable
class VariableNode(CallGraphNode):
def __init__(self, node_name, var_type, element_type=None):
super(VariableNode, self).__init__(node_name)
self.v_type: str = var_type # type of the variable, "None" for untyped variables
self.e_type: str = element_type # type of the element, only for arrays
def MarkDeviceData(self):
self.is_device = True
# print("Variable {}".format(self.name))
# A tree which represents the calling and declaring relationships
class CallGraph(CallGraphNode):
def __init__(self, node_name):
super(CallGraph, self).__init__(node_name)
self.declared_classes: Set[ClassNode] = set() # global classes
self.declared_functions: Set[FunctionNode] = set() # global functions
self.declared_variables: Set[VariableNode] = set() # global variables
self.library_functions: Set[FunctionNode] = set() # library functions
self.called_functions: Set[FunctionNode] = set() # functions called globally(shouldn't be device function)
self.called_variables: Set[VariableNode] = set() # variables called globally
# Find the class 'class_name'
def GetClassNode(self, class_name):
for x in self.declared_classes:
if x.name == class_name:
return x
return None
def GetFunctionNode(self, function_name, class_name):
for x in self.declared_classes:
ret = x.GetFunctionNode(function_name, class_name)
if ret is not None:
return ret
# find the function in the functions defined in the global block
for x in self.declared_functions:
if x.name == function_name:
return x
for x in self.library_functions:
if x.name == function_name:
return x
return None
def GetVariableNode(self, variable_name, variable_type):
# find the variable in the global block
for x in self.declared_variables:
if x.name == variable_name:
if x.v_type == variable_type or variable_type is None:
return x
else:
print("Variable '{}' has type '{}', not '{}'".format(
variable_name, x.v_type, variable_type
))
assert False
return None
# Mark all functions that needs to be allocated in the allocator
def MarkDeviceDataByClassName(self, class_names):
for cln in class_names:
# do not support just mark a child class which nest in another class
for cls in self.declared_classes:
if cls.name == cln:
# Mark all called functions in class cls
cls.MarkDeviceData()
# Mark all called functions in the functions of cls
for func in cls.declared_functions:
func.MarkDeviceData()
# Mark all variables in that class cls (in the functions of cls)
for var in cls.declared_variables:
var.MarkDeviceData()
# Query whether the function is a device function
def IsDeviceFunction(self, function_name, class_name):
for x in self.declared_classes:
if x.name == class_name:
result = x.IsDeviceFunction(function_name, class_name)
if result is not None:
return result
for x in self.declared_functions:
if x.name == function_name:
return x.is_device
print("Undeclared function '{}.{}'".format(class_name, function_name))
|
f8515820f299607c0b8ec6a4f5988e175fe9f5f5 | Subhajit-Roy-18/Mensuration | /Mensuration.py | 4,831 | 4.34375 | 4 | print("This is a program which will help you in Mensuration.")
print("NOTE: While you Input the Measurements, DO NOT TYPE ITS UNIT. \n")
def main():
print("On which Topic do you want help in ?")
print("For Perimeter, Type 1.")
print("For Area, Type 2.")
print("For Volume, Type 3.")
Type = int(input())
if Type == 1:
print("Whose Perimeter do you want to search?")
print("For Triangle, Type 1.")
print("For Square, Type 2.")
print("For Rectangle, Type 3.")
print("For the Circumference of a Circle, Type 4.")
P_Figure = int(input())
if Type == 1 and P_Figure == 1:
print("What is the Type of the Triangle.")
print("For Equilateral, Type 1")
print("For Isosceles, Type 2")
print("For Scalene, Type 3")
T_Type = int(input())
if Type == 1 and P_Figure == 1 and T_Type == 1:
print("Enter the Length of each Side of the Triangle.")
ET_1 = float(input())
print("The Perimeter of the Triangle =", ET_1 * 3, "Units.")
if Type == 1 and P_Figure == 1 and T_Type == 2:
print("Please Enter the Length of each of the Equal Sides.")
IT_1 = float(input())
print("Now, enter the Length of the Unequal Side.")
IT_2 = float(input())
print("The Perimeter of the Triangle =", (IT_1 * 2) + IT_2, "Units.")
if Type == 1 and P_Figure == 1 and T_Type == 3:
print("Enter the Length of the First Side.")
ST_1 = float(input())
print("Enter the Length of the Second Side.")
ST_2 = float(input())
print("Enter the Length of the Third Side.")
ST_3 = float(input())
print("The Perimeter of the Triangle =", ST_1 + ST_2 + ST_3, "Units.")
elif Type == 1 and P_Figure == 2:
print("Enter the length of each Side.")
S_1 = float(input())
print("The Perimeter of the Square =", S_1 * 4, "Units.")
elif Type == 1 and P_Figure == 3:
print("What is the Length of the Rectangle?")
L = float(input())
print("What is its Breadth?")
B = float(input())
print("The Perimeter of the Rectangle =", 2 * (L + B), "Units.")
elif Type == 1 and P_Figure == 4:
print("What is the Radius of the Circle?")
C_1 = float(input())
print("The Circumference of the Circle =", 2 * 3.14159 * C_1, "Units.")
if Type == 2:
print("Whose Area do you wanna search?")
print("For Triangle, Type 1.")
print("For Square, Type 2.")
print("For Rectangle, Type 3.")
print("For Circle, Type 4")
A_Figure = int(input())
if Type == 2 and A_Figure == 1:
print("What is the Length of the Base of the Triangle?")
TB = float(input())
print("Enter the Length of the Height of the Triangle.")
TH = float(input())
print("The Area of the Triangle =", (TB * TH) / 2, "Sq. Units.")
if Type == 2 and A_Figure == 2:
print("Enter the Length of each Side of the Square.")
SA = float(input())
print("The Area of the Square =", SA * SA, "Sq. Units.")
if Type == 2 and A_Figure == 3:
print("Enter the Length of the Rectangle.")
RL = float(input())
print("Enter the Breadth of the Rectangle.")
RB = float(input())
print("The Area of the Rectangle =", RL * RB, "Sq. Units.")
if Type == 2 and A_Figure == 4:
print("Enter the Radius of the Circle.")
CR = float(input())
print("The Area of the Circle =", 3.14159 * CR * CR, "Sq. Units.")
elif Type == 3:
print("Whose Volume do you wanna Find ?")
print("For Cube, Type 1.")
print("For Cuboid, Type 2.")
V_Figure = int(input())
if Type == 3 and V_Figure == 1:
print("What is the Length of each Edge of the Cube ?")
CE = float(input())
print("The Volume of the Cube =", CE * CE * CE, "Cubic Units.")
if Type == 3 and V_Figure == 2:
print("Enter the Length of the Cuboid.")
CL = float(input())
print("Enter the Breadth of the Cuboid.")
CB = float(input())
print("Enter its Height.")
CH = float(input())
print("The Volume of the Cuboid =", CL * CB * CH, "Cubic Units.")
main()
def again():
print("\n \n If you want to execute the program once more, Type YES, Otherwise Input NO.")
Again = input().upper()
if Again == "YES":
print("")
main()
again()
elif Again == "NO":
print("\n Thanks for Using.")
else:
print("\n Wrong Input.")
again()
|
51eed8ad2f705c8e9d872a2ff9cb6245f0b5fb44 | mpkuchera/PHY200_homeworks | /Homework5/intensity.py | 1,262 | 3.75 | 4 | """
name: intensity.py
Compute and visualize diffraction of waves upon encountering a straight edge.
Problem 5.11 from Newman's Computational Physics.
author: Darcy Lewis
date created: 15/3/2021
"""
# Reminder: you can create other helper functions as long as the function
# behaviors below remain the same
# function name: C
"""
C(u) term of integral.
Parameters
----------
u : FLOAT
input.
Returns
-------
cc : FLOAT
C value at u.
"""
# function name: S
"""
S(u) term of integral.
Parameters
----------
u : FLOAT
input.
Returns
-------
ss : FLOAT
S value at u.
"""
# function name: I_ratio
def I_ratio(x):
"""
Compute I ratio at given x values
Parameters
----------
x : array of FLOAT
x values to compute diffraction.
Returns
-------
I_r : array of FLOAT
I/I0 at given x values.
"""
# function name: plot_ratio
"""
plot I/I0 as a function of x
Parameters
----------
x : array of FLOAT
x values.
ratio : array of FLOAT
I/Io.
Returns
-------
None.
"""
def main():
if __name__ == "__main__":
main() |
c5e51a72df7a385de192d1721d28d11385249961 | iakonk/MyHomeRepos | /python/examples/leetcode/easy/find_smallest_contigius_subarr.py | 609 | 3.59375 | 4 | def find_max_freq(arr):
window_start, max_freq = 0, 0
numbers_freq = {}
for window_end in range(len(arr)):
right_num = arr[window_end]
numbers_freq.setdefault(right_num, 0)
numbers_freq[right_num] += 1
while len(numbers_freq) > 1:
left_num = arr[window_start]
numbers_freq[left_num] -= 1
if numbers_freq[left_num] == 0:
del numbers_freq[left_num]
window_start += 1
max_freq = max(max_freq, window_end - window_start + 1)
return max_freq
ans = find_max_freq([1, 2, 2, 3, 1])
print(ans)
|
89f7b5212b15c7540d786400e44793ced58c2cfa | ncrubin/NielsenNNBookExercise | /network.py | 5,664 | 4.40625 | 4 | ''''
Feed forward neural network from Michael Nielsen's book on deep learning
http://neuralnetworksanddeeplearning.com/
Network is set up as number of layers and a list of sizes. The weights and
biases for network are selected at random. The cost function is quadratic.
This program demonstrates a simple neural network with backpropogation and
gradient descent.
in the network_matrix.py program is the matrix generalization of
backpropogation algorithm. From exploiting matrix mult libraries we get a
significant increase in speed of training the network.
'''
import numpy as np
import random
class Network(object):
'''
Object representing my neural net. takes parameter sizes which is a list
or vector of sizes of each layer. weights and biases are initialized by
random
'''
def __init__(self, sizes):
self.num_layers = len(sizes)
self.sizes = sizes
#Obviously don't need bias for input neurons
np.random.seed(1)
self.biases = [np.random.randn(y,1) for y in sizes[1:]]
self.weights = [np.random.randn(y,x) for x,y in zip(sizes[:-1],
sizes[1:]) ]
def feedforward(self, a):
'''
get the output from the network given an input 'a'.
'''
for b, w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w,a) + b)
return a
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
'''
perform stochastic gradient descent:
Training data is a list "(x,y)" of tuples where 'x' is the input and
'y' is the desired output. epochs is the number of iterations of SGD
you want to run, mini_batch_size is the size of the mini batches, and
eta is the learning rate. if "test_data" optional variable is provided
then the test_data will be evaulated after each epoch to guage how the
network training is proceeding. This is useful for determining
progress but slows everything down...considering all the matrix dot you
need to do to perform feedfoward(.) evaluations.
'''
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
#shuffle training data
random.shuffle(training_data)
#get the mini_batches
mini_batches = [ training_data[k:k+mini_batch_size] for k in
xrange(0, n, mini_batch_size)]
#now train our network with each mini_batch
for mini_batch in mini_batches:
self.mini_batch_update(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2} ".format(j,
self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
def mini_batch_update(self, mini_batch, eta):
"""
Update the networks weights and biases by gradient descent using
backpropogation on a single batch
"""
#set up the derivative matrices
nabla_w = [np.zeros(b.shape) for b in self.weights]
nabla_b = [np.zeros(b.shape) for b in self.biases]
for x,y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x,y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b) ]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w) ]
#now update your variables!
self.weights = [w - (eta/len(mini_batch))*nw for w,nw in
zip(self.weights, nabla_w)]
self.biases = [b - (eta/len(mini_batch))*nb for b, nb in
zip(self.biases, nabla_b)]
def backprop(self, x, y):
"""
return a tuple "(nabla_b, nabla_w)" representing the gradient of the
cost function 'C'
"""
#initialize lists of matrices
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
#feedforward
activation = x
activations = [x] #list of activations
zs = []
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
#backwards pass
delta = np.multiply(self.cost_derivative(activations[-1] , y) ,
sigmoid_prime(zs[-1]) )
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)
def evaluate(self, test_data):
"""Return the number of test inputs for which the neural
network outputs the correct result. Note that the neural
network's output is assumed to be the index of whichever
neuron in the final layer has the highest activation."""
test_results = [(np.argmax(self.feedforward(x)), y)
for (x, y) in test_data]
return sum(int(x == y) for (x, y) in test_results)
def cost_derivative(self, output_activations, y):
"""Return the vector of partial derivatives \partial C_x /
\partial a for the output activations."""
return (output_activations-y)
def sigmoid(z):
return 1.0/(1.0 + np.exp(-z))
def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))
|
c59d570c507ebb1c3c67ddd04bb3fb9a4d8629c1 | mohinishmd/Speech-Recognition-Python | /wav_transcribe.py | 821 | 3.8125 | 4 | import speech_recognition as sr
# obtain path to "english.wav" in the same folder as this script
from os import path
WAV_FILE = path.join(path.dirname(path.realpath(__file__)), "microphone-results.wav")
# use "english.wav" as the audio source
r = sr.Recognizer()
with sr.WavFile(WAV_FILE) as source:
audio = r.record(source) # read the entire WAV file
# recognize speech using Google Speech Recognition
try:
print("Google Speech Recognition thinks you said " + r.recognize_google(audio))
file=open('microphone-results.txt','w')
file.write(r.recognize_google(audio))
file.close()
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
|
c1db1a2125e0c87fc0b10d8d3c7ee41e07cad3ed | hegde10122/python_training | /numpy/numpy6.py | 2,700 | 4.4375 | 4 | '''
INDEXING AND SLICING of ndarrays
'''
import numpy as np
arr = np.arange(10)
print(arr)
print(arr[5:8]) #index 8 is not included ---only 3 elemnts at index 5,6,7
arr[5:8] = 19
print(arr)
'''
If you assign a scalar value to a slice, as in arr[5:8] = 19, the value is propagated (or broadcasted henceforth)
to the entire selection.
An important first distinction from Python’s built-in lists is that array slices are views on the original array.
This means that the data is not copied, and any modifications to the view will be
reflected in the source array.
'''
arr_slice = arr[5:8]
print(arr_slice)
arr_slice[1] = 22
print(arr) #The changes are reflected in the original array
'''
In a two-dimensional array, the elements at each index are no longer scalars but rather one-dimensional
arrays
'''
arr2d = np.array([[1, 12, 3], [4, 5, 16], [7, 11, 9]])
print(arr2d[2])
'''
Individual elements can be accessed recursively. But that is a bit too much
work, so you can pass a comma-separated list of indices to select individual elements.
So these are equivalent
'''
print(arr2d[0][1])
print(arr2d[0,1])
'''
In multidimensional arrays, if you omit later indices, the returned object will be a lower dimensional ndarray
consisting of all the data along the higher dimensions.
'''
arr3d = np.array([[[1, 2, 3], [4, 15, 6]], [[7, 18, 9], [10, 11, 12]]]) # 2 X 2 X 3 array
print(arr3d[0]) # gives a 2x3 array
'''
Both scalar values and arrays can be assigned to arr3d[0]
'''
old_values = arr3d[0].copy()
arr3d[0] = 42
print(arr3d)
'''
arr3d[1, 0] gives you all of the values whose indices start with (1, 0),
forming a 1-dimensional array
Note that in all of these cases where subsections of the array have been selected, the
returned arrays are views.
'''
print(arr3d[1, 0])
'''
Indexing with slices
Like one-dimensional objects such as Python lists, ndarrays can be sliced with the
familiar syntax
'''
print(arr[1:4])
'''
Consider the two-dimensional array from before, arr2d. Slicing this array is a bit
different.
'''
print(arr2d[:2]) #select the first two rows of arr2d.
'''
You can pass multiple slices just like you can pass multiple indexes
When slicing like this, you always obtain array views of the same number of dimensions.
'''
print(arr2d[:2, 1:])
'''
By mixing integer indexes and slices, you get lower dimensional slices.
For example, You can select the second row but only the first two columns
'''
print(arr2d[1, :2])
'''
Similarly, I can select the third column but only the first two rows
'''
print(arr2d[:2, 2])
'''
Note that a colon by itself means to take the entire axis, so you can slice only higher dimensional axes by doing
'''
print(arr2d[:, :1])
|
a3c448ce545883a8b5cd713ac47ca825c40c2a1d | swordwielder/python3 | /printdiamond.py | 390 | 3.921875 | 4 | n = int(input())
print(n*'#')
for i in range(1, (2*n+1)//2 + 1):
for j in range((2*n+1)//2 - i):
print(" ", end = "")
for k in range((i*2)-1):
print("#", end = "")
print()
for i in range((2*n+1)//2 + 1, 2*n + 1):
for j in range(i - (2*n+1)//2 -1):
print(" ", end = "")
for k in range((2*n+1 - i)*2 - 1):
print("#", end = "")
print()
|
a04466fc4c154a59dd983fe4a56befe8b530be68 | huwanping001/Python | /chapter4/demo9.py | 225 | 3.8125 | 4 | # 学校:四川轻化工大学
# 学院:自信学院
# 学生:胡万平
# 开发时间:2021/9/18 15:00
age = int(input('请输入你的年龄:'))
if age:
print(age)
else:
print('年龄为:', age) |
c9296d6322695116decd3cc66604a16fae3f3a30 | Slendercoder/Triqui | /my_app/funciones_logica.py | 13,988 | 3.5625 | 4 | import re
conectivos = ['O', 'Y', '>', '=']
Nfilas = 3
Ncolumnas = 3
Nnumeros = 3
Nturnos = 2
class Tree(object):
def __init__(self, label, left, right):
self.left = left
self.right = right
self.label = label
def inorder(A):
#Convierte un Tree en una cadena de símbolos
#Input: A, formula como Tree
#Output: formula como string
if A.right == None:
return A.label
elif A.label == "-":
return '-'+ inorder(A.right)
elif A.label in conectivos:
return '(' + inorder(A.left) + A.label + inorder(A.right) + ')'
def elim_doble_negacion(T):
#Elimina las dobles negaciones en una formula dada como Tree
#Input: Formula como Tree
#Output: Formula como Tree sin dobles negaciones
if T.right == None:
return T
elif T.label == '-':
if T.right.label == '-':
return elim_doble_negacion(T.right.right)
else:
return Tree('-',None,elim_doble_negacion(T.right))
elif T.label in conectivos:
return Tree(T.label,elim_doble_negacion(T.left),elim_doble_negacion(T.right))
def String2Tree(polaco_inverso, LetrasProposicionales):
#Crea una formula como Tree dada una formula como string en notacion polaca inversa
#Input: polaco_inverso, Lista de caracteres con una formula escrita en notacion polaca inversa
# LetrasProposicionales, lista de strings
#Output: Formula como Tree
A = []
for i in polaco_inverso:
A.append(i)
pila = []
for c in A:
if c in LetrasProposicionales:
pila.append(Tree(c, None, None))
elif c =='-':
formulaAux = Tree(c, None, pila[-1])
del pila[-1]
pila.append(formulaAux)
elif c in conectivos:
formulaAux = Tree(c, pila[-1], pila[-2])
del pila[-1]
del pila[-1]
pila.append(formulaAux)
return pila[-1]
def Tseitin(T, LetrasProposicionales):
#Dada una formula T, halla una formula T' igual de buena que T en forma normal conjuntiva
#Input: T formula como Tree
# LetrasProposicionales, lista de strings
#Output: Formula como Tree en forma normal conjuntiva
T = elim_doble_negacion(T)
A = inorder(T)
LetrasProposicionales2 = [chr(x) for x in range(900, 1399)]
L = []
pila = []
i = -1
s = A [0]
while len(A) > 0:
if s in LetrasProposicionales and len(pila) > 0 and pila[-1] == "-":
i += 1
atomo = LetrasProposicionales2[i]
pila = pila[:-1]
pila.append(atomo)
L.append(Tree("=", Tree(atomo,None,None), Tree("-",None, Tree(s, None, None))))
A = A[1:]
if len(s)>0:
s = A[0]
elif s == ")":
w = pila[-1]
o = pila[-2]
v = pila[-3]
pila = pila[:len(pila) -4]
i += 1
atomo = LetrasProposicionales2[i]
L.append(Tree("=", Tree(atomo, None, None), Tree(o, Tree(v, None, None), Tree(w,None, None))))
s = atomo
else:
pila.append(s)
A = A[1:]
if len(A)>0:
s = A[0]
B = ""
if i < 0:
atomo = pila[-1]
else:
atomo = LetrasProposicionales2[i]
for T in L:
if T.right.label == "-":
T= Tree("Y", Tree("O", Tree("-", None, T.left), Tree("-", None, T.right.right)), Tree("O", T.left, T.right.right))
elif T.right.label == "Y":
T= Tree("Y", Tree("Y", Tree("O", T.right.left, Tree("-", None, T.left)), Tree("O", T.right.right, Tree("-", None, T.left))), Tree("O", Tree("O",Tree("-", None, T.right.left), Tree("-", None, T.right.right)), T.left))
elif T.right.label == "O":
T= Tree("Y", Tree("Y", Tree("O", Tree("-", None, T.right.left), T.left), Tree("O", Tree("-", None, T.right.right), T.left )), Tree("O", Tree("O",T.right.left, T.right.right), Tree("-", None, T.left)))
elif T.right.label == ">":
T= Tree("Y", Tree("Y", Tree("O", T.right.left, T.left), Tree("O", Tree("-", None, T.right.right), T.left)), Tree("O", Tree("O", Tree("-", None, T.right.left), T.right.right), Tree("-", None, T.left)))
B += "Y" + inorder(T)
B = atomo + B
return B
def TseitinJL(T, LetrasProposicionales):
#Dada una formula T, halla una formula T' igual de buena que T en forma normal conjuntiva
#Input: T formula como Tree
# LetrasProposicionales, lista de strings
#Output: Formula como Tree en forma normal conjuntiva
T = elim_doble_negacion(T)
A = inorder(T)
LetrasProposicionales2 = [chr(x) for x in range(1400, 1899)]
L = []
pila = []
i = -1
s = A [0]
while len(A) > 0:
if s in LetrasProposicionales and len(pila) > 0 and pila[-1] == "-":
i += 1
atomo = LetrasProposicionales2[i]
pila = pila[:-1]
pila.append(atomo)
L.append(Tree("=", Tree(atomo,None,None), Tree("-",None, Tree(s, None, None))))
A = A[1:]
if len(s)>0:
s = A[0]
elif s == ")":
w = pila[-1]
o = pila[-2]
v = pila[-3]
pila = pila[:len(pila) -4]
i += 1
atomo = LetrasProposicionales2[i]
L.append(Tree("=", Tree(atomo, None, None), Tree(o, Tree(v, None, None), Tree(w,None, None))))
s = atomo
else:
pila.append(s)
A = A[1:]
if len(A)>0:
s = A[0]
B = ""
if i < 0:
atomo = pila[-1]
else:
atomo = LetrasProposicionales2[i]
for T in L:
if T.right.label == "-":
T= Tree("Y", Tree("O", Tree("-", None, T.left), Tree("-", None, T.right.right)), Tree("O", T.left, T.right.right))
elif T.right.label == "Y":
T= Tree("Y", Tree("Y", Tree("O", T.right.left, Tree("-", None, T.left)), Tree("O", T.right.right, Tree("-", None, T.left))), Tree("O", Tree("O",Tree("-", None, T.right.left), Tree("-", None, T.right.right)), T.left))
elif T.right.label == "O":
T= Tree("Y", Tree("Y", Tree("O", Tree("-", None, T.right.left), T.left), Tree("O", Tree("-", None, T.right.right), T.left )), Tree("O", Tree("O",T.right.left, T.right.right), Tree("-", None, T.left)))
elif T.right.label == ">":
T= Tree("Y", Tree("Y", Tree("O", T.right.left, T.left), Tree("O", Tree("-", None, T.right.right), T.left)), Tree("O", Tree("O", Tree("-", None, T.right.left), T.right.right), Tree("-", None, T.left)))
B += "Y" + inorder(T)
B = atomo + B
return B
def forma_clausal(formula):
# Crea una formula en su forma clausal dada una formula en forma normal conjuntiva
#Input: formula, formula como Tree en forma normal conjuntiva
#Output: Formula en su forma clausal
lista = []
count = 0
while len(formula)>0:
if count == len(formula) or formula[count] == "Y":
lista1 = formula[:count]
lista2 = []
while len(lista1)>0:
caracter = lista1[0]
if caracter in ["O", "(" ,")"]:
lista1 = lista1[1:]
elif caracter == "-":
literal = caracter + lista1[1]
lista2.append(literal)
lista1 = lista1[2:]
else:
lista2.append(caracter)
lista1 = lista1[1:]
lista.append(lista2)
formula = formula[count+1:]
count = 0
else:
count +=1
string = ""
listaFinal = []
for i in lista:
for j in i:
string += j
listaFinal.append(string)
string = ""
return listaFinal
def clausulaUnitaria(lista):
#Encuentra una clausula unitaria en una lista de strings
#Input: lista, Lista de strings
#Output:Clausula unitaria
for i in lista:
if (len(i)==1):
return i
elif (len(i)==2 and i[0]=="-"):
return i
return None
## Clausula Vacía
def clausulaVacia(lista):
#Verifica si una lista contiene una clausula vacía
#Input: lista, lista de strings
#Output: booleano
for i in lista:
if(i==''):
return(True)
return False
#interps= {}
## Unit Propagate
def unitPropagate(lista,interps):
# Hace Unit Propagate a un conjunto de clausulas
#Input: lista, lista de strings (formula en forma clausal)
# interps, diccionario (interpretacion parcial)
#Output: lista, lista de strings (formula en forma clausal)
# interps, diccionario con interpretaciones parciales
x = clausulaUnitaria(lista)
while(x!= None and clausulaVacia(lista)!=True):
if (len(x)==1):
interps[str(x)]=1
j = 0
for i in range(0,len(lista)):
lista[i]=re.sub('-'+x,'',lista[i])
for i in range(0,len(lista)):
if(x in lista[i-j]):
lista.remove(lista[i-j])
j+=1
else:
interps[str(x[1])]=0
j = 0
for i in range(0,len(lista)):
if(x in lista[i-j]):
lista.remove(lista[i-j])
j+=1
for i in range(0,len(lista)):
lista[i]=re.sub(x[1],'',lista[i])
x = clausulaUnitaria(lista)
return(lista, interps)
## Literal Complemento
def literal_complemento(lit):
#Encuentra el literal complemento de un literal
#Input:Literal
#Output:Literal complemento.
if lit[0] == "-":
return lit[1]
else:
lit = "-" + lit
return lit
## DPLL
def DPLL(lista, interps):
#Verifica si una formula es satisfacible
#Input: lista, lista de strings (formula en forma clausal)
# interps, diccionario (interpretacion parcial)
#Output: lista, lista de strings (formula en forma clausal)
# interps, diccionario (interpretacion parcial)
lista, interps = unitPropagate(lista,interps)
if(len(lista)==0):
listaFinal = lista
interpsFinal = interps
return(lista,interps)
elif("" in lista):
listaFinal = lista
interpsFinal = interps
return (lista,{})
else:
listaTemp = [x for x in lista]
for l in listaTemp[0]:
if (len(listaTemp)==0):
return (listaTemp, interps)
if (l not in interps.keys() and l!='-'):
break
listaTemp.insert(0,l)
lista2, inter2 = DPLL(listaTemp, interps)
if inter2 == {}:
listaTemp = [x for x in lista]
a =literal_complemento(l)
listaTemp.insert(0,a)
lista2, inter2 = DPLL(listaTemp, interps)
return lista2, inter2
## Interps final
def interpsFinal(interps, LetrasProposicionales):
#Dada una interpretacion ecuentra la interpretacion correspondiente usando solo las letras
#proposicionales necesarias.
#Input:Iterpretacion con todas las letras de LetrasProposicionales2
#Output:Interpretacion con las letras de LetrasProposicionales
interpsf = {i: interps[i] for i in LetrasProposicionales if i in interps}
return interpsf
## RESULTADO
def DPLLResultado(lista, LetrasProposicionales):
#Encuentra la interpretacion usando DPLL
#Input:lista en forma clausal
#Output:Interpretacion
lista, inter = DPLL(lista,{})
interpretacion = interpsFinal(inter, LetrasProposicionales)
return interpretacion
def codifica(f, c, Nf, Nc):
# Funcion que codifica la fila f y columna c
assert((f >= 0) and (f <= Nf - 1)), 'Primer argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nf) - 1 + "\nSe recibio " + str(f)
assert((c >= 0) and (c <= Nc - 1)), 'Segundo argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nc - 1) + "\nSe recibio " + str(c)
n = Nc * f + c
# print(u'Número a codificar:', n)
return n
def decodifica(n, Nf, Nc):
# Funcion que codifica un caracter en su respectiva fila f y columna c de la tabla
assert((n >= 0) and (n <= Nf * Nc - 1)), 'Codigo incorrecto! Debe estar entre 0 y' + str(Nf * Nc - 1) + "\nSe recibio " + str(n)
f = int(n / Nc)
c = n % Nc
return f, c
def codifica3(f, c, o, Nf, Nc, No):
# Funcion que codifica tres argumentos
assert((f >= 0) and (f <= Nf - 1)), 'Primer argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nf - 1) + "\nSe recibio " + str(f)
assert((c >= 0) and (c <= Nc - 1)), 'Segundo argumento incorrecto! Debe ser un numero entre 0 y ' + str(Nc - 1) + "\nSe recibio " + str(c)
assert((o >= 0) and (o <= No - 1)), 'Tercer argumento incorrecto! Debe ser un numero entre 0 y ' + str(No - 1) + "\nSe recibio " + str(o)
v1 = codifica(f, c, Nf, Nc)
v2 = codifica(v1, o, Nf * Nc, No)
return v2
def decodifica3(codigo, Nf, Nc, No):
# Funcion que codifica un caracter en su respectiva fila f, columna c y objeto o
v1, o = decodifica(codigo, Nf * Nc, No)
f, c = decodifica(v1, Nf, Nc)
return f, c, o
def P(fila, columna, signo, turno, numfilas, numcolumnas, numsignos, numturnos):
v1 = codifica3(fila, columna, signo, numfilas, numcolumnas, numsignos)
v2 = codifica(v1, turno, numfilas*numcolumnas*numsignos, numturnos)
codigo = chr(256 + v2)
return codigo
def Pinv(codigo, numfilas, numcolumnas, numsignos, numturnos):
v2 = ord(codigo) - 256
v1, turno = decodifica(v2, numfilas*numcolumnas*numsignos, numturnos)
fila, columna, signo = decodifica3(v1, numfilas, numcolumnas, numsignos)
return fila, columna, signo, turno
def Inorderp(f):
if f.right == None:
return "P" + str(Pinv(f.label, Nfilas, Ncolumnas, Nnumeros, Nturnos))
elif f.label == '-':
return f.label + Inorderp(f.right)
else:
return "(" + Inorderp(f.left) + f.label + Inorderp(f.right) + ")"
|
c2da35c69dbc9990c64b9d228fc5a68059486bca | jiinmoon/Algorithms_Review | /Archives/Leet_Code/Old-Reviews/Current-Reviews/Top-Review-01/0179-Largest-Number.py | 421 | 3.671875 | 4 | # 179 Largest Number
#
# We create a custom comparator that compares by string concatenation.
from functools import cmp_to_key
class Solution:
def largestNumber(self, nums):
def larger(a, b):
return -1 if a + b > b + a else 1
nums = map(str, nums)
nums.sort(key=cmp_to_key(larger))
while nums and nums[0] == '0':
nums = nums[1:]
return "".join(nums)
|
9e1dd814bbc4e447b48cd212ac51444085b650e6 | Bublinz/Python-Expert | /Exercises/student_fidel/triangle.py | 319 | 4.0625 | 4 | # write a program that will calculate the area of a traingle
print('calculate the area of a triangle')
def rate(length):
b = int(input('Input the Base: '))
h = int(input('Input the Height: '))
# area = 0.5 * b * h
area = 0.5 * b * h
print('The area of the triangle is ' + str(area))
rate('length')
|
333e740a6f337c4bbc1d107ad2aef8146905098f | Bansi-Parmar/Python_Basic_Programs | /python_program-062.py | 275 | 3.671875 | 4 | ## 62. 1
## 2 2
## 3 3 3
## 4 4 4 4
## 5 5 5 5 5
print('\n\t patterns')
print('\t...........\n')
n = int(input("Enter No of Rows :- "))
i=0
for r in range(1,n+1):
print((('{} '.format(r)*r) .ljust(n*2)))
i=i+1
|
44b93eaafdb68529be2bae98d6b00d67317c3b21 | vitaedrinker/python | /JohnEmailScrape.py | 882 | 3.890625 | 4 | # read a webpage
import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()
import re #Regex
#Author: John Nicholson
#Scrapes Webpage and pulls all lines with an email to a .txt
def WebToTxt():
print ("Would you like to use a different url other than https://pastebin.com/n9phcmx4?")
answer = raw_input("(y/n?) ")
if answer == 'n':
url = 'https://pastebin.com/n9phcmx4' #Name of file being scraped
else:
print ("Please enter the URL you want to scrape")
url = raw_input(">> ")
r = urllib2.urlopen(url, timeout=100)
f = open('output.xls', 'w')
for line in r.readlines():
if re.search("^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}", line):
#found = re.findall("\>(.*?)\<", line) #finds everything between html tags
f.write(line.replace(':', '\t'))
f.close()
#Main Method
def Main():
WebToTxt()
Main() |
f3c3bc512463b91bf81ec035b760b41ee4b89eb3 | walxc1218/git | /圆的周长面积.py | 1,152 | 4 | 4 | #打印圆的周长和面积
r = 3
p = 3.14
l = 2*p*r
s = p*r**2
print("圆的周长是:",l,"厘米")
print("圆的面积是:",s,"平方厘米")
在交互模式下查看当前作用域的所有变量
help("__main__")
del 语句
作用:
用于删除变量,同时解除与对象的关联,如果可能则释放对象
语法:
del 变量名1,
is/is not
小整数对象池:
cpython中,-5至256的数永远存在于小整数
id(x)函数
作用:
返回一个
练习:
1.在终端输出图形:
*
***
*****
*******
2.中国古代的称是16两一斤,请问古代的216两是几斤几两
写程序打印出来
3从凌晨0:0:0计时,到现在已经过了63320秒,请问现在是几时几分几秒?写程序打印出来
提示:可以用地板除和求余算出
4温度转换(华式温度/摄式温度/升式温度)
算法:
摄式温度=5.0/9.0*(华式温度-32)
开式温度=摄氏温度+273.15
问:
100华式温度转为摄氏温度是多少度
转为开式温度是多少度
|
c2af09a3372d309a5c0e2a0349ea2a9ea3d1acba | L200184092/Praktikum-AlgoStruk | /Praktikum 8/5.py | 957 | 3.78125 | 4 | class PriorityQueue(object):
def __init__(self):
self.qlist = []
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len(self.qlist)
def enqueue(self, data, priority):
entry = PriorityQEntry(data, priority)
self.qlist.append(entry)
def dequeue(self):
assert not self.isEmpty(), "Antrian sedang kosong"
max = 0
for i in range(len(self.qlist)):
if self.qlist[i].priority < self.qlist[max].priority:
max = i
hasil = self.qlist[max]
del self.qlist[max]
print(hasil.item)
class PriorityQEntry(object):
def __init__(self, data, priority):
self.item = data
self.priority = priority
S = PriorityQueue()
S.enqueue("Jeruk", 4)
S.enqueue("Tomat", 2)
S.enqueue("Mangga", 0)
S.enqueue("Duku", 5)
S.enqueue("Pepaya", 2)
S.dequeue()
S.dequeue()
S.dequeue()
|
efcc91ae4fbbacb2e3d66a967c3dde6a51fd1b7b | senioryta/Python-OOP | /12_Super()/main.py | 840 | 3.671875 | 4 | # superclass
class Estudent:
# private class attribute
__total = 0
# constructor __init__()
def __init__(self,name,id,classroom):
self.__name = name
self.__id = id
self.__class = classroom
Estudent.__total += 1
# method
def showinfo(self):
print("{} \n\t id : {} \n\t class : {} \n".format(self.__name,self.__id,self.__class))
# subclass
class Estudent_a(Estudent):
# constructor __init__()
def __init__(self,name,id):
# call superclass and __init__()
super().__init__(name,id,"a")
super().showinfo()
# subclass
class Estudent_b(Estudent):
# constructor __init__()
def __init__(self,name,id):
# call superclass and __init__()
super().__init__(name,id,"b")
super().showinfo()
# object
serafina = Estudent("serafina",138,"b")
angelia = Estudent_a("angelia",107)
suzana = Estudent_b("suzana",139)
|
bbac10925ea7bebbd6ddbdcd6cb460dc401acc40 | VinayakBagaria/Python-Programming | /New folder/Highest Prime Factor.py | 435 | 3.734375 | 4 | #Largest Prime Factor
def prime(a):
for i in range(2,a):
if a%i==0:
return -1
return 1
def calc_prime(n):
p=2
while p*p<=n:
if (n%p==0 and prime(p)!=-1):
n=n//p
else:
p=p+1
print(n)
global take
test=int(input())
list=[None]*test
for i in range(0,test):
list[i]=int(input())
for i in range(0,test):
calc_prime(list[i])
|
c4e7ea0c065b5f60ef259afb67cb5503857ee448 | bpull/fall16 | /graphics/hw/4/circle.py | 1,299 | 3.578125 | 4 | #!/usr/bin/python3
# Our required libraries!
import math
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
#drange definition taken from http://stackoverflow.com/questions/477486/python-decimal-range-step-value
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
#end citation
def createCircle(cx, cy, rad, verts):
spread = 360.0 / verts
for i in drange(0, 360, spread):
i = i*math.pi/180
glVertex3f(cx+math.cos(i)*rad,cy+math.sin(i)*rad, 0.0)
# The function that we will use to draw the environment
def display():
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glColor3f(1.0, 1.0, 1.0) # White
glBegin(GL_LINE_LOOP)
createCircle(50, 50, 25, 50) #last parameter is the number of vertices
glEnd()
glFlush()
# Initialize the environment
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH)
# Set the initial window position and size (if we want to)
glutInitWindowPosition(100,50)
glutInitWindowSize(400, 400)
# Create the window and name it
glutCreateWindow("Brandon Pullig 175148")
# Build the scene
glutDisplayFunc(display)
# Build the Bounding box - much more on this later!
glOrtho(0.0, 100.0, 0.0, 100.0, -2.0, 1.0)
# Go into a loop
glutMainLoop()
|
a0b687706fd97a4a69699b2aac6bf4b0365a912a | JSYoo5B/TIL | /PS/BOJ/11723/11723.py | 857 | 3.65625 | 4 | #!/usr/bin/env python3
from sys import stdin
input = stdin.readline
if __name__ == '__main__':
op_cnt = int(input())
sets = set()
for _ in range(op_cnt):
oper = list(input().split())
operation, operand = oper[0], 0
if len(oper) == 2:
operand = int(oper[1])
if operation == 'add':
sets.add(operand)
elif operation == 'remove':
sets.discard(operand)
elif operation == 'check':
answer = 1 if operand in sets else 0
print(answer)
elif operation == 'toggle':
if operand in sets:
sets.discard(operand)
else:
sets.add(operand)
elif operation == 'all':
sets |= { i for i in range(1, 21) }
elif operation == 'empty':
sets.clear()
|
82d35b1f595648d45986f0d94fe041baf8538e5b | MartinGildea/tutorial2_primeFactor_competition | /martingildea_tutorial2_competition.py | 981 | 3.875 | 4 | # primeFactors.py
# import test code
from lab2Test import speedTestFun
# --------------------------------
# primeFactors()
# input: A positive integer n (e.g. 19162234)
# output: A list of the prime factors of n with multiplicity (e.g. [2, 7, 7, 13, 13, 13, 89])
# method: Divide n by all possible integers in increasing numerical order, which will naturally eliminate
# non-prime numbers.
# --------------------------------
def primeFactors(n):
primeList = [] #primeList is the list of all primeFactors of the target number
primeDivisor = 2 #primeDivisor is a variable that will be added to the list if it can divide the target number without a remainder.
while primeDivisor * primeDivisor <= n:
if n % primeDivisor:
primeDivisor = primeDivisor + 1
else:
n = n / primeDivisor
primeList.append(primeDivisor)
primeList.append(n)
return primeList
#testFun(primeFactors)
speedTestFun(primeFactors)
|
f28640f6e7c1f8ab046edd4b0ee495fc24716bac | HongsenHe/algo2018 | /036_valid_sudoku.py | 3,468 | 3.71875 | 4 | # 07282021
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = len(board)
cols = len(board[0])
# verify each row
for i in range(rows):
visited = set()
for j in range(cols):
if not self.valid(board, i, j, visited):
return False
# verify each col
for i in range(cols):
visited = set()
for j in range(rows):
if not self.valid(board, j, i, visited):
return False
# verify 3x3
for i in range(0, rows, 3):
for j in range(0, cols, 3):
visited = set()
for x in range(i, i + 3, 1):
for y in range(j, j + 3, 1):
if not self.valid(board, x, y, visited):
return False
return True
def valid(self, board, i, j, visited):
num = board[i][j]
if num == '.':
return True
num = int(num)
if num > 9 or num < 1:
return False
if num in visited:
return False
visited.add(num)
return True
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
if not board:
return False
n = len(board) # should be 9
# no duplicated number for each row and column
for row in board:
if not self.valid(row):
return False
for col in zip(*board):
if not self.valid(col):
return False
# no dplicated number for sub board 3 x 3
for i in range(0, n, 3):
for j in range(0, n, 3):
nums = []
for x in range(i, i+3, 1):
for y in range(j, j+3, 1):
nums.append(board[x][y])
if not self.valid(nums):
return False
return True
def valid(self, nums):
# if no duplicated number, then it's valid
nums = [num for num in nums if num != '.']
return len(nums) == len(set(nums))
# 04152019
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# validate each rows
for rows in board:
row_set = set()
for each in rows:
if each in row_set:
return False
if each != '.':
row_set.add(each)
# validate each columns
for i in range(9):
col_set = set()
for rows in board:
col = rows[i]
if col in col_set:
return False
if col != '.':
col_set.add(col)
# validate 3x3
for i in range(0, 9, 3):
for j in range(0, 9, 3):
cube_set = set()
for m in range(i, i+3, 1):
for n in range(j, j+3, 1):
cube = board[m][n]
if cube in cube_set:
return False
if cube != '.':
cube_set.add(cube)
return True |
854cc0ef95d03cb7b1f3d149ad445ef8a2b154ca | dnuffer/dpcode | /determine_if_one_string_is_a_permutation_of_another/python/start.py | 608 | 3.984375 | 4 | """
>>> are_permutations("abc", "cab")
True
>>> are_permutations("abc", "aab")
False
>>> are_permutations("abcd", "abc")
False
>>> are_permutations("", "")
True
>>> are_permutations("a", "a")
True
>>> are_permutations("aaa", "aaa")
True
>>> are_permutations("aaa", "aaaa")
False
>>> are_permutations("aab", "abb")
False
"""
# TODO: Write are_permutations that determines if one string is a permutation of another
if __name__ == '__main__':
import doctest
result = doctest.testmod()
if result.failed > 0:
print "Failed:", result
import sys
sys.exit(1)
else:
print "Success:", result
|
65ea12ccd51b4bc5dd85300bf7a2ce962a20f704 | AndyAtari/PyPong | /pong.py | 2,806 | 3.8125 | 4 | import turtle
# window screen
window = turtle.Screen()
window.title("Pong by AndyAtari")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)
# player 1
paddle_one = turtle.Turtle()
paddle_one.speed(0)
paddle_one.shape("square")
paddle_one.shapesize(stretch_wid=5, stretch_len=1)
paddle_one.color("red")
paddle_one.penup()
paddle_one.goto(-350, 0)
# player 2
paddle_two = turtle.Turtle()
paddle_two.speed(0)
paddle_two.shape("square")
paddle_two.shapesize(stretch_wid=5, stretch_len=1)
paddle_two.color("blue")
paddle_two.penup()
paddle_two.goto(350, 0)
# ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0,0)
ball.dx = 0.15
ball.dy = 0.15
# score card
pen = turtle.Turtle()
pen.speed(0)
pen.penup()
pen.color("white")
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player One: 0 Player Two: 0", align="center", font=("Courier", 24, "normal"))
# score logic
score_one = 0
score_two = 0
# player movement
def paddle_one_up():
y = paddle_one.ycor()
y += 20
if y >= 250:
y = 250
paddle_one.sety(y)
def paddle_one_down():
y = paddle_one.ycor()
y -= 20
if y <= -250:
y = -250
paddle_one.sety(y)
def paddle_two_up():
y = paddle_two.ycor()
y += 20
if y >= 250:
y = 250
paddle_two.sety(y)
def paddle_two_down():
y = paddle_two.ycor()
y -= 20
if y <= -250:
y = -250
paddle_two.sety(y)
# event listeners
window.listen()
window.onkeypress(paddle_one_up, "w")
window.onkeypress(paddle_one_down, "s")
window.onkeypress(paddle_two_up, "Up")
window.onkeypress(paddle_two_down, "Down")
# game loop
while True:
window.update()
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# ball boundaries
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_one += 1
pen.clear()
pen.write(f"Player One: {score_one} Player Two: {score_two}", align="center", font=("Courier", 24, "normal"))
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_two += 1
pen.clear()
pen.write(f"Player One: {score_one} Player Two: {score_two}", align="center", font=("Courier", 24, "normal"))
# paddle collisions
if ball.xcor() > 340 and ball.xcor() < 350 and (ball.ycor() < paddle_two.ycor() + 50 and ball.ycor() > paddle_two.ycor() -50):
ball.setx(340)
ball.dx *= -1
if ball.xcor() < -340 and ball.xcor() > -350 and (ball.ycor() < paddle_one.ycor() + 50 and ball.ycor() > paddle_one.ycor() -50):
ball.setx(-340)
ball.dx *= -1 |
92821beaaca67c43ac128590d27098ea30b250ef | Cyntha-K/bioinfo-lecture-2021-07 | /0706/020.py | 53 | 3.5 | 4 | a = input('word1')
b = input('word2')
print(a + b)
|
b1a3712100763fe1b397d0bbe7624566e417b345 | choco9966/Algorithm-Master | /programmers/level2/code/조이스틱.py | 1,746 | 3.71875 | 4 | # ord를 이용해서 알파벳의 위치를 출력하고 순차적으로 진행하는게 빠른지, 반대로 진행하는게 빠른 지 계산
def cal_change_alphabet(solution):
diff = min(abs(ord(solution)-ord('A')), abs(26 - (ord(solution)-ord('A'))))
return diff
def change_alphabet(text, index):
text_ = list(text)
text_[index] = 'A'
text = ''.join(text_)
return text
def check_alphabet(text):
if len(set(list(text))) == 1:
return True
def solution(name):
answer_list = []
answer = 0
n = len(name)
# 알파벳을 모두 A로 바꿨을 때 갯수
for i in range(n):
answer += cal_change_alphabet(name[i])
name = change_alphabet(name, 0)
if check_alphabet(name) == 1: return 0
# 조작키를 이용해서 이동하는 최소의 갯수
# 1. 오른쪽으로 갔다가 왼쪽으로 가는 경우
for i in range(1, n):
name_left = name
answer_left = answer + i
for k in range(1, i+1):
name_left = change_alphabet(name_left, k)
for j in range(1, n-i):
name_left = change_alphabet(name_left, i-j)
answer_left += 1
if check_alphabet(name_left): break
answer_list.append(answer_left)
# 2. 왼쪽으로 갔다가 오른쪽으로 가는 경우
for i in range(1, n):
name_right = name
answer_right = answer + i
for k in range(1, i+1):
name_right = change_alphabet(name_right, -k)
for j in range(0, n-i):
name_right = change_alphabet(name_right, -i+j)
if check_alphabet(name_right): break
answer_right += 1
answer_list.append(answer_right)
return min(answer_list)
|
a6629d987219ccf10ba4f10674bd7e890108c71b | 111110100/my-leetcode-codewars-hackerrank-submissions | /hackerrank/plusminus.py | 1,660 | 4 | 4 | '''
Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with places after the decimal.
Note: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to are acceptable.
Example
There are elements, two positive, two negative and one zero. Their ratios are , and . Results are printed as:
0.400000
0.400000
0.200000
Function Description
Complete the plusMinus function in the editor below.
plusMinus has the following parameter(s):
int arr[n]: an array of integers
Print
Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with digits after the decimal. The function should not return a value.
Input Format
The first line contains an integer, , the size of the array.
The second line contains space-separated integers that describe .
Constraints
Output Format
Print the following lines, each to decimals:
proportion of positive values
proportion of negative values
proportion of zeros
Sample Input
6
-4 3 -9 0 4 1
Sample Output
0.500000
0.333333
0.166667
Explanation
There are positive numbers, negative numbers, and zero in the array.
The proportions of occurrence are positive: , negative: and zeros: .
'''
def plusMinus(arr):
p = sum(map(lambda x: x > 0, arr)) * 1.0/len(arr)
n = sum(map(lambda x: x < 0, arr)) * 1.0/len(arr)
z = sum(map(lambda x: x == 0, arr)) * 1.0/len(arr)
return f'{p:.6f}\n{n:.6f}\n{z:.6f}'
print(plusMinus([-4, 3, -9, 0, 4, 1])) |
b044ac8e0900ea8f23ccdf6b01f9f6c2b56640c7 | 15929134544/wangwang | /leetcode/14 最长公共前缀.py | 1,274 | 3.515625 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# # 思路一:
# # 空字符串
# if not strs:
# return ''
# for index in range(len(strs[0])):
# # 把第一个字符串的每个字母依次和后面每个字符串的字母做比较
# for str in strs[1:]:
# # 两种情况:
# # 1.完全一样就接着判断下一个
# # 2.不一样就直接返回
# # index >= len(str)应该写在之前
# if index >= len(str) or str[index] != strs[0][index]:
# # 如果不同直接返回前面相同的值
# return strs[0][:index]
# return strs[0]
# 思路二
result = ''
index = 0
while True:
try:
# 利用去重来判断每个字母是否相同
sets = set(str[index] for str in strs)
if len(sets) == 1:
result += sets.pop()
index += 1
else:
break
except Exception as e:
break
return result |
1a8556a871fa5a328ee8a0c600da163cb3d8277b | onitonitonito/k_mooc_reboot | /tortoise_hare.py | 1,376 | 4 | 4 | """
# finde duplicated number
given an array nums containing n+1 integers where each inter is between
1 & n (inclusve)
prove that at least one duplicate num must exist. Assue that there is only
duplicate num but it could be repeated more than once.
find the duplicate one.
Example 1:
- Input : [1,2,4,2,2]
- Output: 2
Example 2:
- Input : [1,3,4,6,6,6,5]
- Output: 6
* You must use only constant, 0(1) extra space.
* You must not modify the array (assue the array is read only once)
* Your runtime complexity should be less than 0(n2).
Floyd's Tortoise and Hare Algorithm
https://www.youtube.com/watch?v=pKO9UjSeLew&feature=youtu.be
"""
# tortoise & hare loop algorithm
# https://manducku.tistory.com/45
nums = [1,2,4,3,5,6,2]
nums = [1,3,4,6,6,6,5]
def main():
print(find_duplicate(nums))
print(find_hare_tortoise(nums))
def find_duplicate(nums):
seen = {}
for num in nums:
if num in seen:
return num
seen[num] = True
return seen
def find_hare_tortoise(nums):
tortoise = nums[0]
hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
ptr1 = nums[0]
ptr2 = tortoise
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
return ptr1
if __name__ == '__main__':
main()
pass
|
a5494c7da9b4739273c40e84b05daeb06c8e3ae3 | smitgabani/algorithms-python3 | /sorting/selection-sort.py | 323 | 3.71875 | 4 | def selsort(A):
r = len(A)
for x in range(r):
minimum = x
for y in range(x + 1, r):
if A[y] < A[minimum]:
minimum = y
(A[x], A[minimum]) = (A[minimum],A[x])
mylist = input('Enter the list values to be stored: ').split()
selsort(mylist)
print(mylist)
|
5f3b816c0dad6a85f6f79ed2f49a928aff9dc750 | RianMarlon/Python-Geek-University | /secao7_colecoes/exercicios1/questao23.py | 740 | 4.125 | 4 | """
23) Ler dois conjuntos de números reais, armazenando-os em vetores
e calcular o produto escalar entre eles. Os conjuntos têm 5 elementos
cada. Imprimir os dois conjuntos e o produto escalar, sendo que o produto
escalar é dado por: x1 * y1 + x2 * y2 + ... + xn * yn
"""
lista1 = []
lista2 = []
for i in range(5):
lista1.append(float(input("Digite um valor para o primeiro vetor: ")))
print()
for i in range(5):
lista2.append(float(input("Digite um valor para o segundo vetor: ")))
print(f"\nPrimeiro vetor: {lista1}")
print(f"Segundo vetor: {lista2}")
produto_escalar = 0
for i in range(5):
produto_escalar += (lista1[i] * (i+1)) * (lista2[i] * (i+1))
print(f"Produto escalar dos dois conjuntos: {produto_escalar}")
|
2d68a23199e80a85907d665fd0af9f248e37e9a4 | Sa4ras/amis_python71 | /km71/Likhachov_Artemii/3/Task7.py | 437 | 4 | 4 | print('This program calculate the count of hours and minutes after 00:00')
while True:
X = input('Input minutes: ')
try:
if int(X) >= 0:
h = int(X)//60
m = int(X)%60
print(h, 'hours', m, 'minutes')
break
else:
print('Try again')
continue
except ValueError:
print('Try again')
continue
print('Artemii Likhachov KM-71') |
8a394b2e6973a1610215e78c524527c5e066bf60 | ElcimarSilva/InterfaceGraficaPy | /main.py | 620 | 4.09375 | 4 | from tkinter import *
def infos_no_print():
texto = "Esta é minha mensagem no método"
texto_do_metodo["text"] = texto
janela = Tk()
janela.title("Minha janela criada em Python")
# janela.geometry("400x400")
texto_orientacao = Label(janela, text="Clique aqui para ver infos do método")
texto_orientacao.grid(column=0, row=0, padx=10, pady=10)
botao = Button(janela, text="Buscar infos que estão no método", command=infos_no_print)
botao = botao.grid(column=0, row=3, padx=10, pady=10)
texto_do_metodo = Label(janela, text="")
texto_do_metodo.grid(column=0, row=5, padx=10, pady=10)
janela.mainloop()
|
04e01661aa2d540993e644027e1791859de1016e | JaberKhanjk/LeetCode | /Array Problems/Sort Array By Parity II.py | 547 | 3.5 | 4 | class Solution(object):
def sortArrayByParityII(self, A):
n = len(A)
odd = []
even = []
for each in A:
if each % 2 == 0:
even.append(each)
else:
odd.append(each)
final = [0]*n
for i in range(n/2):
final[2*i+1] = odd[i]
final[i*2] = even[i]
return final
"""
:type A: List[int]
:rtype: List[int]
"""
|
f04fc11d9f06c6deddca4bfc1d92e8f52739bd69 | code-mic/Sololearn-Python-Core | /Fibonacci.py | 163 | 4.15625 | 4 | num = int(input())
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for number in range(num):
print(fibonacci(number))
|
14b6b7cfc759cdcb0ce848f67e576ebcdfe27070 | DipendraDLS/Python_OOP | /14.Thread_&_Multithreading/13.Single_Tasking_Using_Thread.py | 572 | 3.671875 | 4 | '''
- When multiple tasks are executed by a thread one by one, then it is called single tasking.
'''
from threading import Thread
from time import sleep
class MyExam(Thread):
def solve_questions(self):
self.q1()
self.q2()
self.q3()
def q1(self):
print('Q1 Solved')
sleep(3)
def q2(self):
print('Q2 Solved')
sleep(3)
def q3(self):
print('Q3 Solved')
mye = MyExam()
t = Thread(target=mye.solve_questions)
t.start() # Multiple task are being executed one by one.
|
05f070ee2296e17882060d7350a55d9a2a50ba9f | hsnylmzz/Python-Learning | /pyt/set4.py | 241 | 3.96875 | 4 | def kume_dondur(str_kume: str):
if str_kume.startswith("{") and str_kume.endswith("}"):
kume_elemanlari = str_kume[1:len(str_kume) -1]
v = kume_elemanlari.split(", ")
print(v)
kume_dondur("{1, 2, 3, 17}")
|
2b269158d03bb71c784dadfb2c877b56e9208618 | ruchamahabal/TXP_Tech_Events | /codemapper/q1.py | 740 | 3.75 | 4 | def prime_list(l):
result=[]
flag = 0
for i in l:
for j in range(2,i):
if i%j!=0:
flag = 1
else:
flag = 0
break
if flag == 1 or i==2 :
if i not in result:
result.append(i)
return result
# sample testcases
# test case 1
print(prime_list([2,3,6,7]))
# output 1 = [2, 3, 7]
# testcase 2
print(prime_list([4,6,8,10]))
# output 2 = []
# testcase 3
print(prime_list([44,71,356,1032]))
# output 3 = [71]
# hidden testcases
# testcase 1
print(prime_list([2,3,3,6,7,2]))
# output 1 = [2, 3, 7]
# testcase 2
print(prime_list([5,6,9,8,5,6,9,8]))
# output = [5]
# testcase 3
print(prime_list([]))
# output 3 = []
|
c76c43f407f7df9ed3497049e720eda7ec797f47 | poojithayadavalli/String | /IMEI validation.py | 1,759 | 4.25 | 4 | """
International Mobile Equipment Identity (IMEI) is a number, usually unique, to identify mobile phones, as well as some satellite phones.
The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin, model, and serial number of the device.
The task is to validate IMEI in following steps:
1.Starting from the rightmost digit, double the value of every second digit (e.g., 7 becomes 14).
2.If doubling of a number results in a two digits number i.e greater than 9(e.g., 7 × 2 = 14), then add the digits of the product
(e.g., 14: 1 + 4 = 5), to get a single digit number.
3.Now take the sum of all the digits.
4.Check if the sum is divisible by 10 i.e.(total modulo 10 is equal to 0) then the IMEI number is valid; else it is not valid.
Input:
Input contains the 14digit number
Output:
Print whether it is valid IMEI or not
Example:
Input:
490154203237518
Output:
Valid
Explanation:
IMEI: 4 9 0 1 5 4 2 0 3 2 3 7 5 1 8
Double:4 18 0 2 10 8 2 0 3 4 3 14 5 2 8
alternate
Sum :4+9+0+2+1+8+2+0+3+4+3+5+5+2+8=60
Since 60 is divisible by 10 It is a valid IMEI number.
Input:
695154204233518
Output:
Invalid
Input:
596154604273518
output:
Invalid
Input:
870154203237518
Output:
Valid
Input:
597154203237538
Output:
Invalid
"""
def sumDig( n ):
a = 0
while n > 0:
a = a + n % 10
n = int(n / 10)
return a
def isValidIMEI(n):
s = str(n)
l = len(s)
if l != 15:
return False
d = 0
sum = 0
for i in range(15, 0, -1):
d = (int)(n % 10)
if i % 2 == 0:
d = 2 * d
sum = sum + sumDig(d)
n = n / 10
return (sum % 10 == 0)
x=int(input())
if isValidIMEI(x):
print("Valid")
else:
print("Invalid")
|
16272970aa5433ed7481251935efb29d3e76b981 | sandeepkumar8713/pythonapps | /02_string/16_possible_space_in_string.py | 1,848 | 4.34375 | 4 | # https://www.geeksforgeeks.org/print-possible-inpStrs-can-made-placing-spaces/
# Question : Given a inpStr you need to print all possible strings that can be made by placing spaces
# (zero or one) in between them.
#
# Input: str[] = "ABC"
# Output: ABC
# AB C
# A BC
# A B C
#
# Question Type : Easy
# Used : Given a inpStr of length n, let its index be i.
# Make a list buff of length 2n and index j.
# Set first element of buff : buff[0] = inpStr[0]. Call the recursive function
# printPatternUtil(inpStr, buff, i, j, n) with i = 1 and j = 2.
# In recursive function if i == n: set buff[j] = '\0', print buff and return
# Here we have two option either to place space or not, so take both the routes.
# buff[j] = inpStr[i], printPatternUtil(inpStr, buff, i + 1, j + 1, n)
# buff[j] = ' ', buff[j + 1] = inpStr[i], printPatternUtil(inpStr, buff, i + 1, j + 2, n)
# Complexity : Since number of Gaps are n-1, there are total 2^(n-1) patters each having length
# ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)).
def toString(List):
s = ""
for x in List:
if x == '\0':
break
s += x
return s
def printPatternUtil(inpStr, buff, i, j, n):
if i == n:
buff[j] = '\0'
print(toString(buff))
return
# Either put the character
buff[j] = inpStr[i]
printPatternUtil(inpStr, buff, i + 1, j + 1, n)
# Or put a space followed by next character
buff[j] = ' '
buff[j + 1] = inpStr[i]
printPatternUtil(inpStr, buff, i + 1, j + 2, n)
def printPattern(inpStr):
n = len(inpStr)
buff = [0] * (2 * n)
buff[0] = inpStr[0]
printPatternUtil(inpStr, buff, 1, 1, n)
if __name__ == "__main__":
inpStr = "ABCD"
printPattern(inpStr)
|
ade1dda398282ab6e380793e113a0186ccdd69a0 | eucalypto/bitesofpy | /47/password.py | 1,356 | 3.953125 | 4 | import string
PUNCTUATION_CHARS = list(string.punctuation)
used_passwords = set('PassWord@1 PyBit$s9'.split())
def validate_password(password):
if len(password) < 6:
return False
if len(password) > 12:
return False
# This is an alternative for characters that need only one appearance.
# The advantage: the generator stops as soon as it gets a positive result.
# The disadvantage: it's hard to extend to require two appearances
#
# if not any(char in PUNCTUATION_CHARS for char in password):
# return False
# if not any(char in string.digits for char in password):
# return False
# if not any(char in string.ascii_uppercase for char in password):
# return False
digits = 0
lower = 0
upper = 0
punctuation = 0
for char in password:
if char in string.digits:
digits += 1
elif char in string.ascii_lowercase:
lower += 1
elif char in string.ascii_uppercase:
upper += 1
elif char in PUNCTUATION_CHARS:
punctuation += 1
if digits < 1:
return False
if lower < 2:
return False
if upper < 1:
return False
if punctuation < 1:
return False
if password in used_passwords:
return False
used_passwords.add(password)
return True
|
f4948d57dcfb16839e16488fedd316b5ab8b4732 | j-d-0630/python | /a0323_binary_tree_doi.py | 3,424 | 3.984375 | 4 | """
Binary Tree
根付き二分木の表現
id left rightの情報が付与されたときに
節点の情報をその番号が小さい順に出力する
node id, parent , depth, heigth
Preorder Tree Walk 先行順巡回
根節点, 左部分木, 右部分木の順番
Inorder Tree Walk 中間順巡回
左部分木, 根節点, 右部分木の順番
Postorder Tree Walk 後行順巡回
左部分木, 右部分木, 根節点の順番
"""
import dataclasses
@dataclasses.dataclass
class Node:
parent:int = None
left:int = None
right:int = None
depth:int = 0
height:int = 0
value:int = None
def rec(r,d):
Tree[r].depth = d
if Tree[r].right != None:
rec(Tree[r].right,d+1)
if Tree[r].left != None:
rec(Tree[r].left,d+1)
def set_hegiht(r):
h1 = 0
h2 = 0
if Tree[r].right != None:
h1 = set_hegiht(Tree[r].right) + 1
if Tree[r].left != None:
h2 = set_hegiht(Tree[r].left) + 1
Tree[r].height = h1 if h1 > h2 else h2
return Tree[r].height
def PreOrderWalk(r,walkList):
walkList.append(Tree[r].value)
if Tree[r].left != None:
PreOrderWalk(Tree[r].left,walkList)
if Tree[r].right != None:
PreOrderWalk(Tree[r].right,walkList)
def InOrderWalk(r,walkList):
if Tree[r].left != None:
InOrderWalk(Tree[r].left,walkList)
walkList.append(Tree[r].value)
if Tree[r].right != None:
InOrderWalk(Tree[r].right,walkList)
def PostOrderWalk(r,walkList):
if Tree[r].left != None:
PostOrderWalk(Tree[r].left,walkList)
if Tree[r].right != None:
PostOrderWalk(Tree[r].right,walkList)
walkList.append(Tree[r].value)
if __name__ == "__main__":
input_data = []
input_data.append("0 1 4")
input_data.append("1 2 3")
input_data.append("2 -1 -1")
input_data.append("3 -1 -1")
input_data.append("4 5 8")
input_data.append("5 6 7")
input_data.append("6 -1 -1")
input_data.append("7 -1 -1")
input_data.append("8 -1 -1")
N = len(input_data)
Tree = [ Node() for i in range(N) ]
for data_str in input_data:
data = data_str.split()
node_id = int(data[0])
node_left = int(data[1])
node_right = int(data[2])
Tree[node_id].value = node_id
if node_right != -1:
Tree[node_id].right = node_right
Tree[node_right].parent = node_id
if node_left != -1:
Tree[node_id].left = node_left
Tree[node_left].parent = node_id
r_index = 0
for i in range(N):
if Tree[i].parent == None:
r_index = i
rec(r_index,0)
set_hegiht(r_index)
print(Tree)
walkList = []
PreOrderWalk(0,walkList)
print("PreOrderWalk Result")
print(walkList)
walkList = []
InOrderWalk(0,walkList)
print("InOrderWalk Result")
print(walkList)
walkList = []
PostOrderWalk(0,walkList)
print("PostOrderWalk Result")
print(walkList)
# Treeを可視化 # graphviz
from graphviz import Digraph
g = Digraph(format='png')
g.attr('node', shape='circle')
for edge_info in Tree:
if edge_info.parent != None:
g.edge(str(edge_info.parent), str(edge_info.value))
g.view() |
490bfd37ebfa51bcf4eaf3019f0fdf6c542e5127 | titoeb/python-desing-patterns | /python_design_patterns/bridge/ex.py | 1,235 | 3.734375 | 4 | from abc import ABC
class Shape:
def __init__(self, renderer):
self.name = None
self.renderer = renderer
class Triangle(Shape):
def __init__(self, renderer):
super().__init__(renderer)
self.name = "Triangle"
def __str__(self):
return self.renderer.render_triangle
class Square(Shape):
def __init__(self, renderer):
super().__init__(renderer)
self.name = "Square"
def __str__(self):
return self.renderer.render_square
# imagine VectorTriangle and RasterTriangle are here too
class Renderer(ABC):
@property
def what_to_render_as(self):
return None
class VectorRenderer(Renderer):
@property
def render_triangle(self):
return f"Drawing Triangle as lines"
@property
def render_circle(self):
return f"Drawing Circle as lines"
class RasterRenderer(Renderer):
@property
def render_triangle(self):
return f"Drawing Triangle as pixels"
@property
def render_circle(self):
return f"Drawing Circle as pixels"
# TODO: reimplement Shape, Square, Triangle and Renderer/VectorRenderer/RasterRenderer
if __name__ == "__main__":
print(str(Triangle(RasterRenderer()))) |
ccdf74f0435d63c7efe74177bcc8f34a4c7eae1b | anandshudda/dat-chapter-2 | /numpy_practice.py | 2,022 | 3.875 | 4 | import pandas as pd
import numpy as np
# 1. Use arange to create an array of the numbers from 0 to 100.
a = np.arange(101)
print "Array of the numbers from 0 to 100: ", '\n', a, '\n'
# 2. Create two arrays [1, 3, 5] and [2, 4, 6] and add them.
x = [1, 3, 5]
y = [2, 4, 6]
z = np.add(x,y)
print "Adding [1, 3, 5] and [2, 4, 6]: ", '\n', z, '\n'
# 3. Create a 3-by-6 matrix and then find out its dimensionality using ndim.
m = np.matrix([[1,2,3,4,5,6], [11, 12, 13, 14, 15, 16], [21, 22, 23, 24, 25, 26]])
print "matrix m: ", '\n', m, '\n'
print "Dimensions of m: ", m.ndim
print "shape of m: ", m.shape
# 4. In the aforementioned matrix, use dtype to discover the data types within the matrix.
print "Data types within the above matrix: ", m.dtype, '\n'
# 5. Create a 4-by-5 matrix full of zeros using zeros.
z = np.zeros((4,5))
print "4-by-5 matrix full of zeros: ", '\n', z, '\n'
# Then, create a 5-by-4 matrix full of ones using ones.
o = np.ones((5,4))
print "5-by-4 matrix full of ones: ", '\n', o, '\n'
# 6. Use reshape to turn the array from Question 1 into a 10-by-10 matrix.
ai = a[0:100]
#am = np.asmatrix(ai.reshape(10,10))
am = ai.reshape(10,10)
print "10-by-10 matrix: ", am, '\n'
# 7. Given two 2-by-2 arrays A and B of your creation, do A * B and dot(A, B). What's the difference?
Aa = np.arange(4)
A = Aa.reshape(2,2)
Bb = np.arange(4)
B = Bb.reshape(2,2)
print "A * B is: ", '\n', A * B, '\n'
print "dot(A,B) is: ", '\n', np.dot(A,B), '\n'
# 8. Given the array in Question 1, set every 2nd element to 31415. (Hint: use the third parameter in list slicing)
a = np.arange(101)
a[::2] = 31415
print "Set every 2nd element of a to 31415: ", '\n', a, '\n'
# 9. Write a function that takes any arbitrary multidimensional array (aka matrix)
# and returns just the nth column. Hint: the function will look like def retrieve_column(matrix, n).
def retrieve_column(matrix, n):
return matrix[:,n]
print "Input matrix is: ", '\n', am, '\n'
print "nth column: ", '\n', retrieve_column(am, 1) |
f1576b68a38ea069cae3dbf808f9e4a37863e00c | LisandroGuerra/zombies1 | /Lista3_desafio/questao05.py | 70 | 3.59375 | 4 | num = input("Entre com número inteiro positivo: ")
print (num[::-1])
|
29e9a3e5f31badc37a0c7d00dd0a7c3dcad510b2 | StylishSdp/ProgrammingTask | /Task2/栈/有效的括号.py | 800 | 4 | 4 | def isValid(s):
if not s:
return True
if len(s) % 2 != 0: #通过一些明显的条件去掉一些False的例子
return False
if s[0] == ')' or s[0] == ']' or s[0] == '}':
return False
if s[-1] == '(' or s[-1] == '[' or s[-1] == '{':
return False
stack = []
for i in range(len(s)):
if s[i] == '(' or s[i] == '[' or s[i] == '{':
stack.append(s[i])
elif s[i] == ')' and stack[-1] == '(': #匹配条件:当前为右括号,且栈顶为对应的左括号,才能出栈
stack.pop()
elif s[i] == ']' and stack[-1] == '[':
stack.pop()
elif s[i] == '}' and stack[-1] == '{':
stack.pop()
if len(stack) == 0:
return True
else:
return False |
fdcae381bf9aef293f664de508f1fe575bc250ce | simranmahindrakar/DAA-things | /gh - Copy.py | 570 | 3.625 | 4 | ##def mystery(l):
## if len(l) < 2:
#### return (l)
## else:
## return ([l[-1]] + mystery(l[1:-1]) + [l[0]])
runs = {"Test":{"Dhawan":[190,14,35,119],"Kohli":[3,103,13,42],"Pujara":[153,15,133,8]},"ODI":{"Dhawan":[37],"Kohli":[63]}}
#runs["ODI"]["Pujara"].extend([44])
#runs["ODI"]["Pujara"].append([44])
#runs["ODI"]["Pujara"][0]=44
#runs["ODI"]["Pujara"]=[44]
inventory={}
inventory[("Amul","Mystic Mocha")] = 55
#inventory[["Amul","Mystic Mocha"]] = 55
inventory["Amul, Mystic Mocha"] = 55
inventory["Amul"] = ["Mystic Mocha",55]
|
4311e7c569bfb53fc8a127f9d56629f4a6671e35 | Jack-Sh/04_Math_Quiz | /08_greater_lesser.py | 1,363 | 4.15625 | 4 | import random
def choice_checker(question, valid_list, error):
valid = False
while not valid:
# Ask user for choice (and put in lowercase)
response = input(question).lower()
# iterates through list and if response is an item
# in the list (or the first letter of an item), the
# full item name is returned
for item in valid_list:
if response == item[0] or response == item:
return item
else:
print(error)
true_false_list = ["true", "false"]
lowest = 1
highest = 10
statement = "greater_lesser"
endgame = "no"
while endgame != "yes":
chosen_num = random.randint(lowest, highest)
num_1 = random.randint(lowest, highest)
num_2 = random.randint(lowest, highest)
if statement == "greater_lesser":
if chosen_num == 1:
question = "{} > {}".format(num_1, num_2)
else:
question = "{} < {}".format(num_1, num_2)
print(question)
correct_answer = eval(question)
if correct_answer == True:
answer = "true"
else:
answer = "false"
true_false = choice_checker("Is this equation True or False? ", true_false_list, "Please enter true or false")
if true_false == answer:
print("CORRECT")
else:
print("INCORRECT") |
ecbd30291b872f1099f59a37326443259464e816 | EmsDz/EmsDominoGame | /Clases/ClassHandPlay.py | 3,472 | 3.640625 | 4 |
#
class handPlay(object): # partida
"""docstring for handPlay"""
def __init__(self, players):
self.handPlayNumber = 0 # present hand play, is integer
self.players = players # players in this round, is a list
self.firstsTurn = '' # who play first
self.openGameToken = '' # the token that start the game
self.winner = None # name of the winner
self.points = 0 # count of points of the current handPlay
self.currentRound = []
self.handPlayLog = {}
# make the order of play, that can vary in handplay to handplay
def makePlayOrder(self):
for t in range(0, len(self.players)):
if self.players[t].name == self.firstsTurn:
self.players = self.players[t:] + self.players[0:t]
# finds the first turn in each start game
def makeFirstsTurn(self):
# look for a double
for double in ['66', '55', '44', '33', '22', '11', '00']:
# raise Exception('something happend')
for player in self.players:
if double in player.tokens:
self.firstsTurn = player.name
self.openGameToken = double
return
# look for maximum token
maxToken = 0
for player in self.players:
for x in player.tokens:
if int(x) > maxToken:
temporaryFirstsTurn = player.name
maxToken = int(x)
self.firstsTurn = temporaryFirstsTurn
self.openGameToken = str(maxToken)
return
def openHandPlay(self, player):
print('Open With Double')
print(player.name, 'Start This Round.')
input('Press enter to continue')
if player.imAbot:
# play automatically
if self.openGameToken == '':
maxToken = 0
for x in player.tokens:
if int(x) > maxToken:
maxToken = int(x)
self.openGameToken = str(maxToken)
print(player.name + ' Played: ', self.openGameToken)
return player.tokens.pop(self.openGameToken)
# human play
player.showPlayerTokens()
token = input('Enter Token To Play: ').upper()
# ended game
if token in ['X', 'SALIR', 'EXIT', 'EX', 'CLOSE', 'END']:
if player.leaveGame():
return 'EXIT'
# controls the input
while token not in player.tokens or token != self.openGameToken:
if token != self.openGameToken and self.openGameToken in player.tokens:
if self.handPlayNumber != 1:
break
print('You Need To Start With a Double. A bigger one, like: ', self.openGameToken)
elif token not in player.tokens:
print('Invalid Token.')
else:
break
token = input('Enter Token Again: ')
# ended game
if token in ['X', 'SALIR', 'EXIT', 'EX', 'CLOSE', 'END']:
if player.leaveGame():
return 'EXIT'
print(player.name + ' Played: ' + token)
return player.tokens.pop(token)
def showHandLog(self):
for l in self.handPlayLog:
print(str(l), end=' ')
for log in self.handPlayLog[l]:
print(log[0].name + ': ' + log[1], end=' ')
print('')
print('\n')
|
fff5cd69fc413a7bbd29ad8b5c76d9aff0b237b6 | Zabdielsoto/Curso-Profesional-Python | /7.- Unidad/Ejercicio2.py | 624 | 4.25 | 4 | '''Ejercicio 2: Clases
Modifique el método del ejercicio
anterior para convertirlo en una propiedad (@property)
'''
class Punto:
def __init__(self, x, y):
self.x = x
self.y = y
@property
def cuadrante(self):
if self.x > 0 and self.y > 0:
print("Primer cuadrante")
elif self.x < 0 and self.y > 0:
print("Segundo Cuadrante")
elif self.x > 0 and self.y < 0:
print("Tercer Cuadrante")
elif self.x < 0 and self.y < 0:
print("Cuarto Cuadrante")
p1 = Punto(1,1)
p2 = Punto(-1,1)
p3 = Punto(1,-1)
p4 = Punto(-1,-1)
p1.cuadrante
p2.cuadrante
p3.cuadrante
p4.cuadrante |
850796d4461986e2e29f34a882786e899a7bad8a | brucemin/repertory | /exercise05/3.py | 776 | 3.75 | 4 | Number = int(input('请输入一个三位数:'))
#输出每一位上的数
a = int(Number/100)
b = int((Number-100*a)//10)
c = int(Number%10)
#判断a,b,c大小,并按从大到小排列,再从小到大排列
if a>b and a>c and b>c:
print(str(a) + str(b) + str(c))
print(str(c) + str(b) + str(a))
elif a>b and a>c and c>b:
print(str(a) +str(c) +str(b))
print(str(b) + str(c) + str(a))
elif b>a and b>c and a>c:
print(str(b) + str(a) + str(c))
print(str(c) + str(a) + str(b))
elif b>a and b>c and c>a:
print(str(b)+ str(c) + str(a))
print(str(a) + str(c) + str(b))
elif c>a and c>b and a>b:
print(str(c) + str(a) + str(b))
print(str(b) + str(a) + str(c))
else:
print(str(c)+ str(b) + str(a))
print(str(a)+ str(b) + str(c))
|
f212ee7e13223eb60571b62499e56ceeef2d9bbd | Helton-Rubens/Python-3 | /exercicios/exercicio037.py | 780 | 3.9375 | 4 | num = int(input('Digite um número inteiro: '))
print('+='*10)
print('''\nEscolha uma das bases para conversão:
[\033[1;34m1\033[m] Converter para \033[4;35mBINÁRIO\033[m
[\033[1;34m2\033[m] Converter para \033[4;35mOCTAL\033[m
[\033[1;34m3\033[m] Converter para \033[4;35mHEXADECIMAL\033[m\n''')
opc = int(input('Sua opção: '))
if opc == 1:
print('O número {} convertido para \033[1;34mbinário\033[m é: {}.'.format(num, bin(num) [2:]))
elif opc == 2:
print('O número {} convertido para \033[1;34moctal\033[m é: {}.'.format(num, oct(num) [2:]))
elif opc == 3:
print('O número {} convertido para \033[1;34mhexadecimal\033[m é: {}'.format(num, hex(num) [2:]))
else:
print('\033[1;31mAlerta!\033[m \n\033[1;31mOpção inválida. \nTente novamente.\033[m') |
ef91a079fb73758417e844ab90c3575104c746cd | ludwigwittgenstein2/Algorithms-Python | /copyThird.py | 988 | 3.828125 | 4 | #!/bin/Python
"""
Logging in Python
"""
import logging
def firstLog():
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('Start reading database')
#read database here
records = {'John':55, 'tom':66}
logger.debug('Records:%s', records)
logger.info('Updating records....')
#update records here
logger.info('Finish updating records')
def secondLog():
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a file Handler
handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)
# Create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info('Hello baby')
def main():
secondLog()
if __name__ == '__main__':
main()
|
32de8a183bb0b8f673d185544e8d83a2b9757e1e | jproddy/rosalind | /bioinformatics_stronghold/seto.py | 1,263 | 3.84375 | 4 | '''
Introduction to Set Operations
http://rosalind.info/problems/seto/
Given: A positive integer n (n≤20,000) and two subsets A and B of {1,2,…,n}.
Return: Six sets: A∪B, A∩B, A−B, B−A, Ac, and Bc (where set complements are taken with respect to {1,2,…,n}).
'''
filename = 'rosalind_seto.txt'
def union(A, B):
return A | B
# alternatively,
# u = A.copy()
# for element in B:
# if element not in u:
# u.add(element)
# return u
def intersection(A, B):
return A & B
# alternatively,
# i = set()
# for element in A: # can optimize by using the smaller of the sets here
# if element in B:
# i.add(element)
# return i
def set_difference(A, B):
return A - B
# alternatively,
# d = set()
# for element in A:
# if element not in B:
# d.add(element)
# return d
def complement(A, n):
# wrt {1,2,...,n}
return set(range(1, n+1)) - A
def main():
with open(filename) as f:
n = int(f.readline().strip())
A = {int(i) for i in f.readline().strip()[1:-1].split(', ')}
B = {int(i) for i in f.readline().strip()[1:-1].split(', ')}
print(union(A, B))
print(intersection(A, B))
print(set_difference(A, B))
print(set_difference(B, A))
print(complement(A, n))
print(complement(B, n))
if __name__ == '__main__':
main()
|
fd4c8a3f8de296ae8df949979ffd8c3602b97369 | wong2/PyOthello | /src/network.py | 1,292 | 3.75 | 4 | '''
network.py
This module defines class Server and Client. They are used in network games.
'''
import socket, sys, os
class Server:
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 5543
self.socket.bind(('', port))
self.socket.listen(1)
def waitingForClient(self):
(self.conn, addr) = self.socket.accept()
self.cf = self.conn.makefile('rw', 0)
return str(addr)
def sendAndGet(self, row, col):
self.cf.write(str((row, col))+'\n')
x, y = eval(self.cf.readline()[:-1])
return (x, y)
def close(self):
print "I'm server, Bye!"
self.conn.close()
class Client:
def __init__(self, host):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 5543
self.s.connect((host, port))
print 'connected to ' + host
self.sf = self.s.makefile('rw', 0)
def getFromServer(self):
row, col = eval(self.sf.readline()[:-1])
return (row, col)
def sendToServer(self, row, col):
self.sf.write(str((row, col))+'\n')
def close(self):
self.sf.close()
self.s.close()
print "I'm client, bye!" |
6340c85c3136ea4615724301b87e5252fc67077e | klisostom/Python | /Projetos/decida_por_mim.py | 938 | 3.59375 | 4 | import random
"""
Objetivo: Crie um script que responda qualquer pergunta que for feita a ele. Recomendo ter
uma base de possíveis respostas (10-20 ou mais). Ex: Será que devo sair de casa hoje? Seu
script reponde: “Sim, vai lá!”
"""
conjunto_respostas = [
'Sim, vai lá!',
'Não, é estranho!',
'Talvez dê certo.',
'Talvez, quem sabe?!',
'Pode ser.',
'Eu acho que não.',
'Pode ser amanhã?',
'E se fosse com você?',
'E se fosse comigo?',
'E se fosse com um parente seu?',
'Não, acredito que não.',
'Tu vai mesmo é?',
'Vai dar certo!',
'Tem que dar certo, desta vez.',
'Vamos tocer!',
'Daqui há 1 hora nós vamos.',
'Já não sei o que dizer.',
'Isso é possível!',
'Falta pouco!',
'É isso aí!'
]
pergunta = input("Faça alguma pergunta:\n")
resposta = conjunto_respostas[random.randrange(1, len(conjunto_respostas) + 1)]
print(resposta) |
3bd64d83524d44d8229de0fc8be77de7f4c75201 | vitthalpadwal/Python_Program | /hackerrank/python_sort.py | 1,765 | 4.375 | 4 | """
You are given a spreadsheet that contains a list of athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the th attribute and print the final resulting table. Follow the example given below for better understanding.
image
Note that is indexed from to , where is the number of attributes.
Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input.
Input Format
The first line contains and separated by a space.
The next lines each contain elements.
The last line contains .
Constraints
Each element
Output Format
Print the lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity.
Sample Input 0
5 3
10 2 5
7 1 0
9 9 9
1 23 12
6 5 9
1
Sample Output 0
7 1 0
10 2 5
6 5 9
9 9 9
1 23 12
Explanation 0
The details are sorted based on the second attribute, since is zero-indexed.
"""
# !/bin/python
'''
from __future__ import print_function
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nm = raw_input().split()
n = int(nm[0])
m = int(nm[1])
arr = []
for _ in xrange(n):
arr.append(map(int, raw_input().rstrip().split()))
k = int(raw_input())
arr.sort(key=lambda x:x[1][k])
for i in range(N):
for j in range(M):
print(i[1][j])
'''
from __future__ import print_function
from collections import defaultdict, OrderedDict
I = map(int, raw_input().split())
D = OrderedDict()
for i in xrange(I[0]): D[i] = map(int, raw_input().split())
K = input()
k = sorted(D.items(), key=lambda x: x[1][K])
for i in k:
print(*i[1])
|
1c4f2dd4d21fbe5251870e40ad305a55e5f760b8 | jugu/projecteuler | /20160112_euler003.py | 497 | 3.765625 | 4 | '''The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?'''
''' number of test cases '''
import math
Ts = raw_input('')
T = int(Ts)
caseN = list()
for i in range(T):
caseN.append(long(raw_input('')))
for N in caseN:
x = 2
while N%x == 0:
N = int(N/x)
max = N
x = 3
while x <= int(math.sqrt(N)):
if (N%x == 0):
N = int(N/x)
max = N
else:
x = x + 2
print max |
efcc50989912ee5f4dc8e8569ce6be68e68d4010 | Syyan7979/Kattis-Solutions-python- | /Python Kattis/Kattis124(drmmessages).py | 479 | 3.75 | 4 | import string
alphabet = string.ascii_uppercase
def message(someString):
counter = 0
out = ""
for i in someString:
counter += alphabet.index(i)
for i in someString:
out += alphabet[(alphabet.index(i) + counter)%26]
return out
def conversion(A, B):
out = ""
for i in range(len(A)):
out += alphabet[(alphabet.index(A[i]) + alphabet.index(B[i])) % 26]
print(out)
ab = input()
a, b = ab[:len(ab)//2], ab[len(ab)//2:]
w1, w2 = message(a), message(b)
conversion(w1, w2) |
5e113a23f68b740462a4d98cfbac6b6c233271aa | tchaitanya2288/pyproject01 | /dictionaries methods/set_update.py | 306 | 3.875 | 4 | ##6 Set Union with Mutation = a_set.update()
# Syntax: a_set.update(an_iter)
# Example:
s = set([1, 2, 3, 4, 5])
s.update(set([5, 6, 7]))
print(s)
#Output : set([1, 2, 3, 4, 5, 6, 7])
'''
Mutates a_set to be the union of set a_set and the set of
elements in iterable an_iter. Returns None.
'''
'' |
ac8c7716c9ed9da4842bb1afdacb7cbaa4f532f2 | youinmelin/practice2020 | /recurrence_03_maze.py | 3,215 | 3.71875 | 4 | from random import choice
import sys
sys.setrecursionlimit(3000) # set the maximum depth as 3000
# 0: wall, 1:road, 2:terminal, 3:wrong road, 4:passed road
class Maze():
def __init__(self,maze_list):
self.maze_list = maze_list
self.currentx = 1
self.currenty = 1
self.stepx = 0
self.wrong_num = 0
def go_ahead(self,dir_num=0):
# print(f'x={x},y={y},{direction}')
if dir_num > 3:
dir_num = 0
#dir_list = [[1,0,'right'],[0,1,'down'],[-1,0,'left'],[0,-1,'up']]
dir_list = [[1,0,'down'],[0,1,'right'],[-1,0,'up'],[0,-1,'left']]
#dir_list = [[0,1,'down'],[1,0,'right'],[0,-1,'up'],[-1,0,'left']]
# y,x,direction = dir_list[random.randint(0,3)]
x,y,direction = dir_list[dir_num]
print(y,x,direction,end=' ')
self.currentx += x
self.currenty += y
self.stepx += 1
print('try:', self.currenty, self.currentx, 'step :', self.stepx)
# wrong_num : count continuous wrong steps
block = self.maze_list[self.currentx][self.currenty]
if block == 0 or block == 3 or block == 4:
# If failed, go back one step
self.currentx -= x
self.currenty -= y
self.stepx -= 1
self.wrong_num += 1
print('----wrong---- ',self.wrong_num)
# if continuous wrong steps is 3,then set this block is 0
if self.wrong_num == 4:
self.maze_list[self.currentx][self.currenty] = 1
self.wrong_num = 0
# if self.wrong_num == 3:
# self.maze_list[self.currentx][self.currenty] = 3
print('back to :', self.currenty, self.currentx)
print(f'current x,y = {self.currentx},{self.currenty} ')
# if failed, change a direction
self.go_ahead(dir_num+1)
# Be able to continue
elif self.maze_list[self.currentx][self.currenty] == 1:
self.wrong_num = 0
self.passedx = self.currentx - x
self.passedy = self.currenty - y
self.maze_list[self.passedx][self.passedy] = 4
print(f'{self.passedx},{self.passedy} = 4')
print(f'current x,y = {self.currentx},{self.currenty} ')
self.go_ahead(choice([0,1,2,3]))
# Reach the terminal
elif self.maze_list[self.currentx][self.currenty] == 2:
print('stopped at :', self.currenty, self.currentx)
print('steps is :', self.stepx)
return True, self.stepx
else:
return 'wrong maze!', self.stepx
if __name__ == '__main__':
maze_list1 = [[0,0,0,0,0,0,0],
[0,1,1,1,1,2,0],
[0,0,0,0,0,0,0]]
maze_list2 = [[0,0,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,1,0],
[0,2,0],
[0,0,0]]
maze_list3 = [[0,0,0,0,0,0,0],
[0,1,1,1,1,0,0],
[0,0,1,1,1,2,0],
[0,0,0,0,0,0,0]]
# print(maze_list1)
maze1 = Maze(maze_list3)
maze1.go_ahead()
for i in maze1.maze_list:
print(i)
|
b30707789ef8429c866ac0190ed2c0edcbe2725f | zuohd/python-excise | /python_project/turple.py | 127 | 3.890625 | 4 | tuple1 = (1,)
print(tuple1)
tuple2 = (2, 3, 4, 5, 6)
print(tuple2[0])
print(tuple2[-1])
# tuple can not change :tuple2[0]=1
|
53cbd077e5f6f5da71d972e87223357fa8600dd0 | C-CCM-TC1028-111-2113/homework-1-JennyAleContreras | /assignments/22DigitosPares/src/exercise.py | 529 | 3.890625 | 4 | def main():
#escribe tu código abajo de esta línea
number = input('Dame un número: ')
pair = int
for i in range(0, 10):
pair = 0
if int(number[0])%2 == 0:
pair = pair + 1
if int(number[1])%2 == 0:
pair = pair + 1
if int(number[2])%2 == 0:
pair = pair + 1
if int(number[3])%2 == 0:
pair = pair + 1
print('El número de dígitos pares es:',str(pair))
pass
if __name__ == '__main__':
main()
|
072d3165615dcb15084e2f7dbc56ce6af3470317 | hn-on-fire/Python | /Basic Projects/Arithmetic Formatter/arithmatic_formater.py | 1,790 | 3.640625 | 4 | def arithmetic_arranger(questions, answers=False):
if len(questions) > 5:
return 'Error: Too many problems.'
print1, print2, print3, print4 = "", "", "", ""
for inpNums in questions:
nums = inpNums.split()
if nums[1] != '+' and nums[1] != '-':
return 'Error: Operator must be \'+\' or \'-\'.'
num1, num2 = None, None
try:
num1 = int(nums[0])
num2 = int(nums[2])
except ValueError:
return 'Error: Numbers must only contain digits.'
if num1 > 9999 or num2 > 9999:
return 'Error: Numbers cannot be more than four digits.'
max_len = max(len(nums[0]), len(nums[2]))
line1, line2, line3 = "", "", ""
if max_len == len(nums[0]):
line1 = " " + nums[0]
line2 = nums[2]
for i in range(len(line1) - len(line2) - 1):
line2 = " " + line2
line2 = nums[1] + line2
else:
line2 = nums[1] + " " + nums[2]
line1 = nums[0]
while len(line1) < len(line2):
line1 = " " + line1
for _ in range(len(line1)):
line3 += "-"
print1 += (line1 + " ")
print2 += (line2 + " ")
print3 += (line3 + " ")
if answers:
ans = None
if nums[1] == '-':
ans = str(num1 - num2)
else:
ans = str(num1 + num2)
while len(line1) > len(ans):
ans = " " + ans
print4 += (ans + " ")
if answers:
return print1.rstrip() + "\n" + print2.rstrip() + "\n" + print3.rstrip() + "\n" + print4.rstrip()
else:
return print1.rstrip() + "\n" + print2.rstrip() + "\n" + print3.rstrip()
|
be6333704328b9c7c85bc00ebd34f5080b078800 | augustkx/defer-defaults | /defer_defaults/deferral.py | 798 | 3.5 | 4 | import inspect
from functools import wraps
deferred = object()
# An implementation of the deferrable args wrapper suggested by Jonathon Fine
def deferrable_args(func):
"""
Use this to decorate a function that you want to accept "defer" arguments, which will be overwritten by defaults.
:param func: A function
:return: A function with the same signature, which will swaps in defaults for deferred arguments then calls func
"""
sig = inspect.signature(func)
@wraps(func)
def defer_args(*args, **kwargs):
overridden_args = sig.bind(*args, **kwargs).arguments
for k, v in overridden_args.items():
if v is deferred:
overridden_args[k] = sig.parameters[k].default
return func(**overridden_args)
return defer_args
|
30043b764335efa70034fe0d312166c8dcd3c3b8 | kmurphy/coderdojo | /07-Monkey_Wars/code/Monkey_Wars.py | 3,728 | 3.90625 | 4 | import turtle
import math
import random
screen = turtle.Screen()
screen.setup (width=600, height=600, startx=0, starty=0)
screen.setworldcoordinates(-300,-10,300,500)
WINDOW_WIDTH = 25
FLOOR_HEIGHT = 40
bob = turtle.Turtle() # draws the city
red = turtle.Turtle() # red player
blue = turtle.Turtle() # blue player
def jump(t, x,y):
t.penup()
t.setposition(x,y)
t.pendown()
def draw_rectangle(x,y, width, height, color="black"):
jump(bob,x,y)
bob.color(color)
bob.begin_fill()
bob.setheading(0)
bob.forward(width)
bob.left(90)
bob.forward(height)
bob.left(90)
bob.forward(width)
bob.left(90)
bob.forward(height)
bob.left(90)
bob.end_fill()
#draw_rectangle(100,0,50,100)
def draw_building(x,y, windows, floors, color="black", health=1):
height = floors*FLOOR_HEIGHT
width = windows*WINDOW_WIDTH
print ("Building with %d floors and %d windows per floor"
% (floors, windows))
draw_rectangle(x,y, width, height, color=color);
for floor in range(floors):
for window in range(windows):
color = "yellow" if random.random()<health else "black"
draw_rectangle(x+(0.3+window)*WINDOW_WIDTH,
y + (0.3+floor)*FLOOR_HEIGHT,
WINDOW_WIDTH*0.4, FLOOR_HEIGHT*0.4, color)
red = turtle.Turtle()
blue = turtle.Turtle()
def draw_city():
screen.tracer(0)
red.floors = random.randint(2,10)
red.health = 1
blue.floors = random.randint(2,10)
blue.health = 1
draw_building(-300,0,3,red.floors , "red", red.health)
draw_building(-50,20,3,11, "gray")
draw_building(-150,20,10,9, "gray")
draw_building(-225,0,5,6)
draw_building(0,10,7,3, "darkgray")
draw_building(90,0,5,4)
draw_building(215,0,3, blue.floors, "blue", 0.1)
screen.tracer(1,1)
draw_city()
jump(red,-280,red.floors*FLOOR_HEIGHT+10)
red.setheading(90)
red.shape("triangle")
red.shapesize(0.5)
red.color("red")
jump(blue,270,blue.floors*FLOOR_HEIGHT+10)
blue.setheading(90)
blue.shape("triangle")
blue.shapesize(0.5)
blue.color("blue")
def redUp():
red.left(2)
print ("Player red heading is now %s" % red.heading())
def redDown():
red.right(2)
print ("Player red heading is now %s" % red.heading())
def redFire():
print ("Player red fired")
fire(red)
def blueUp():
blue.left(2)
print ("Player blue heading is now %s" % blue.heading())
def blueDown():
blue.right(2)
print ("Player blue heading is now %s" % blue.heading())
def blueFire():
print ("Player blue fired")
fire(blue)
def fire(player):
pass
# create a new turtle to represent the rock
screen.tracer(0)
ball = turtle.Turtle()
ball.shape("circle")
ball.shapesize(0.5)
# move rock to player position and heading
x, y = player.position()
jump(ball, x, y)
# use projectile logic to get vertical and horizontal speed
speed = 100
dt = 0.05
angle = math.pi/180*player.heading()
dx = speed*math.cos(angle)
dy = speed*math.sin(angle)
# animate rock movement
screen.tracer(1)
while 1:
# update rock position
x = x + dx*dt
y = y + dy*dt
dy = dy - dt*9.81
ball.goto(x,y)
# check if rocks moved passed city
if x<-300 or x>300 or y<0: break
# check if collision with buildings
# check if passed screen
ball.clear()
screen.onkey(redUp, "q")
screen.onkey(redDown, "a")
screen.onkey(redFire, "z")
screen.onkey(blueUp, ".")
screen.onkey(blueDown, ",")
screen.onkey(blueFire, "m")
screen.listen()
screen.mainloop() |
15162c4c356ea7eb2439412d745c6c515903e684 | afrayz29/python-lessons | /exercises/11-Your-First-If/app.py | 249 | 3.890625 | 4 |
total = int(input('How much money do you have in your pocket\n'))
# YOUR CODE HERE
if total>100:
print("give me your money!")
elif total>50:
print("buy me some coffee your cheap!")
elif total<50:
print("you are a poor guy, go away!")
|
71501d9ebfa06c33e9ea9c6343be65a5e1785578 | Kostimo/IT2SCHOOL | /PythonLessons spring 2021/Week4/task3.py | 162 | 3.625 | 4 | A = [1,2,3,4,5,6,7,8,9,10]
m = int(input("M: "))
print(A)
def shift(lst, sh):
x = len(lst) - (sh%len(lst))
return lst[x:] + lst[:x]
print(shift(A, m))
|
cb9ef8e6c0a1e59a7b4b8ebcce88a6206de1c031 | Ravitejagupta/Python | /lc-1315.py | 1,207 | 3.53125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from queue import deque
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
visited = set()
if not root:
return 0
ans = 0
q = deque()
q.append(root)
while q:
node = q.popleft()
l,r = node.left, node.right
if l: q.append(l)
if r: q.append(r)
if node.val%2 == 0:
if l:
if l.left and l.left not in visited:
ans += l.left.val
visited.add(l.left)
if l.right and l.right not in visited:
ans += l.right.val
visited.add(l.right)
if r:
if r.left and r.left not in visited:
ans += r.left.val
visited.add(r.left)
if r.right and r.right not in visited:
ans += r.right.val
visited.add(r.right)
return ans
|
f8985f583de1e83d9efe1ceb36142456edb9fac8 | safat/pratice | /src/codeforces/A281.py | 198 | 4 | 4 | def capitalize(input):
first_char = input[0]
if 'a' <= first_char <= 'z':
first_char = str(chr(ord(first_char) - 32))
return first_char + input[1:]
print(capitalize(input()))
|
f8d64dbaef27baf1b79034d0009de8a7745568b9 | deepakag5/Data-Structure-Algorithm-Analysis | /leetcode/binarytree_second_minimum.py | 2,128 | 3.953125 | 4 | # Time Complexity: O(N)+O(N) =O(N) , N is the total number of nodes in the given tree.
# We visit each node exactly once during dfs and then scan through visited
# Space Complexity: O(N)+O(N) = O(N), for info stored on stack and visited
def findSecondMin(root):
if root is None:
return None
# this is an iterative method to perform depth first search O(N) {level order traversal}
stack = [root]
visited = set()
while stack:
node = stack.pop()
visited.add(node.val)
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
# print(visited)
min_val = root.val
second_min = float('inf')
# cheking the visited set - O(N)
for val in visited:
if min_val < val < second_min:
second_min = val
return second_min if second_min < float('inf') else -1
def findSecondMinOptimumSol(self, root):
self.second_min = float('inf')
min_val = root.val
def traverse(node):
if not node:
return
if min_val < node.val < self.second_min:
self.second_min = node.val
elif node.val == min_val:
traverse(node.left)
traverse(node.right)
traverse(root)
return self.second_min if self.second_min < float('inf') else -1
def findSecondMinOptimumSol_1(root):
"""
Optimum solution without the use of instance variable
Note : In Python 2 you cannot modify references to
variables within functions outside of its scope.
By wrapping the value in a list, it allows modification of
the value without modifying the reference to the list variable.
Hence we have
"""
second_min = [float('inf')]
min_val = root.val
def traverse(node):
if not node:
return
if min_val < node.val < second_min[0]:
second_min[0] = node.val
elif node.val == min_val:
traverse(node.left)
traverse(node.right)
traverse(root)
return second_min[0] if second_min[0] < float('inf') else -1
|
d2dd1371d54bde7afad3259405e38f00b6894005 | w22116972/leetcode_Ender | /520. Detect Capital/520.py | 869 | 3.640625 | 4 | class Solution(object):
def detectCapitalUse(self, word):
case1 = True
case2 = True
case3 = True
lower_case = 'abcdefghijklmnopqrstuvwxyz'
upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if word[0] in upper_case:
case2 = False
for i in range(1, len(word)):
if case1 and word[i] in lower_case:
case1 = False
if case3 and word[i] in upper_case:
case3 = False
if not case1 and not case3:
return False
return case1 or case3
else:
case1 = False
case3 = False
for i in range(1, len(word)):
if word[i] in upper_case:
# case2 = False
return False
return case2 # case2 = True |
9a7fc625754d5f87356d1c95d0440f1a5fed5247 | nurarenke/study | /anagrams_diff_permutations.py | 1,308 | 3.90625 | 4 | '''Cracking the Coding interview, problem 1.3:
Given two strings, write a method to decide if one is a permutation of the other.
Whitespace and punctuation are significant and it is case sensitive.
>>> sorted_anagram("nura", "arun")
True
>>> count_anagram("nura", "arun")
True
>>> sorted_anagram("Burger ", "Burger")
False
>>> count_anagram("Burger ", "Burger")
False
>>> sorted_anagram("RrRr", "rrrr")
False
>>> count_anagram("RrRr", "rrrr")
False
>>> sorted_anagram("Hello World!", "Hello World?")
False
>>> count_anagram("Hello World!", "Hello World?")
False
'''
from collections import Counter
# Option one - sorting first then comparing
def sorted_anagram(s1, s2):
string1 = sorted(s1)
string2 = sorted(s2)
if len(string1) != len(string2):
return False
for indx in xrange(len(string1)):
if string1[indx] != string2[indx]:
return False
return True
#Option two - counting first then comparing
def count_anagram(s1, s2):
dict1 = Counter(s1)
dict2 = Counter(s2)
if len(s1) != len(s2):
return False
if dict1.keys() != dict2.keys():
return False
else:
return True
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. YAY!\n" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.