blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
fd0b2f4db92b53e57857fb01fba022d9bd3e8394
|
larrywork/Data_Analysis
|
/Outlier Detection and Treatment Using Python.py
| 3,027 | 3.796875 | 4 |
#importing libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
#loading the dataset
df=pd.read_csv("all_seasons.csv")
#viewing a snapshot of the dataset
df.head()
print(df.shape) #Getting the number of rows and columns of the dataframe using the "shape command"
df.info()#Getting information about null values and data types using the "info command"
#Creating Box-plots for numeric columns to visually identify outliers
plt.figure(figsize=(18,5))
plt.subplot(1,3,1)
sns.boxplot( y=df["age"] );
plt.subplot(1,3,2)
sns.boxplot( y=df["player_height"] );
plt.subplot(1,3,3)
sns.boxplot( y=df["player_weight"] );
#Creating distribution-plots to bettwr understand the spread of the numeric columns
fig, ax =plt.subplots(1,3, figsize=(18, 7))
sns.histplot(df['age'], kde = True, color ='red', bins = 50, ax=ax[0])
sns.histplot(df['player_height'], kde = True, color ='red', bins = 50, ax=ax[1])
sns.histplot(df['player_weight'], kde = True, color ='red', bins = 50, ax=ax[2])
fig.show()
#Identifying the upper limit for age using IQR
IQR = df.age.quantile(0.75) - df.age.quantile(0.25)
upper_limit = df.age.quantile(0.75) + (IQR * 1.5)
upper_limit
#Printing total number of outliers for the age feature
total = np.float(df.shape[0])
print('Total Players: {}'.format(df.age.shape[0]))
print('Players aged more than 39 years: {}'.format(df[df.age>39].shape[0]))
print('Percentage of players aged more than 39 years: {}'.format(df[df.age>39].shape[0]*100/total))
#Deleting the players that are aged more than the upper limit
df_ageremoved= df[df['age']<39]
df_ageremoved
sns.boxplot( y=df_ageremoved["age"] );
#Identifying upper and lower limit for height
IQR = df.player_height.quantile(0.75) - df.player_height.quantile(0.25)
upper_limit = df.player_height.quantile(0.75) + (IQR * 1.5)
lower_limit = df.player_height.quantile(0.25) - (IQR * 1.5)
print("Upper height limit:"+ str(upper_limit ))
print("Lower height limit:"+ str(lower_limit ))
#Let us cap these outliers at the upper and lower limits and print the box-plot after outlier treatment
df['Height_treated'] = np.where(df['player_height']> 217.28 , 217.28 , df['player_height'])
df['Height_treated'] = np.where(df['Height_treated']< 186.58 , 186.58, df['Height_treated'])
sns.boxplot( y=df["Height_treated"] );
#Identifying upper and lower limit for weight
IQR = df.player_weight.quantile(0.75) - df.player_weight.quantile(0.25)
upper_limit = df.player_weight.quantile(0.75) + (IQR * 1.5)
lower_limit = df.player_weight.quantile(0.25) - (IQR * 1.5)
print("Upper weight limit:"+ str(upper_limit ))
print("Lower weight limit:"+ str(lower_limit ))
#Let us impute these outliers using the mean and print the box-plot after outlier treatment
df['Weight_treated'] = np.where(df['player_weight']> 137.21 , df['player_weight'].mean(), df['player_weight'])
df['Weight_treated'] = np.where(df['Weight_treated']< 62.82 , df['player_weight'].mean(), df['Weight_treated'])
sns.boxplot( y=df["Weight_treated"] );
|
b29d6d6ffbecc6c72760556f32bf4de64af03e07
|
aviruprc/deloittetraining
|
/Python/Backslash/openpyxl/Backslash.openpyxl.py
| 1,703 | 3.609375 | 4 |
#!/usr/bin/env python
# coding: utf-8
# In[38]:
#importing load_workbook and Workbook from openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
#importing the formatting libraries
from openpyxl.styles import Fill,Font,Color,colors
#generating the new excel file
wb3 = Workbook()
wb3.save(filename = 'excel_file_diff.xlsx')
#set file path for the three excel files
filepath1="excel_file_old.xlsx"
filepath2="excel_file_new.xlsx"
filepath3="excel_file_diff.xlsx"
#loading all the excel files
wb1=load_workbook(filepath1)
wb2=load_workbook(filepath2)
#selecting the three excel sheets
sheet1=wb1.active
sheet2=wb2.active
sheet3=wb3.active
#evaluating the maximum rows and columns
max_row1=sheet1.max_row
max_column1=sheet1.max_column
#printing the header of the excel file
for i in range(1,2):
for j in range(1,max_column1+1):
cell_obj1=sheet1.cell(row=i,column=j)
sheet3.cell(row=i, column=j).value = cell_obj1.value
wb3.save(filepath3)
"""comparing cell by cell from the two excel sheets
#and printing the strings as it is and the differences of the values in the 3rd sheet"""
for i in range(2,max_row1+1):
for j in range(1,max_column1+1):
cell_obj1=sheet1.cell(row=i,column=j)
cell_obj2=sheet2.cell(row=i,column=j)
if type(cell_obj1.value) == str and type(cell_obj2.value) == str :
sheet3.cell(row=i, column=j).value = cell_obj1.value
else:
temp=cell_obj1.value-cell_obj2.value
sheet3.cell(row=i, column=j).value = temp
if temp!=0:
sheet3.cell(row=i, column=j).font = Font(color=colors.RED) #formatting here
wb3.save(filepath3)
|
a2cc6b58dae4d80cd0da230e3b25328f3ec5039e
|
dbarattini/ArduPy
|
/examples/temperature_sensor.py
| 530 | 3.5625 | 4 |
from ardupy import *
# arduino connected to port COM5 with baudrate 9600
arduino = Arduino("COM5", debug_mode=YES)
ts = arduino.addTemperatureSensor(A0, lambda voltage : (voltage - .5) * 100) # using a temperature sensor connected to pin A0 (analog)
# explicited a function for voltage to temperature conversion
temperature = ts.getTemperature() # returns the temperature calculated
arduino.closeConnection() # close connection to arduino
|
d5f1d10eae634fd53bbfc993b13b0955ad41d639
|
harammon/Visual_Programming
|
/과제4/dict.py
| 825 | 3.8125 | 4 |
"""
* 파일명 : Dict.py
* 작성일 : 2020년 11월 12일
* 작성자 : 문헌정보학과 20142611 이하람
"""
f = open('dict_test.TXT', 'r')
dictKey = []
dictValue = []
while True:
line = f.readline()
if line == '':
break
line = line[:-1]
s = line.split(':')
s[0] = s[0].rstrip()
s[1] = s[1].lstrip()
dictKey.append(s[0])
dictValue.append(s[1])
myDict = dict(zip(dictKey, dictValue))
while True:
userInput = input("단어? ")
if userInput == '종료':
break
if myDict.get(userInput) == " ":
print(userInput, end = " ")
print(" ")
else:
print(userInput, end = " ")
if myDict.get(userInput) == None:
print("사전에 없는 단어입니다.")
else:
print(myDict.get(userInput))
f.close()
|
995b0fcf52b80a98c8f70ca679dbe8ed3341aa0a
|
inauski/SistGestEmp
|
/Tareas/Act03. Cadenas, For/ejer04/ejer04.py
| 365 | 4.125 | 4 |
print ("Ejer 4")
frase = input("Escribe un correo: ")
if frase.__contains__("gmail.com"):
print ("Termina en gmail.com")
else:
print ("No termina en gmail.com")
print ("Cantidad de '@': %s" % frase.count('@'))
print ("@ esta en: %s" % (frase.index('@')))
print ("Usuario: %s" % (frase.split("@")[0]))
print ("Dominio: %s" % (frase.split("@")[1]))
|
05e2ad3f21f80a3754a74f36f9563b726de91c87
|
daniel-reich/turbo-robot
|
/vuSXW3iEnEQNZXjAP_20.py
| 633 | 4.40625 | 4 |
"""
Create a function that takes a number and returns a string like square.
### Examples
create_square(-1) ➞ ""
create_square(0) ➞ ""
create_square(1) ➞ "#"
create_square(2) ➞ "##\n##"
create_square(3) ➞ "###\n# #\n###"
create_square(4) ➞ "####\n# #\n# #\n####"
"####
# #
# #
####"
### Notes
N/A
"""
def create_square(n):
arr = []
if n==None or n <= 0:
return ''
elif n == 1:
return '#'
else:
arr.append(n*'#')
for i in range(n-2):
arr.append('#'+(' '*(n-2)+ '#'))
arr.append(n*'#')
return '\n'.join(arr)
|
f1ea4298a1ffaa4e6286154c0f05dcb952538679
|
francisco-igor/ifpi-ads-algoritmos2020
|
/semana_5_condicionais/uri_1040_media_3.py
| 775 | 3.6875 | 4 |
def main():
n1, n2, n3, n4 = input().split(' ')
n1 = float(n1)
n2 = float(n2)
n3 = float(n3)
n4 = float(n4)
notas(n1, n2, n3, n4)
def notas(n1, n2, n3, n4):
media = (n1 * 2 + n2 * 3 + n3 * 4 + n4 * 1) / (2 + 3 + 4 + 1)
print('Media: {:.1f}'.format(media))
if media >= 7:
print('Aluno aprovado.')
elif media < 5:
print('Aluno reprovado.')
else:
print('Aluno em exame.')
nota = float(input())
print('Nota do exame: {}'.format(nota))
media_final = (nota + media) / 2
if media_final >= 5:
print('Aluno aprovado.')
else:
print('Aluno reprovado.')
print('Media final: {:.1f}'.format(media_final))
main()
|
2da7031de3f2ab3751a6c1e52c8cb713504de13b
|
koushik-muthesh/python
|
/BST_insert.py
| 617 | 3.90625 | 4 |
class Node:
def __init__(self,data):
self.data=data
self.right=None
self.left=None
def insert(node,data):
if node is None:
return Node(data)
if data<node.data:
node.left=insert(node.left,data)
else:
node.right=insert(node.right,data)
return node
def inorder(root):
if root is not None:
inorder(root.left)
print(root.data)
inorder(root.right)
root=None
n=int(input())
for i in range(n):
a=int(input())
root=insert(root,a)
inorder(root)
|
4681d747d8f2bb01afde9b7420f559734514b8cc
|
porregu/unit7
|
/claswork1.py
| 125 | 3.515625 | 4 |
original = "abcdefghij"
first = original[1:4]
print(first)
last = original[3:11]
print(last)
final = first+last
print(final)
|
c7188563ef6579310fbff9c864e513235507df14
|
theCorvoX3N/Problem-Solving
|
/DivisibleSumPairs.py
| 390 | 3.5 | 4 |
# HackerRank
# - Algorithms > Implementation > Divisible Sum Pairs
# 16/12/17
(n, k) = map(int, input().strip().split(" "))
array = list(map(int, input().strip().split(" ")))
def check(i,j):
if (array[i] + array[j]) % k == 0:
return 1
else:
return 0
total = 0
for i in range(n):
j= i+1
while j<n:
total += check(i, j)
j += 1
print(total)
|
bd2aa5aebc30e28fc2982879e116a601e574ef77
|
Arteche-Angelo/Programming-Examples
|
/Homework_3/Homework_3.py
| 608 | 4.28125 | 4 |
import random
directions =["North","South","East", "West"] #creates the list
int= random.randint(1,4) # makes a random int and stores int as a variable
print(int) #print the int
decision = input("would you like to continue enter 'y' for yes and 'n' for no \n") #ask user and store input
while(decision!="n"): #im assuming the only inputs are going to be "n" or "y"
print("you decided to go "+directions[int-1]) #i subrtracted 1 so that way i dont go out of the list indexs
int= random.randint(1,4)
print(int)
decision = input("would you like to continue enter 'y' for yes and 'n' for no \n")
|
f6bab1ef9fd6140bd7d182eda817a0427a874f27
|
gaurav-gunhawk/Python
|
/PythonPratice/PracticeTuple.py
| 310 | 3.96875 | 4 |
# We can add hetrogeneous elements in the tuple.
# Elements are in the sequential form as inserted in the tuple.
# Use () for tuple defination
# Iteration in tuple is more faster than list.
# User cannot insert or delete the value once declared.
practiceTuple = (21,34,'ref')
print(practiceTuple)
|
ed71877bc614768f1ba7a51e7436106f1a3fa7ac
|
gauravtatke/codetinkering
|
/leetcode/LC14_longest_common_prefix.py
| 1,516 | 3.6875 | 4 |
from __future__ import annotations
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
return longest_common_prefix3(strs)
def longest_common_prefix1(strs: List[str]) -> str:
prefix = ''
if not strs:
return ''
min_len = min([len(s) for s in strs])
total_len = len(strs)
for i in range(min_len):
ch = strs[0][i]
match = True
for s in strs:
if s[i] != ch:
match = False
break
if match:
prefix = prefix + ch
else:
break
return prefix
def longest_common_prefix2(strs: List[str]) -> str:
if not len(strs):
return ''
for i in range(len(strs[0])):
ch = strs[0][i]
for st in strs[1:]:
# either index is more than string length or char does not match
if i >= len(st) or st[i] != ch:
# this also returns empty string if nothing matches
return strs[0][:i]
# when all strings are same
return strs[0]
def longest_common_prefix3(strs: List[str]) -> str:
if not len(strs):
return ''
answer = ''
for index, letter in enumerate(strs[0]):
for st in strs[1:]:
if index >= len(st) or st[index] != letter:
return answer
answer = answer + letter
return answer
if __name__ == '__main__':
sol = longest_common_prefix3(['flower', 'flow', 'flight'])
print(sol)
|
d47baf7139a0a1d46b8627c3838e76583a9513ea
|
hgreen-akl/ProjectEuler
|
/Python/Problem 10.py
| 429 | 3.625 | 4 |
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# This is a very Slow function due to the large amount of processing and memory storage
import sys, os
from tqdm import tqdm
from useful_functions.prime import is_prime
import numpy as np
prime_below_2m = 0
for i in tqdm(range(1,2000000)):
if is_prime(i) == True:
prime_below_2m += i
print(prime_below_2m)
|
a6e9226349a67aa13a855c8a97104afe890602c1
|
Mainnox/bootcamp_python
|
/Day00/ex09/guess.py
| 1,133 | 3.921875 | 4 |
from random import randint
import os
def header():
print("\t*******************************************")
print("\t*** GUESSING GAME ****")
print("\t*******************************************\n")
print("This is an interactive guessing game !")
print("You have to enter a number between 1 and 99 to find out the secret number.")
print("Type 'exit' to end the game.")
print("Good luck!\n")
random = randint(1, 99)
os.system('clear')
header()
temp = 1
while (1):
count = 0
print("What's your guess between 1 and 99?")
put = input()
if not put:
continue
if put == "exit":
exit()
for i in put:
if i.isdigit() == False:
count += 1
if count != 0:
print("Just type a number ffs.")
continue
if int(put) < random:
print("Too low.")
temp += 1
continue
elif int(put) > random:
print("Too big.")
temp += 1
continue
else:
os.system('clear')
print("GG !\nYou find the magic number in " + str(temp) + " attempts.\nYou rock !")
break
|
534fb9c9b7127bc79d47e81fe43ac4ec7c9c6927
|
bulygin69/dijkstra
|
/l3.py
| 2,234 | 3.8125 | 4 |
#!/usr/bin/python
# Листинг №3
# логика: (не существует Х) = (Х ≠ Х)
# (существует Х) = (Х = Х)
A = ('a', 'b', 'c', 'd')
B = ('e', 'c', 'd', 'f')
C = ('g', 'h')
D = ()
#
def set_intersect(set_1, set_2):
si = False
for in1Set in set_1:
for in2Set in set_2:
if in1Set == in2Set:
#in1Set == in2Set - т. е. одно,
# т. е. (существует Х) = (Х = Х) = (одно Х)
#print(set_1, и set_2 пересекаются: ', in1Set, '=', in2Set)
si = True
#else: print('пересечение set_1 и set_2 пусто')
#поскольку (не существовать = нет хотя бы одного)
# (не существовать = не (один или более одного))
if si == True: print(set_1, ' и ', set_2, 'пересекаются')
else: print(set_1, ' и ', set_2, ' не пересекаются')
return si
#
set_intersect(A, B) #True: множества A и В пересекаются по элементам 'c', 'd'
#Имеем (одно или более одного) равенства.
set_intersect(A, C) #False: множества А и С не пересекаются,
#поскольку каждый из элементов множества А
#попарно не равен каждому элементу из множества С.
set_intersect(D, D) #False: пустое множество определяется
#тождественно ложной формулой (противоречием).
#В пустом множестве нет такого элемента X, что X=X.
#Сказать, что в множестве не существует элементов -
#то же, что сказать, что
#каждый элемент Х этого множества такой, что Х≠Х.
|
67e5be5992ae51358e079271d5d879dd587b78f5
|
dheerosaur/leetcode-practice
|
/python/653.two-sum-iv-input-is-a-bst.py
| 3,190 | 3.59375 | 4 |
#
# @lc app=leetcode id=653 lang=python3
# [algorithms] - Easy
#
# [653] Two Sum IV - Input is a BST
# https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
#
# Given a Binary Search Tree and a target number, return true if there exist
# two elements in the BST such that their sum is equal to the given target.
#
# Input:
# 5
# / \
# 3 6
# / \ \
# 2 4 7
#
# Target = 9
#
# Output: True
#
# Input:
# 5
# / \
# 3 6
# / \ \
# 2 4 7
#
# Target = 28
#
# Output: False
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
from ds.bst import TreeNode, constructBST
class Solution:
def findTarget_dfs(self, root: TreeNode, k: int) -> bool:
def find(root):
if root is None:
return False
if root.val in s:
return True
s.add(k - root.val)
return find(root.left) or find(root.right)
s = set()
return find(root)
def findTarget_bfs(self, root: TreeNode, k: int) -> bool:
s = set()
dq = deque([root])
while dq:
node = dq.popleft()
if k - node.val in s:
return True
s.add(node.val)
if node.left:
dq.append(node.left)
if node.right:
dq.append(node.right)
return False
def findTarget_inorder(self, root: TreeNode, k: int) -> bool:
def inorder(root):
if root:
inorder(root.left)
A.append(root.val)
inorder(root.right)
A = []
inorder(root)
left, right = 0, len(A) - 1
while left < right:
total = A[left] + A[right]
if total == k:
return True
elif total > k:
right -= 1
else:
left += 1
return False
def findTarget(self, root: TreeNode, k: int) -> bool:
def get_left(node):
if node.left:
yield from get_left(node.left)
yield node.val
if node.right:
yield from get_left(node.right)
def get_right(node):
if node.right:
yield from get_right(node.right)
yield node.val
if node.left:
yield from get_right(node.left)
lgen, rgen = get_left(root), get_right(root)
val_left, val_right = next(lgen), next(rgen)
while val_left < val_right:
print(val_left, val_right)
total = val_left + val_right
if total < k:
val_left = next(lgen)
elif total > k:
val_right = next(rgen)
else:
return True
return False
def test():
sol = Solution()
cases = [
([5, 3, 6, 2, 4, None, 7], 9),
([5, 3, 6, 2, 4, None, 7], 5),
]
for T, k in cases:
print(sol.findTarget(constructBST(T), k))
if __name__ == '__main__':
test()
|
351ccee7742596996f427ef7a873c3370cb3d259
|
Linzertorte/test
|
/generate.py
| 1,205 | 3.71875 | 4 |
#./generate grammar1 3
import sys
import random
def remove_comment(line):
last = line.find('#')
if last == -1:
return line
else:
return line[0:last]
def insert_rule(grammar, lhs, rhs):
if lhs not in grammar:
rules = []
rules.append(rhs)
grammar[lhs]=rules
else:
grammar[lhs].append(rhs)
def get_grammar(grammar_file):
f = open(grammar_file,'r')
grammar = {}
for line in f:
line = line.rstrip()
line = remove_comment(line)
if len(line)==0:
continue
symbols = line.split()
lhs = symbols[1]
rhs = symbols[2:]
insert_rule(grammar,lhs,rhs)
return grammar
def expand(grammar,symbol):
if symbol not in grammar:
return symbol
rules = grammar[symbol] #get rules
rule = rules[random.randint(0,len(rules)-1)]
sentence = ""
for w in rule:
sentence += expand(grammar,w) + " "
return sentence[0:-1]
if __name__=='__main__':
grammar_file = sys.argv[1]
grammar = get_grammar(grammar_file)
for i in xrange(int(sys.argv[2])):
print expand(grammar,'ROOT')
|
cd3ccfba0fbbd3a96c3da6c06d8a51b6e6f5fe0d
|
HarshaniDil/DataStructure
|
/Stack_using_deque.py
| 306 | 3.796875 | 4 |
from collections import deque
stack = deque()
#To push some elements in to the stack
stack.append('P')
stack.append('I')
stack.append('N')
stack.append('K')
stack.append('I')
print(stack)
#POP
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
|
09ee5254261ac09911484152e84ae08351619c62
|
Fareen14/Python-Projects
|
/Vowel Count.py
| 685 | 4.0625 | 4 |
print("Enter the string whose vowel count you want:\n")
s = input()
i=0
a_count = 0
e_count = 0
i_count = 0
o_count = 0
u_count = 0
for letter in s:
if letter == "a":
a_count += 1
if letter == "e":
e_count += 1
if letter == "i":
i_count += 1
if letter == "o":
o_count += 1
if letter == "u":
u_count += 1
vowel_count = a_count + e_count + i_count + o_count + u_count
print("Total vowel count is: " + str(vowel_count))
print(" 'a' count is: " + str(a_count))
print(" 'e' count is: " + str(e_count))
print(" 'i' count is: " + str(i_count))
print(" 'o' count is: " + str(o_count))
print(" 'u' count is: " + str(u_count))
|
ef9851dd1c8739add9268f3fb1a681e5fcfb2530
|
Jworboys/Learning_Python
|
/learning Python/11_loops/code.py
| 879 | 3.921875 | 4 |
number = 7
''' While loop'''
while True:
user_input = input("Would you like to play? (Y/n)")
if user_input == "n":
break
user_number = int(input("Guess our number: "))
if user_number == number:
print("You guessed correctly!")
elif abs (number - user_number) == 1:
print("You were off by one.")
else:
print("Sorry you guessed wrong!")
'''For loop'''
friends = ["Rolf", "Jen", "Bob", "Anne"]
for friend in friends:
print(f"{friend} is my friend.")
''' Using for loop to add up a sum'''
grades = [35,67,98,100,100]
total = 0
amount = len(grades)
for grade in grades:
total += grade
print(total / amount)
'''Can be done much easier like so, using the sum function'''
grades = [35,67,98,100,100]
total = sum(grades)
amount = len(grades)
print(total / amount)
|
0a162b1fcdf3a3a39cdf2888495eabf555652f9b
|
elsandkls/SNHU_IT140_itty_bitties
|
/regex_extra_practice.py
| 3,935 | 4.46875 | 4 |
#Meta-character Description Example
#. Matches any character except a newline
#^ Matches start of a string
#$ Matches the end of a string
#* Matches 0 or more repititions of the character immediately preceding xy* will match xy, xyyyyy and will match x.
#Note: This is a greedy metacharacter -- it will match as many characters as possible. Maybe more than you want.
#+ Match 1 or more repititions of the character immediately preceding xy+ will match: xy, xyyyyy, but will not match: x
#Note: This is a greedy metacharacter -- it will match as many characters as possible. Maybe more than you want.
#? Match 1 or more repititions of the regular expression xy? will match x and xy.
#Note: This is a greedy metacharacter -- it will match as many characters as possible. Maybe more than you want.
#*?, +?, ?? The non-greedy versions of *, +, and ? Match as few characters as possible.
#{m} Match exactly m copies of the regular expression a{3} will match aaa but not aa, a, or aaaa.
#{m,n} Match exactly m through n copies of the regular expression a{2,4}b will match aab, aaab, aaaab but not ab, a, or aaaaab.
#\ Escapes metacharacters so you can use them in a regular expression \* will match *.
#[] Matches a set of characters [ab] will match: a, b, ab
import re
pattern="[abc]"
a_str="a"
b_str="b"
c_str="c"
ab_str="ab"
bc_str="bc"
abc_str="abc"
xabc_str="xabc"
match1 = re.match(pattern, a_str)
if match1 != None:
print(pattern + " matched " + a_str)
else:
print(pattern + " did not match " + a_str)
match2 = re.match(pattern, b_str)
if match2 != None:
print(pattern + " matched " + b_str)
else:
print(pattern + " did not match " + b_str)
match3 = re.match(pattern, c_str)
if match3 != None:
print(pattern + " matched " + c_str)
else:
print(pattern + " did not match " + c_str)
match4 = re.match(pattern, ab_str)
if match4 != None:
print(pattern + " matched " + ab_str)
else:
print(pattern + " did not match " + ab_str)
match5 = re.match(pattern, bc_str)
if match5 != None:
print(pattern + " matched " + bc_str)
else:
print(pattern + " did not match " + bc_str)
match6 = re.match(pattern, abc_str)
if match6 != None:
print(pattern + " matched " + abc_str)
else:
print(pattern + " did not match " + abc_str)
match7 = re.match(pattern, xabc_str)
if match7 != None:
print(pattern + " matched " + xabc_str)
else:
print(pattern + " did not match " + xabc_str)
import re
pattern='xy*'
str_x='x'
str_xy='xy'
str_xyyyyy='xyyyyy'
m1 = re.match(pattern, str_x)
if m1 != None:
print(pattern + " matched " + str_x)
else:
print(pattern + " did not match " + str_x)
m2 = re.match(pattern, str_xy)
if m2 != None:
print(pattern + " matched " + str_xy)
else:
print(pattern + " did not match " + str_xy)
m3 = re.match(pattern, str_xyyyyy)
if m3 != None:
print(pattern + " matched " + str_xyyyyy)
else:
print(pattern + " did not match " + str_xyyyyy)
import re
pattern='a{3}'
str_a_quad='aaaa'
str_a_tripple='aaa'
str_a_tripple_b='aaab'
str_a_double='aa'
str_a_single='a'
m7 = re.match(pattern, str_a_quad)
if m7 != None:
print("matched %s" % str_a_quad)
else:
print(pattern + " did not match " + str_a_quad)
m8 = re.match(pattern, str_a_tripple)
if m8 != None:
print("matched %s" % str_a_tripple)
else:
print(pattern + " did not match " + str_a_tripple)
m9 = re.match(pattern, str_a_tripple_b)
if m9 != None:
print("matched %s" % str_a_tripple_b)
else:
print(pattern + " did not match " + str_a_tripple_b)
m10 = re.match(pattern, str_a_double)
if m10 != None:
print("matched %s" % str_a_double)
else:
print(pattern + " did not match " + str_a_double)
m11 = re.match(pattern, str_a_single)
if m11 != None:
print(m11.group(0))
else:
print(pattern + " did not match " + str_a_single)
|
9a13d411a318ebcae50b0b8231b00ce4c64bf34a
|
junkhp/atcorder
|
/abc_184_d.py
| 719 | 3.59375 | 4 |
# -*- coding: utf-8 -*-
class CalcMemo:
def __init__(self):
self.memo_dict = {(100, 100, 100): 0}
def calc_e(self, x, y, z):
if x == 100 or y == 100 or z == 100:
return 0
xyz = x + y + z
xyz_tuple = (x, y, z)
if xyz_tuple in self.memo_dict.keys():
return self.memo_dict[xyz_tuple]
self.memo_dict[xyz_tuple] = x/xyz*(self.calc_e(x + 1, y, z) + 1) + \
y/xyz*(self.calc_e(x, y + 1, z) + 1) + z/xyz*(self.calc_e(x, y, z + 1) + 1)
return self.memo_dict[xyz_tuple]
def main():
x, y, z = map(int, input().split())
a = CalcMemo()
print(a.calc_e(x, y, z))
if __name__ == "__main__":
main()
|
97c12337598845bbaded9033d2437d4465594272
|
sdrendall/fishRegistration
|
/usefulTools/xlsxToCsv.py
| 1,257 | 3.5 | 4 |
#!/usr/bin/python
import xlrd
import csv
import argparse
def generate_parser():
parser = argparse.ArgumentParser(
description='Concatenates the sheets from the specified xlsx workbook into a csv file')
parser.add_argument('-x', '--xlsxPath', help='The path to the xlsx file', required=True)
parser.add_argument('-c', '--csvPath', help='The path to the csv output file', required=True)
parser.add_argument('-n', '--numHeaders', type=int, default=0,
help='The number of header rows on each sheet of the xlsx file')
return parser
def get_row_iter(sheet):
for i in xrange(sheet.nrows):
yield sheet.row(i)
def skip_rows(irows, n):
while irows and n > 0:
irows.next()
n -= 1
def unpack_cells(cells):
return [cell.value for cell in cells]
def main():
parser = generate_parser()
args = parser.parse_args()
csv_file = open(args.csvPath, 'w')
csv_writer = csv.writer(csv_file)
book = xlrd.open_workbook(args.xlsxPath)
for sheet in book.sheets():
irows = get_row_iter(sheet)
skip_rows(irows, args.numHeaders)
for cells in irows:
csv_writer.writerow(unpack_cells(cells))
if __name__ == '__main__':
main()
|
af6e0898263feceed4c35e1730eb270abc0488e8
|
ntujvang/holbertonschool-higher_level_programming
|
/0x04-python-more_data_structures/0-square_matrix_simple.py
| 144 | 3.65625 | 4 |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new = []
for i in matrix:
new.append([n * n for n in i])
return new
|
5bd3e77d5701ca9486007351cb633d4c0af46158
|
HLOverflow/school_stuffs
|
/Year3/AI/sudokusolver.py
| 4,539 | 4.0625 | 4 |
__author__ = "Tay Hui Lian"
__doc__ = '''This is sudoku solver I made from my free time after AI exam.
This uses constraint propagation where each move will propagate the
constraints(by removing the number) to other square's searchspace.'''
board = [[] for i in range(9)]
# initialization - note that changes to this board will need to change the asserts statements below.
board[0] = [0,0,9,3,0,6,0,0,8]
board[1] = [8,1,0,5,2,0,0,7,0]
board[2] = [0,5,0,0,8,0,0,2,0]
board[3] = [9,0,3,0,0,0,0,0,0]
board[4] = [0,7,2,9,6,4,3,8,0]
board[5] = [0,0,0,0,0,0,2,0,9]
board[6] = [0,9,0,0,3,0,0,4,0]
board[7] = [0,3,0,0,4,5,0,9,2]
board[8] = [5,0,0,8,0,7,6,0,0]
# initialize searchspace
searchspace = [[[k for k in range(1,10)]for j in range(9)] for i in range(9)]
def removesearchspace(board, searchspace):
for i in range(9):
for j in range(9):
if board[i][j]>0:
searchspace[i][j] = []
def outputboard(board):
print "==== board ===="
for i in range(9):
for j in range(9):
print "%d" %board[i][j],
print
print "==============="
def violatehorizontal(board, r, c, value):
if value in board[r]:
return True
return False
def violatevertical(board, r, c, value):
if value in [board[i][c] for i in range(9)]:
return True
return False
def violate3x3(board, r, c, value):
index_r = (r/3)*3
index_c = (c/3)*3
tmp = []
for i in range(index_r, index_r + 3):
for j in range(index_c, index_c + 3):
tmp.append(board[i][j])
if value in tmp:
return True
return False
def removefromsearchspace(lst, toremove):
for i in toremove:
lst.remove(i)
def outputsearchspace(searchspace):
print "=== searchspace ==="
for i in range(9):
for j in range(9):
print "(%d, %d):" % (i, j), searchspace[i][j]
print "=== searchspace ==="
def propagateconstraint(searchspace, r, c, value):
for i in range(9):
try:
searchspace[i][c].remove(value) # remove from verticals
except ValueError:
pass
try:
searchspace[r][i].remove(value) # remove from horizontals
except ValueError:
pass
index_r = (r/3)*3
index_c = (c/3)*3
for i in range(index_r, index_r + 3):
for j in range(index_c, index_c + 3):
try:
searchspace[i][j].remove(value) # remove from 3x3 grid.
except ValueError:
pass
#outputboard(board)
removesearchspace(board, searchspace)
# unit testing of functions
assert violatehorizontal(board, 0, 7, 9) == True
assert violatehorizontal(board, 1, 5, 9) == False
assert violatevertical(board, 5, 2, 9) == True
assert violatevertical(board, 1, 5, 9) == False
assert violate3x3(board, 1, 2, 5) == True
assert violate3x3(board, 1, 2, 6) == False
# first level search (will reduce the search space a lot).
for i in range(9):
for j in range(9):
if searchspace[i][j]:
toremove = [] # cannot remove while enumerating. probably due to race condition.
for possible in searchspace[i][j]:
if violatehorizontal(board, i, j, possible) or violatevertical(board, i, j, possible) or violate3x3(board, i, j, possible):
toremove.append(possible)
removefromsearchspace(searchspace[i][j], toremove) # eliminate violated - remove in 1 shot
toremove = []
assert searchspace[0][0] == [2,4,7]
assert searchspace[0][4] == [1,7]
outputboard(board)
def writeanswer():
for i in range(9):
for j in range(9):
if len(searchspace[i][j]) == 1: # the only possible answer
value = searchspace[i][j][0]
print "confirmed:", (i, j), "=", value
board[i][j] = value
propagateconstraint(searchspace, i, j, value)
return None
#outputsearchspace(searchspace)
writeanswer()
outputboard(board)
assert board[1][5] == 9
#outputsearchspace(searchspace)
count = 1
def endgame(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return False
return True
while(not endgame(board)):
writeanswer()
outputboard(board)
count+=1
print "end game"
print count
|
c3c7bb7075a34bf3a31bcacc7b6f5fbf9859e1c2
|
DeshanHarshana/Python-Files
|
/pythonfile/New folder/listexample.py
| 512 | 3.65625 | 4 |
lt=[]
def command(lst):
if lst[0] == 'insert':
lt.insert(int(lst[1]), int(lst[2]))
elif lst[0] == 'remove':
lt.remove(int(lst[1]))
elif lst[0] == 'append':
lt.append(int(lst[1]))
elif lst[0] == 'sort':
lt.sort()
elif lst[0] == 'print':
print(lt)
elif lst[0] == 'pop':
lt.pop()
elif lst[0] == 'reverse':
lt.reverse()
count=int(input())
print(count)
for i in range(count):
inputvalue=input().split()
command(inputvalue)
|
e447647beb8a1ecc8275e79de33ad37e7fa73c3f
|
omurovec/COSC-marking-tool
|
/export-to-eclipse.py
| 3,620 | 3.5 | 4 |
import csv
from pathlib import Path
from zipfile import ZipFile
import os
import shutil
PACKAGE_PATH = "P:/PATH/TO/PROJECT/SRC/"
GRADEBOOK_CSV_PATH = "P:/PATH/TO/CSV.csv"
LAB_SECTIONS = ["L2M", "L2N"]
SUBMISSIONS_PATH = "Submissions.zip"
# Add/replace package name in java file
def correct_package(filepath, package_name):
try:
lines = open(filepath).read().splitlines()
no_package_name = True
# Search first 5 lines for a package statement
if len(lines) > 5:
for i in range(5):
if "package " in lines[i]:
# Replace package import line
print(f"Package Name changed to {package_name}")
lines[i] = "package " + package_name + ";\n"
no_package_name = False
if no_package_name:
# Add package import line
print(f"Added Package Name {package_name}")
lines = ["package " + package_name + ";\n"] + lines
# Re-write file with new package name
open(filepath, "w").write('\n'.join(lines))
except:
print(f"Error reading file: {filepath}")
# Returns list of Java files in the folder
def search_java(zip):
files = []
for filename in zip.namelist():
if ".java" in filename:
files.append(filename)
return files
# Extract and move to eclipse
def extract_move(ID, assign_name, section, zip):
print(
f"\n\nFile: {ID}\nAssignment: {assign_name}\nSection: {section}\n_________________\n")
# Create project folder
project_path = PACKAGE_PATH+assign_name+"/"+section+"/"+ID
if not os.path.exists(PACKAGE_PATH+assign_name):
os.mkdir(PACKAGE_PATH+assign_name)
if not os.path.exists(PACKAGE_PATH+assign_name+"/"+section):
os.mkdir(PACKAGE_PATH+assign_name+"/"+section)
if not os.path.exists(PACKAGE_PATH+assign_name+"/"+section+"/"+ID):
os.mkdir(PACKAGE_PATH+assign_name+"/"+section+"/"+ID)
# Extract Java files and move to project folder
for javafile in search_java(zip):
try:
zip.extract(javafile, project_path)
try:
# Move to project folder
os.rename(project_path+"/"+javafile, project_path +
"/"+os.path.basename(javafile))
except:
print(f"File {javafile} already processed.")
except:
print(f"Skipping BAD ZIP")
# Delete non-Java files
for path in os.listdir(project_path):
if os.path.isdir(project_path+'/'+path):
shutil.rmtree(project_path+"/"+path)
else:
correct_package(project_path+"/"+path,
f"{assign_name}.{section}.{ID}")
# Extract download from canvas
with ZipFile(SUBMISSIONS_PATH, 'r') as zip:
zip.extractall()
for lab_section in LAB_SECTIONS:
# Read IDs from csv
id_list = []
with open(GRADEBOOK_CSV_PATH, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
count = 0
for row in csv_reader:
if count == 0:
count += 1
elif row["Lab"] == lab_section:
id_list.append(row["Student Number"])
count += 1
for filename in os.listdir("./"):
for ID in id_list:
if ID in filename:
try:
extract_move("ID_" + ID, os.path.basename(
os.path.abspath("")), lab_section, ZipFile(filename))
except:
print(f"Error unzipping bad zip: {filename}")
|
e9ed3ba43cc25e6c4191ee34a064b68108f59c79
|
sushantao/neosphere-exercises
|
/day6/funcUse.py
| 200 | 3.984375 | 4 |
def multiplyMe(x):
y = x * x
return y
r=multiplyMe(2)
print(r)
def multiplyMe1(x):
'''
This function returns a square.
'''
y = x * x
return y
print(help(multiplyMe1))
|
bf1c7c9e226cecb6eb887d292d029788ce520673
|
DanielMoscardini-zz/python
|
/pythonProject/Curso Em Video Python/Mundo 1/ex026.py
| 468 | 4.0625 | 4 |
"""
Faça um software que leia uma frase pelo teclado e mostre:
>Quantas vezes aparece a letra "a"
>Em que posição ela aparece a primeira vez
>Em que posição ela aparece a ultima vez
"""
frase = str(input('Digite uma frase: ')).strip().lower()
print(f'A letra "a" apareceu: {frase.count("a")} vezes\n'
f'A letra "a" apareceu a primeira vez na {frase.find("a")+1}º posição\n'
f'A letra "a" apareceu a ultima vez na {frase.rfind("a")+1}º posição.')
|
98e71a71e0ad7a6dc050c14aa335d9f2f08c3453
|
NickJJFisher/DigitalSolutions2020
|
/Chapter5/PaintJob.py
| 455 | 3.828125 | 4 |
Amount = int(input("How much in feet are you painting?"))
Cost = int(input("How much for a gallon of paint?"))
Paint = (Amount / 112)
print (Paint, "Galloons of paint is required")
Hours = (Paint / 8)
print (Hours, "hours of labour is required")
PaintCost = Paint * Cost
print (PaintCost, "dollars is required for the paint")
LabourCost = Hours * 35
print (LabourCost, "Dollars is required for labour")
print (PaintCost + LabourCost, " Is the total Cost")
|
1f7a3e0609e7fae1e17d41c09bd66131fe99d3fd
|
sbaldrich/udacity
|
/ud120/svm/svm_author_id.py
| 1,778 | 3.625 | 4 |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
#clf = SVC(kernel = "linear") Train using 1% of the data and an rbf kernel
# Toss out 99% of the data
#features_train = features_train[:len(features_train)/100]
#labels_train = labels_train[:len(labels_train)/100]
# Find the optimal value for C
#for c in [10, 100, 1000, 10000]:
for c in [10000]: # only use C = 10000 b/c it was found to be its optimal value
clf = SVC(kernel = "rbf", C = c)
t0 = time()
clf.fit(features_train, labels_train)
print "Training time for SVM with C = %.1f is: %.3f" % (c, round(time() - t0, 3))
t0 = time()
pred = clf.predict(features_test)
print "Prediction time for SVM is with C = %.1f is: %.3f" % (c, round(time() - t0, 3))
print "The score of the SVM model with C = %.1f is: %.3f" % (c, accuracy_score(pred, labels_test))
print "Predictions for elements(10, 26, 50) = (%d, %d, %d)" % (pred[10], pred[26], pred[50])
print "Number of events predicted as being on Chris(1) class: %d" % (len([x for x in pred if x]))
#########################################################
|
219f1b0a470b1f24234096bb5552f90d6c3b8eba
|
1144063098/python_source
|
/python_oop/file2.py
| 125 | 3.9375 | 4 |
a={"name":"张三","age":18,"addr":"长沙"}
s={k:v for k,v in a.items() if k=="age" or k=="addr"}
print(a.get("named",18))
|
e6ba8174109e67cf82093e7e0dd616e673418595
|
huangxiaoxin-hxx/javascript_fullstack
|
/leetcode/candies/a.py
| 260 | 3.5 | 4 |
from typing import List
class Solution:
def distributeCandies(self, candies:List[int]) -> int:
# min 函数式 内置函数
return min(len(candies)>>1, len(set(candies)))
x = Solution()
print("最大的种类数",x.distributeCandies([1,1,2,2,3,3]))
|
092c80df82022a827edf999d92b29ea2a0a25e39
|
gioliveirass/atividades-pythonParaZumbis
|
/Lista de Exercicios IV/Ex02.py
| 290 | 3.796875 | 4 |
# Exercicio 02
print('Exercicio 02')
import random
num, impares, pares = [], [], []
num = random.sample(range(100), 20)
for x in num:
if x%2 == 0:
pares.append(x)
else:
impares.append(x)
print(f'Números: {num}')
print(f'Impares: {impares}')
print(f'Pares: {pares}')
|
6e609e851af5edd4a5db63cfc72ab93ef84beceb
|
guimunarolo/studies
|
/data_structures/stack/balanced_symbols_string.py
| 426 | 3.671875 | 4 |
from . import Stack
SYMBOLS_PAIRS = {"(": ")", "[": "]", "{": "}"}
def is_balanced(symbols_string):
openers = SYMBOLS_PAIRS.keys()
my_stack = Stack()
for symbol in symbols_string:
if symbol in openers:
my_stack.push(symbol)
continue
last_opened = my_stack.pop()
if symbol != SYMBOLS_PAIRS[last_opened]:
return False
return my_stack.is_empty()
|
cf0d8096278dd7847101c2c590e31b966910d3ad
|
toolbox-and-snippets/Toolbox-Python
|
/src/lists.py
| 3,083 | 4.21875 | 4 |
### Lists ###
# List of Lists #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
# Create 2-dimensional matrix
lst_2d = [[0] * 3 for i in xrange(3)]
print lst_2d
# Assign a value within the matrix
lst_2d[0][0] = 5
print lst_2d
# Enumerate #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
# Allows you to have access to the indexes of the elements within a for loop
l = ['a', 'b', 'c', 'd', 'e', 'f']
for (index, value) in enumerate(l):
print index, value
# Transpose an iterable #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
a = [[1, 2, 3], [4, 5, 6]]
print zip(*a)
# Same with dicts
d = {"a":1, "b":2, "c":3}
print zip(*d.iteritems())
# Flatten a list of lists #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
lol = [['a', 'b'], ['c'], ['d', 'e', 'f']]
for outer in lol:
for inner in outer:
print inner
# Find out if line is empty #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
line = ""
if not line.strip():
print 'empty'
# Remove duplicates from a List #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
L = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print list(set(L))
# Get integers from a string (space seperated) #
# https://stackoverflow.com/questions/691946/short-and-useful-python-snippets
S = "1 2 2 3 3 3 4 4 4 4"
print [int(x) for x in S.split()]
# # Create an n-dimensional array ##
# https://gist.github.com/alexholehouse/6190193#file-gistfile1-py
# Main function to call
# typeOfitem
# Should be a class which can generate objects
# e.g. float, int, complex, or any other type, such as
# myCoolClass
#
# dimensions
# value for a 1D array, or a list or tuple defining the
# dimensions, for higher order arrays. e.g. a 3D array
# might be [2,3,4]
#
def nDarray(typeOfitem, dimensions):
depth = 0
if type(dimensions) == int:
dimensions = [dimensions]
return(recursiveAllocator(typeOfitem, dimensions, depth))
# Recursive internal function
def recursiveAllocator(basetype, dimensionList, depth):
# Base case
if depth == len(dimensionList) - 1:
currentDimension = dimensionList[depth]
array = []
for i in xrange(0, currentDimension):
array.append(basetype())
return array
# Recursive case
else:
array = []
currentDimension = dimensionList[depth]
# for each element in each dimension recursively
# call the function
for i in xrange(0, currentDimension):
array.append(recursiveAllocator(basetype, dimensionList, depth + 1))
return array
# Split a list into evenly sized chunks
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
l = range(1, 1000)
def chunks(l, n):
# Yield successive n-sized chunks from l
for i in xrange(0, len(l), n):
yield l[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
|
d8ab5ec281b21f17f17008519ef108f37d918e16
|
kimje0322/Algorithm
|
/기타/0226/Queue.py
| 168 | 3.640625 | 4 |
def enqueue(n):
global rear
if rear == len(queue)-1:
print('full')
else:
rear += 1
queue[rear] = n
queue = [0]*3
front = rear = -1
|
7a2b5a841817f4daa80a4679c648bbf5552765d8
|
Abishek1608/Problem-solvjng
|
/greater 3 no.py
| 230 | 4.21875 | 4 |
n1=int(input('enter the value'))
n2=int(input('enter the value'))
n3=int(input('enter the value'))
if(n1>n2 and n1>n3):
print('n1 is greater')
elif(n2>n3 and n2>n1):
print('n2 is greater')
else:
print('n3 is greater')
|
0192d036de02c0f0fb50947fd496767a69b0ad79
|
claudiayunyun/yunyun_hackerrank
|
/python/SwapCase.py
| 596 | 4.125 | 4 |
# lambda expression
##syntax : lambda arguments : expression
# map function
# map(function, iterables)
# function Required. The function to execute for each item
# iterable Required. A sequence, collection or an iterator object.
# You can send as many iterables as you like,
# just make sure the function has one parameter for each iterable.
def swap_case(s):
result = map(lambda char: char.upper() if char.islower() else char.lower(), list(s))
return ''.join(list(result))
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
e055fa59e7f2d6ed3bb871394dba58a69f37eeb2
|
moskalikbogdan/CDV
|
/Python/Warsztaty/Week02/W02.Z05.2.py
| 476 | 3.703125 | 4 |
"""
@author: Bogdan Moskalik,
DataScience,
Niestacjonarne,
Grupa 2
"""
n = int(input("Prosze podac liczbe: "))
def silnia_rek(n):
if n>1:
return n*silnia_rek(n-1)
elif n in (0,1):
return 1;
def silnia_iter(n):
silnia=1
if n in (0,1):
return 1
else:
for i in range(2,n+1):
silnia = silnia*i
return silnia
print ('silnia rekurencyjnie', silnia_rek(n))
print ('silnia iteracyjnie', silnia_iter(n))
|
1cf3d2df6666254381eec65f8a731dd49ec4d13b
|
StephenAjayi/learning_py1
|
/connected_caves.py
| 1,079 | 3.8125 | 4 |
from random import choice
# setup caves
cave_numbers = range(0,20)
caves = []
for i in cave_numbers:
caves.append([])
unvisited_caves = range(0,20)
visited_caves = [0]
unvisited_caves.remove(0)
while unvisited_caves != []:
i = choice(visited_caves)
print len(caves[i])
if len(caves[i]) >= 3:
continue
next_cave = choice(unvisited_caves)
caves[i].append(next_cave)
caves[next_cave].append(i)
visited_caves.append(next_cave)
unvisited_caves.remove(next_cave)
for number in cave_numbers:
print number, ":", caves[number]
print '____________'
for i in cave_numbers:
while len(caves[i]) < 3:
passage_to = choice(cave_numbers)
# if len(caves[passage_to]) >= 3:
# continue
# if passage_to == i:
# random_cave = choice(caves)
# random_tunnel_choice = choice(range(0,2))
caves[i].append(passage_to)
# caves[passage_to].append(i)
for number in cave_numbers:
print number, ":", caves[number]
print '____________'
|
5bcf516cb1dbd462a296dd2861e7485e38a436ba
|
InduprasadSR/PythonFunFacts
|
/Fact_2.py
| 131 | 4.21875 | 4 |
#Palindrome
SomeString = 'MALAYALAM'
print("Palindrome!") if SomeString == SomeString[::-1] else print("Not a palindrome!")
|
cce31d4661c35965d2aa0cfa09da8d91b0d09bcf
|
gerosantacruz/Python
|
/criptrography/transpositionDecrypt.py
| 1,418 | 4.1875 | 4 |
# Transposition Cipher Decryption
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import math, pyperclip
def main():
message = input('Enter the message to decrypt \n')
key = int(input('Please enter the key: \n'))
plain_text = decrypt_message(key, message)
print(plain_text + '|')
def decrypt_message(key, message):
#the numbers of columns in our transposition grid:
num_of_columns = int(math.ceil(len(message)/float(key)))
num_of_rows = key
#the number of shaded boxes in the last column of the grid:
num_shades_boxes = (num_of_columns * num_of_rows) - len(message)
#each strin in the plaintext represents a column in the grid:
plain_text = [''] * num_of_columns
#the column and row variables point to where in the grid the next
#character in the encrypted message will go
column = 0
row = 0
for symbol in message:
plain_text[column] += symbol
column += 1 #point to the next column
#if there are no more columns or we are at shade box
#go back to the first column and the next row
if(column == num_of_columns) or (column == num_of_columns -1 and
row >= num_of_rows - num_shades_boxes):
column = 0
row += 1
return ''.join(plain_text)
""" if decrypt is run(inste of imported as module)
call the main function """
if __name__ == '__main__':
main()
|
8ea75cb1b5dad651cf7ac45ee8f17ac2a52e4698
|
andreas-anhaeuser/py_utils_igmk
|
/test/test_translation.py
| 1,182 | 3.546875 | 4 |
#!/usr/bin/python3
"""Testing suite for translation module."""
import unittest
from misc.translation import translate
class Translation(unittest.TestCase):
def setUp(self):
self.filename = 'test_files/dictionary.txt'
self.kwargs = {}
def test_regular(self):
self.term = 'Brot'
self.expected = 'bread'
def test_case_sensitive(self):
self.term = 'brot'
self.expected = 'bread'
self.kwargs['ignore_case'] = True
def test_list(self):
self.term = 'Bank'
self.expected = ['bench', 'bank']
def test_commas(self):
self.term = 'wieso, weshalb, warum'
self.expected = ['why, why, why', 'Why']
def tearDown(self):
expected = self.expected
result = translate(self.term, filename=self.filename, **self.kwargs)
if not isinstance(result, list):
self.assertEqual(result, expected)
else:
Nres = len(result)
Nexp = len(expected)
self.assertEqual(Nres, Nexp)
for n in range(Nres):
self.assertEqual(result[n], expected[n])
if __name__ == '__main__':
unittest.main()
|
fe5889e234696b7fc2904a9d13fb755b8fc1514b
|
jayanti-prasad/ml-algorithms
|
/raw/kmeans_example.py
| 4,357 | 3.59375 | 4 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import argparse
np.random.seed (seed=292)
"""
This program is a full demo of K-means clustering without using any library.
Comments & Feedback:
- Jayanti Prasad Ph.D [[email protected]]
"""
def get_data ():
"""
Create two dimensional data for clustering.
Change the parameters if you wish, I have put two Gaussians.
"""
cov = [[1, 0], [0, 1]]
X1 = np.random.multivariate_normal([0,1], cov, 100)
X2 = np.random.multivariate_normal([4,4], cov, 100)
X = np.concatenate((X1, X2), axis=0, out=None)
df = pd.DataFrame(columns=['x','y'])
df['x'] = X[:,0]
df['y'] = X[:,1]
return df.sample(frac=1)
def get_centeroid (df, num_clusters,columns):
"""
At every iteration we need to compute the centerioids of the clusters.
"""
centers = np.zeros([num_clusters, len(columns)])
for i in range(0, num_clusters):
df1 = df [df['cid'] == float(i)][columns].copy()
for j in range (0, len(columns)):
if df1.shape[0] > 0:
centers[i,j] = df1[columns[j]].mean()
return centers
def assign(df, centers):
"""
At every iteration we assign points to clusters on the basis of their
proximity.
"""
cid = np.random.randint(centers.shape[0],size=[df.shape[0]])
for i in range (0, df.shape[0]):
dc = np.zeros ([centers.shape[0]])
for j in range (0, centers.shape[0]):
pos = np.array([df.iloc[i]['x'],df.iloc[i]['y']])
dc[j] = np.linalg.norm (pos - centers[j,:])
cid[i] = np.argmin (dc)
df['cid'] = cid
return df
def get_dispersion(df, centers,columns):
"""
A measure of the goodness of clustering. You may need to
modify it. Here I mostly depend on the visual impression.
"""
ss = 0.0
for i in range (0, centers.shape[0]):
df1 = df [df['cid'] == float(i)][columns].copy()
for j in range (0, len(columns)):
df1[columns[j]] = df1[columns[j]] - centers[i,j]
ss += df1[columns[j]].var()
return ss
class Kmeans:
"""
This the K-mean modulel
"""
def __init__(self, num_clusters, ndim):
self.num_clusters = num_clusters
self.centers = np.zeros ([num_clusters,ndim])
def fit (self, df, num_epochs):
df['cid'] = np.random.randint(int(self.num_clusters),size=[len(df)])
centers = np.random.randint(df.shape[0]-1,size=[self.num_clusters])
for i in range(0, self.num_clusters):
self.centers[i,:] = np.array([df.iloc[i]['x'],df.iloc[i]['y']])
for i in range (0, num_epochs):
df = assign(df, self.centers)
self.centers = get_centeroid (df, self.num_clusters,['x','y'])
ss = get_dispersion(df, self.centers,['x','y'])
print(i, ss)
return df,ss
def predict (self, df):
return assign(df, self.centers)
def plot_data (df_train,df_test,columns,centers):
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(121)
bx = fig.add_subplot(122)
ax.set_title('Original data')
bx.set_title('Clustered data with num cluster= ' + str(centers.shape[0]))
ax.scatter(df_train['x'],df_train['y'])
for i in range(0, centers.shape[0]):
df1 = df_train [df_train['cid'] == float(i)][columns].copy()
df2 = df_test [df_test['cid'] == float(i)][columns].copy()
bx.scatter(df1['x'],df1['y'],label='Train [class:' + str(i) +']' )
bx.scatter(df2['x'],df2['y'],marker='+',label='Test [class:' + str(i) + ']')
bx.scatter(centers[:,0],centers[:,1],c='k',marker="x",label='Centeroids')
bx.legend()
plt.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-n','--num-epochs',type=int,help='Number of epochs',default=10)
parser.add_argument('-c','--num-clusters',type=int,help='Number of clusters',default=2)
args = parser.parse_args()
df = get_data()
df_train = df.iloc[:int(0.8*df.shape[0])]
df_test = df.iloc[int(0.8*df.shape[0]):]
print(df_train.shape, df_test.shape)
KM = Kmeans (args.num_clusters,df_train.shape[1])
df_train,ss = KM.fit(df_train,args.num_epochs)
df_test = KM.predict(df_test)
plot_data (df_train,df_test,['x','y'],KM.centers)
|
6aadec8764ddc87e34ffeabc2ce27ffd30a901bc
|
XidongHuang/PythonStudy
|
/projects/ex48/ex48/lexicon.py
| 1,042 | 3.59375 | 4 |
"""*************************************************************************
> File Name: lexicon.py
> Author: XidongHuang (Tony)
> Mail: [email protected]
> Created Time: Wed 12 Oct 20:53:48 2016
************************************************************************"""
# -*- coding: utf-8 -*-
#!/usr/bin/env python3.5
direction=['north', 'south','east']
verb = ['go', 'kill', 'eat']
stop = ['the', 'in', 'of']
nouns = ['bear', 'princess']
number = range(999999)
vocabulary={'direction': direction, 'noun': nouns, 'verb': verb, 'stop': stop, 'number': number}
def scan(sentence):
words = sentence.split()
result = []
for word in words:
found = False
for key,value in vocabulary.items():
if word.lower() in value:
result.append((key, word))
found = True
break
if not found:
try:
for key, value in vocabulary.items():
num_word = int(word)
if num_word in value:
result.append((key, num_word))
break
except ValueError:
result.append(('error', word))
return result
|
8f70ae2e8eceed564e916e54843eeb1747193b41
|
arifkhan1990/Competitive-Programming
|
/Data Structure/Linked list/Circular Linked List/practice/Spoj/CLSLDR_Class_Leader.py
| 2,769 | 3.671875 | 4 |
# Name : Arif Khan
# Judge: SPOJ
# University: Primeasia University
# problem: CLSLDR - Class Leader
# Difficulty: Easy
# Problem Link: https://www.spoj.com/problems/CLSLDR/
#
# this solution is give TLE
from typing import Any
class Node:
def __init__(self, data: Any):
self.data = data
self.next = None
class ListNode:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node.data
if node == self.head:
break
def __repr__(self):
return "->".join(str(item) for item in iter(self))
def __len__(self):
return len(tuple(iter(self)))
def insert(self, data: Any, index: int) -> None:
if index < 0 and index > len(self):
return
node = Node(data)
if self.head is None:
node.next = node
self.head = self.tail = node
elif index == 0:
node.next = self.head
self.head = self.tail = node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
node.next = temp.next
temp.next = node
if index == len(self) - 1:
self.tail = node
def delete(self, index: int):
if not 0 <= index < len(self):
return
if self.head == self.tail:
self.head = self.tail = None
elif index == 0:
self.tail.next - self.tail.next.next
self.head = self.head.next
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
temp.next = temp.next.next
if index == len(self) - 1:
self.tail = temp
def delete_node(self, idx1: int, idx2: int):
curr = None
del_node = self.head
i = 1
while del_node != curr:
if i < idx1:
del_node = del_node.next
else:
j = 1
while j < idx2:
del_node = del_node.next
if j == idx2-1:
curr = del_node.next
del_node.next = curr.next
j += 1
i += 1
print(del_node.data)
def print_list(self):
print(self)
if __name__ == "__main__":
tc = int(input())
for _ in range(tc):
n, m, o = map(int, input().split())
node = ListNode()
for i in range(1, n+1):
node.insert(i, i-1)
node.delete_node(m, o)
|
6a28792808879b45b8ea333c713b40afcc714bdd
|
dorabelme/Learn-Python-3-the-Hard-Way
|
/ex6.py
| 750 | 4.03125 | 4 |
# types of people
types_of_people = 10
x = f"There are {types_of_people} types of people."
# variable called binary
binary = "binary"
# variable don't
do_not = "don't"
# there are people who know binary and who don't
y = f"Those who know {binary} and those who {do_not}."
# printing x and y statements
print(x)
print(y)
# printing string with x
print(f"I said: {x}.")
# printing string with y
print(f"I also said: {y}.")
# variable hilarious
hilarious = False
# variable
joke_evaluation = "Isn't that joke so funny?! {}"
# printing two above variables
print(joke_evaluation.format(hilarious))
# string called w
w = "This is the left side of..."
# string called e
e = "a string with a right side."
# printing two strings together
print(w + e)
|
5df0461bc7bc0cc5fbc298e0983bc38b70187c64
|
jdukosse/LOI_Python_course-SourceCode
|
/Chap12/riskyread.py
| 165 | 3.59375 | 4 |
# Sum the values in a text file containing integer values
sum = 0
f = open('mydata.dat')
for line in f:
sum += int(line)
f.close() # Close the file
print(sum)
|
a84baa95dcf9dae9b229c0bbb568578cf4dc68c9
|
JankaGramofonomanka/numbering_patterns
|
/pckg/source/linear_formula.py
| 28,309 | 3.78125 | 4 |
from . import misc
class LinearFormula():
"""A class to represent a linear formula (a first degree polynomial)"""
#-INIT--------------------------------------------------------------------
def __init__(self, *args):
"""Initializes the formula"""
self.multipliers = []
self.variables = []
# for example if the formula is 'a + 4b - 3c' then we should get
# <self.multipliers> == [1, 4, -3 ]
# <self.variables> == ['a', 'b', 'c']
if len(args) == 1:
arg = args[0]
# init with <LinearFormula>
if type(arg) == LinearFormula:
self.multipliers = arg.multipliers.copy()
self.variables = arg.variables.copy()
# init with string
elif type(arg) == str:
self.read_from_string(arg)
# init with dict
elif type(arg) == dict:
for variable, multiplier in arg.items():
self.variables.append(variable)
self.multipliers.append(int(multiplier))
# init with something convertible to an integer
else:
try:
self.multipliers.append(int(arg))
self.variables.append('')
except ValueError:
raise ValueError(f'invalid argument: {arg}')
except TypeError:
raise TypeError(f'invalid argument: {arg}')
# init with lists
elif len(args) == 2 and type(args[0]) == type(args[1]) == list:
if len(args[0]) != len(args[1]):
raise ValueError("""lists of multipliers and variables must
have the same length""")
else:
self.multipliers = args[0].copy()
self.variables = args[1].copy()
elif len(args) == 2:
raise TypeError('arguments have to be lists')
else:
raise TypeError('the constructor takes at most 2 arguments')
#-------------------------------------------------------------------------
#-STRING-TO-FORMULA-CONVERSION--------------------------------------------
def read_from_string(self, string):
"""Converts a string into a formula"""
# I assume that <string> is made of substrings like this:
# operator, multiplier, variable, operator, multiplier, variable, ...
# where some of the substrings can be empty
# the algorithm in essence works like this:
# 1. read operator
# 2. read multiplier
# 3. read variable
# 4. add segment
# 5. go back to point 1. if the string hasn't ended
# set up temporary data
self._setup_read_from_string()
for char in string:
self._process(char)
# this will add the last segment
self._process(' ')
self._tear_down_read_from_string()
def _setup_read_from_string(self):
"""Sets up memory for the <read_from_string> function"""
self._current_operation = None
self._current_multiplier = None
self._current_variable = None
self._phase = 'operation'
def _tear_down_read_from_string(self):
"""Deletes memory used by the <read_from_string> function"""
del self._current_operation
del self._current_multiplier
del self._current_variable
del self._phase
def _process(self, char):
"""Choses the processing algorithm based on which phase the main
algorithm is in"""
if self._phase == 'operation':
self._process_operation(char)
elif self._phase == 'multiplier':
self._process_multiplier(char)
elif self._phase == 'variable':
self._process_variable(char)
# the 3 methods below:
# <_process_operation>, <_process_multiplier>, <_process_variable>
# work like this:
# if <char> is "supported":
# do stuff
# else:
# clean up
# go to the next phase
# pass <char> to the next _process_whatever method
def _process_operation(self, char):
"""Processes <char> given that <char> is part of an operation
(+ or -)"""
if char == ' ':
# in the middle of a string a space does not tell us anything
# also this prevents from going in circles when a space occurs
# after a variable name
pass
elif LinearFormula._type_of_char(char) == 'operator':
if char == '+':
self._current_operation = '+'
elif char == '-':
self._current_operation = '-'
else:
raise ValueError(f'invalid operation - {char}')
else:
# clean up
if self._current_operation is None:
self._current_operation = '+'
# next phase
self._phase = 'multiplier'
self._process_multiplier(char)
def _process_multiplier(self, char):
"""Processes <char> given that <char> is part of a number"""
if LinearFormula._type_of_char(char) == 'number':
if self._current_multiplier is None:
self._current_multiplier = int(char)
else:
self._current_multiplier *= 10
self._current_multiplier += int(char)
else:
# clean up
if self._current_multiplier is None:
self._current_multiplier = 1
if self._current_operation == '-':
self._current_multiplier *= -1
# next phase
self._phase = 'variable'
self._process_variable(char)
def _process_variable(self, char):
"""Processes <char> given that <char> is part of a variable name"""
if LinearFormula._type_of_char(char) in {'char', 'number'}:
# the first character of the variable name has to pass through
# the <self._process_number> method so it won't be a number
if self._current_variable is None:
self._current_variable = char
else:
self._current_variable += char
else:
# clean up
if self._current_variable is None:
self._current_variable = ''
# add segment (part of clean up)
self.multipliers.append(self._current_multiplier)
self.variables.append(self._current_variable)
# reset temporary data and go to the next phase
self._setup_read_from_string()
self._process_operation(char)
@classmethod
def _type_of_char(cls, char):
"""Tells whether <char> is a number, space, operator or a regular
character"""
try:
int(char)
return 'number'
except ValueError:
if char == ' ':
return 'space'
elif char in {'+', '-'}:
return 'operator'
else:
return 'char'
#-------------------------------------------------------------------------
#-MAGIC-METHOD-OVERLOADS--------------------------------------------------
def __str__(self):
text = ''
for i in range(self.length()):
if self.multipliers[i] >= 0:
if i != 0:
# the '+' should be omitted at the beginning
text += ' + '
if self.multipliers[i] != 1 or self.variables[i] == '':
# if the multiplier is 1 and there is a variable, there is
# no sense in writing the multiplier
text += str(self.multipliers[i])
else:
if i != 0:
text += ' - '
else:
# at the beginning the '-' shouldn't have spaces around it
text += '-'
if self.multipliers[i] != -1 or self.variables[i] == '':
# if the multiplier is -1 and there is a variable, there
# is no sense in writing the multiplier
# the '-' was already written
text += str(-self.multipliers[i])
# don't forget the variable
text += self.variables[i]
# the string shouldn't be empty
if text == '':
text = '0'
return text
def __eq__(self, other):
if type(other) != type(self):
return False
if self.multipliers == [] or self.multipliers == [0]:
return other.multipliers == [] or other.multipliers == [0]
return (
self.multipliers == other.multipliers
and self.variables == other.variables
)
def __neg__(self):
result = self.copy()
for i in range(result.length()):
result.multipliers[i] *= -1
return result
@misc.convert_to_type('owners type', operator=True)
def __iadd__(self, other):
for i in range(other.length()):
multiplier = other.multipliers[i]
variable = other.variables[i]
self.add_segment(multiplier, variable, inplace=True)
return self
@misc.convert_to_type('owners type', operator=True)
def __isub__(self, other):
self += -other
return self
@misc.convert_to_type(int, operator=True)
def __imul__(self, other):
for i in range(self.length()):
self.multipliers[i] *= other
return self
@misc.convert_to_type(int, operator=True)
def __itruediv__(self, other):
for i in range(self.length()):
self.multipliers[i] = int(self.multipliers[i] / other)
return self
@misc.convert_to_type(int, operator=True)
def __ifloordiv__(self, other):
self.zip()
for i in range(self.length()):
self.multipliers[i] //= other
return self
@misc.convert_to_type(int, operator=True)
def __imod__(self, other):
self.modulo(other, inplace=True)
return self
@misc.assignment_to_binary('+=')
def __add__(self, other):
pass
@misc.assignment_to_binary('-=')
def __sub__(self, other):
pass
@misc.assignment_to_binary('*=')
def __mul__(self, other):
pass
@misc.assignment_to_binary('/=')
def __truediv__(self, other):
pass
@misc.assignment_to_binary('//=')
def __floordiv__(self, other):
pass
@misc.assignment_to_binary('%=')
def __mod__(self, other):
pass
def __rmul__(self, other):
return self * other
def __len__(self):
return len(self.multipliers)
def __getitem__(self, key):
"""Returns the <key>-th segment of the formula if <key> is an integer,
if key is a variable name, returns the multiplier corresponding to
<key>"""
if type(key) == str:
copy_of_self = self.copy()
copy_of_self.zip(inplace=True)
for i in range(len(copy_of_self)):
if copy_of_self.variables[i] == key:
return copy_of_self.multipliers[i]
raise KeyError(f'{key}')
else:
try:
int(key)
except ValueError:
raise KeyError(f'{key}')
except TypeError:
raise KeyError(f'invalid key type: {type(key)}')
if int(key) == key:
return self.get_segment(key)
else:
raise KeyError(f'{key}')
#-------------------------------------------------------------------------
#-MODIFICATION------------------------------------------------------------
@misc.inplace(default=False)
def add_segment(self, multiplier, variable):
self.multipliers.append(multiplier)
self.variables.append(variable)
@misc.inplace(default=False)
def insert_segment(self, multiplier, variable, index):
self.multipliers.insert(index, multiplier)
self.variables.insert(index, variable)
@misc.inplace(default=False)
def remove_segment(self, index):
del self.multipliers[index]
del self.variables[index]
@misc.inplace(default=False)
def substitute(self, recursive=False, **kwargs):
"""Substitutes given variables for given formulas"""
# <kwargs> should look like this {variable: formula}
if recursive:
self._substitute_recursive(**kwargs)
else:
self._substitute_non_recursive(**kwargs)
def _substitute_non_recursive(self, **kwargs):
"""Substitutes given variables for given formulas once"""
# <kwargs> should look like this {variable: formula}
# assign integers to variables
variable_ints = {}
for i, variable in enumerate(kwargs.keys()):
variable_ints[variable] = i
# replace variables with the integers assigned to them
for j in range(len(self)):
variable = self.variables[j]
if variable in variable_ints.keys():
self.variables[j] = variable_ints[variable]
# the steps above are included to avoid issues when one of the
# formulas uses one of the variables we want to substitute
# substitute the integers with desired formulas
for variable, formula in kwargs.items():
self._substitute_one_variable(variable_ints[variable], formula)
def _substitute_recursive(self, **kwargs):
"""Substitutes given variables for given formulas recursively"""
# that means if, for example, we want to substitute recursively
# 'a' for 'b' and 'b' for 'c' in the formula 'a', we will get 'c'
# instead of 'b'
while set(kwargs) & self.get_variables() != set():
for variable, formula in kwargs.items():
# this will avoid issues when <formula> contains <variable>
for i in range(len(self)):
if self.variables[i] == variable:
self.variables[i] = -1
self._substitute_one_variable(-1, formula)
@misc.convert_to_type('owners type', arg_index=1)
def _substitute_one_variable(self, variable, formula):
"""Substitutes <variable> for <formula>"""
# for example if <self> "==" 'a + b',
# <variable> == 'a',
# <formula> "==" 'x + 2'
# then the result should be 'x + 2 + b'
# <formula> is assumed to not use <variable>
while True:
try:
# find the first segment with <variable> and put it aside
i = self.variables.index(variable)
multiplier = self.get_segment(i)[0]
self.remove_segment(i, inplace=True)
# insert each segment from <formula> multiplied by
# <multiplier> into <self>
for j in range(formula.length()):
self.insert_segment(
multiplier*formula.multipliers[j],
formula.variables[j],
i + j,
inplace=True
)
except ValueError:
# break if no more segments with <variable> exist
break
@misc.inplace(default=False)
def zip(self):
"""Reduces the formula to the simplest form"""
for variable in set(self.variables):
# find the first segment with <variable> and put it aside
i = self.variables.index(variable)
multiplier = self.get_segment(i)[0]
self.remove_segment(i, inplace=True)
while True:
try:
# if more segments with <variable> exist, merge them
# with the segment put aside
j = self.variables.index(variable)
multiplier += self.get_segment(j)[0]
self.remove_segment(j, inplace=True)
except ValueError:
# if no more segments with <variable> exist, add the
# merged segments to the formula
if multiplier != 0:
self.insert_segment(
multiplier, variable, i,
inplace=True
)
break
@misc.inplace(default=False)
def modulo(self, n):
"""Reduces the formula to it's simplest modulo <n> equivalent"""
self.zip(inplace=True)
for i in range(self.length()):
self.multipliers[i] %= n
self.zip(inplace=True)
#-------------------------------------------------------------------------
#-OTHER-------------------------------------------------------------------
def length(self):
"""Returns how many segments the formula has"""
return len(self)
def print(self):
"""Prints the formula"""
print(self.__str__())
def copy(self):
"""Returns a copy of <self>"""
copy_of_self = LinearFormula(self.multipliers, self.variables)
return copy_of_self
def get_segment(self, index):
"""Returns a tuple representing <index>-th segment of the formula"""
# for example if formula <formula> is 'a + 3b - 4c', then
# <formula.get_segment(1)> will return (3, 'b')
multiplier = self.multipliers[index]
variable = self.variables[index]
return (multiplier, variable)
def evaluate(self, **kwargs):
"""Returns the value of the formula, given the variable values"""
result = 0
# no variable is represented by a '' string
kwargs[''] = 1
try:
for i in range(self.length()):
result += self.multipliers[i]*kwargs[self.variables[i]]
except KeyError:
raise TypeError("Not all values are provided")
return result
def get_variables(self, omit_zeros=False):
"""Returns a set of variables used by the formula"""
if omit_zeros:
return set(self.zip().variables) - {''}
else:
return set(self.variables) - {''}
@misc.convert_to_type('owners type')
def equivalent(self, other):
"""Tells the user whether <self> and <other> are euivalent or not"""
self_zipped = self.zip()
other_zipped = other.zip()
# after zip() equivalent formulas should jave the same variables,
# including the '' variable
if set(self_zipped.variables) != set(other_zipped.variables):
return False
# if the formulas have different multipliers corresponding to the
# same variable, the result is false
for variable in self_zipped.variables:
if self_zipped[variable] != other_zipped[variable]:
return False
# all multipliers are the same
return True
@misc.convert_to_type('owners type')
def separate(self, formula):
"""Returns a tuple ('m', formula_2), such that
m*<formula> + formula_2 == <self>"""
this = self.zip()
zipped_formula = formula.zip()
if zipped_formula.variables in [[], ['']]:
this -= formula
return (1, this)
condition = True
multiplier = 0
while condition:
if zipped_formula.get_variables() - this.get_variables() != set():
condition = False
break
var = zipped_formula.variables[0]
if var == '':
# this means there are more variables
var = zipped_formula.variables[1]
var_multiplier = this[var]
if var_multiplier > 0 and multiplier >= 0:
this -= zipped_formula
multiplier += 1
elif var_multiplier < 0 and var_multiplier <= 0:
this += zipped_formula
multiplier -= 1
else:
condition = False
this.zip(inplace=True)
return (multiplier, this)
def get_bounds(
self, lower_bounds={}, upper_bounds={},
order=None, recursive=False
):
if recursive == True and order is not None:
raise ValueError(
"The 'recursive' argument cannot be True "
+ "when 'order' is specified"
)
elif order is None:
return self._get_bounds_no_order(
lower_bounds, upper_bounds, recursive)
else:
return self._get_bounds_order(lower_bounds, upper_bounds, order)
def _get_bounds_no_order(
self, lower_bounds={}, upper_bounds={}, recursive=False):
"""Returns a tuple (l_bound, u_bound) such that
l_bound <= <self> <= u_bound, given the bounds of the variables"""
if type(upper_bounds) != dict or type(lower_bounds) != dict:
raise TypeError('arguments are should be dictionaries')
lower_kwargs = {}
upper_kwargs = {}
# zip to avoid redundant zips
zipped = self.zip()
# we will use the <substitute> method to get the lower and upper
# bounds, therefore we need to chose which given bound goes where
# for example if the formula is 'a + b' and the upper bound of 'b' is
# 5, then we will get the upper bound of the formula by substituting
# 'b' for 5, but if the formula is 'a - b', then the aforementioned
# operation will give us the lower bound
zipped._prepare_kwargs_for_get_bounds(
lower_kwargs, lower_bounds, 'lower', 'lower')
zipped._prepare_kwargs_for_get_bounds(
lower_kwargs, upper_bounds, 'lower', 'upper')
zipped._prepare_kwargs_for_get_bounds(
upper_kwargs, lower_bounds, 'upper', 'lower')
zipped._prepare_kwargs_for_get_bounds(
upper_kwargs, upper_bounds, 'upper', 'upper')
lower_bound = self.substitute(**lower_kwargs).zip()
upper_bound = self.substitute(**upper_kwargs).zip()
if recursive == True:
calculate_lower = True
calculate_upper = True
while calculate_lower or calculate_upper:
if calculate_lower:
lower_kwargs = {}
# zip to avoid redundant zips
lower_bound.zip(inplace=True)
# choose the variable bounds
lower_bound._prepare_kwargs_for_get_bounds(
lower_kwargs, lower_bounds, 'lower', 'lower')
lower_bound._prepare_kwargs_for_get_bounds(
lower_kwargs, upper_bounds, 'lower', 'upper')
if lower_kwargs == {}:
# there are no more bounds to use
calculate_lower = False
lower_bound.substitute(**lower_kwargs, inplace=True)
lower_bound.zip(inplace=True)
if calculate_upper:
upper_kwargs = {}
# zip to avoid redundant zips
upper_bound.zip(inplace=True)
# choose the variable bounds
upper_bound._prepare_kwargs_for_get_bounds(
upper_kwargs, lower_bounds, 'upper', 'lower')
upper_bound._prepare_kwargs_for_get_bounds(
upper_kwargs, upper_bounds, 'upper', 'upper')
if upper_kwargs == {}:
# there are no more bounds to use
calculate_upper = False
upper_bound.substitute(**upper_kwargs, inplace=True)
upper_bound.zip(inplace=True)
return (lower_bound, upper_bound)
def _prepare_kwargs_for_get_bounds(
self, kwargs, bounds, result_type, arg_type):
"""Modifies <kwargs> to pass to the <substitute> method,
in the <get_bounds> method"""
# <result_type> - type of the dict that's being modified - <kwargs>,
# should be 'lower' or 'upper'
# <arg_type> - type of the dict passed to <get_bounds> - <bounds>,
# should be 'lower' or 'upper'
for var, bound in bounds.items():
try:
mul = self[var]
except KeyError:
continue
if mul >= 0 and arg_type == result_type:
kwargs[var] = bound
elif mul <= 0 and arg_type != result_type:
kwargs[var] = bound
def _get_bounds_order(self, lower_bounds, upper_bounds, order):
"""Substitutes variables for their bounds given in <lower_bounds> and
<upper_bounds>, in order specified by <order> to return a tuple
(l_bound, u_bound) such that l_bound <= <self> <= u_bound"""
# <lower_bounds>, <upper_bounds> - dicts representing bounds of
# individual variables, in a form {variable: bound}
# <order> - a list representing the order in which to substitute the
# variables
upper_bound = self.zip()
lower_bound = upper_bound.copy()
for variable in order:
# get the bounds of <variables>
try:
variable_lower_bound = lower_bounds[variable]
except KeyError:
variable_lower_bound = None
try:
variable_upper_bound = upper_bounds[variable]
except KeyError:
variable_upper_bound = None
# and use them to get the bounds of <self>
lower_bound._process_variable_bound(
variable, 'lower',
lower_bound=variable_lower_bound,
upper_bound=variable_upper_bound
)
upper_bound._process_variable_bound(
variable, 'upper',
lower_bound=variable_lower_bound,
upper_bound=variable_upper_bound
)
return lower_bound, upper_bound
def _process_variable_bound(
self, variable, output_bound_type,
lower_bound=None, upper_bound=None
):
"""Modifies <self> so that <self> after the algorithm is the upper or
lower bound of <self> before the algorithm, based on the bounds of
<variable>"""
# <lower_bound>, <upper_bound> - lower and upper bounds of <variable>
# <output_bound_type> - should be "lower" or "upper" - a string that
# specifies whether the modified <self> should be the lower or upper
# bound of the original <self>
try:
multiplier = self[variable]
except KeyError:
return
if output_bound_type not in ('lower', 'upper'):
raise ValueError(
f"invalid 'output_bound_type' argument: {output_bound_type}")
# we will substitute one of the formulas <lower_bound>, <upper_bound>
# for <variable> to get the desired outcome
# for example <self> is 'a + b' and the upper bound of 'b' is 5, then
# we will get the upper bound of the formula by substituting 'b' for
# 5, but if the formula is 'a - b', then the aforementioned
# operation will give us the lower bound
if multiplier > 0:
if output_bound_type == 'lower':
bound = lower_bound
elif output_bound_type == 'upper':
bound = upper_bound
else:
if output_bound_type == 'lower':
bound = upper_bound
elif output_bound_type == 'upper':
bound = lower_bound
if bound is not None:
self.substitute(**{variable: bound}, inplace=True)
self.zip(inplace=True)
#-------------------------------------------------------------------------
|
0de034c6b9b380313387957d56941775047f5f63
|
a100kpm/daily_training
|
/problem 0137.py
| 1,258 | 3.953125 | 4 |
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Implement a bit array.
A bit array is a space efficient array that holds a value of 1 or 0 at each index.
init(size): initialize the array with size
set(i, val): updates index at i with val where val is either 1 or 0.
get(i): gets the value at index i.
'''
class space_array:
def __init__(self,size):
self.array=[0]*size
def set_(self,i,val):
self.array[i]=val
def get(self,i):
return self.array[i]
# =============================================================================
# =============================================================================
# =============================================================================
# =============================================================================
# # # # NAY NAY NAY NAY
# # # # =============================================================================
# =============================================================================
# =============================================================================
#
# =============================================================================
|
0e4c2aa723791f021934087b676836faab15b45b
|
kodfactory/AdvayaAndShubh
|
/OddOrEven.py
| 140 | 4.15625 | 4 |
num = 122
#9 -> int
#"9" -> string
#print(9%2)
#print(10%2)
if num%2 == 1:
print("Number is odd")
else:
print("Number is even")
|
9037989137481cbe2f3ce7be1c39ed7c2c8e8a4c
|
ywozvc/perceptron
|
/perceptron.py
| 3,114 | 3.859375 | 4 |
import numpy as np
from collections import Counter
from math import sqrt
import perceptron_errors
class Perceptron:
"""
Description:
---
Perceptron with a sigmoid activation function for binary classification
"""
def __init__(self, n_tuple, weights=None):
"""
Parameters
---
n_tuples : int
x = (x1,x2...x_n)
what is the dimension of the vector space of these vectors
weights : np.array
an array of weights. if None weights will be calculated randomly
about a normal
distribution centered at zero
References
---
1. https://intoli.com/blog/neural-network-initialization/
"""
if(n_tuple<=0):
raise perceptron_errors.VectorError()
else:
self.n_tuple = n_tuple
if weights==None:
# n_tuples + 1 because bias needs a weight as well
"""
weight will be calculated using the np.random.normal() method
with standard deviation calculated based on [1]
STANDARD DEVIATION(std) equal to 'variances which are
inversely proportional to the number of inputs
into each neuron.
"""
std = sqrt(2.0/n_tuple+1)
self.weights = np.random.normal(loc=0,scale=std,size=n_tuple+1)
self.learning_rate = 0.05
self.bias = 1
@staticmethod
def sigmoidal_activation(x):
"""
Description
---
Sigmoidal activation function. exists between 0 and 1.
will take in as input the weighted sum of x_n, weights,
and bias and output a integer value [0,1]
Parameter
---
x: float
the weighted sum x_n variable and the weights and bias
Returns
---
0 or 1 (activation function where the threshold is 0.5)
"""
result = 1.0 / (1 + np.power(np.e, -x))
return 0 if result < 0.5 else 1
def __call__(self, x_n):
"""
Parameters
---
x_n : list
a python list representing the n-tuple real valued x variable
each numerical value in the list should be float
Returns
---
Perceptron.sigmoid_function : int
will return either a zero or one
"""
weighted_input = self.weights[:-1] * x_n
weighted_sum = weighted_input.sum() + self.bias *self.weights[-1]
return Perceptron.sigmoidal_activation(weighted_sum)
def adjust(self, target_result, calculated_result, in_data):
error = target_result - calculated_result
for i in range(len(in_data)):
correction = error * in_data[i] *self.learning_rate
#print("weights: ", self.weights)
#print(target_result, calculated_result, in_data, error, correction)
self.weights[i] += correction
# correct the bias:
correction = error * self.bias * self.learning_rate
self.weights[-1] += correction
|
65b876469a2c613aeb2acd10bb4609569d933028
|
dyrroth-11/Information-Technology-Workshop-I
|
/Python Programming Assignments/Assignemt1/22.py
| 523 | 4.09375 | 4 |
#!/usr/bin/env python3
"""
Created on Wed Mar 25 10:17:27 2020
@author: Ashish Patel
"""
"""
Write a Python program to convert a list of multiple integers into a single integer.
Sample list: [11, 33, 50]
Expected Output: 113350
LOGIC:1)we take a list as a input.
2)Then concatenate every element of it into a string.
3)finally print that string.
"""
list = list(input("Enter list: ").split(","))
s=str("")
for i in list:
s = s + str(i)
print("final number by concatinating numbers of the list: " +s)
|
85c7f984ad99195198970f8adf32f42e3c9d9931
|
raghavendra990/python-practice
|
/linked_list/linked_list.py
| 2,667 | 4.0625 | 4 |
#Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# linked list class
class LinkedList:
#function to initialize the linke dlist onject
def __init__(self):
self.head = Node
#t thios function will print hte contents of the linked lisr
def PrintList(self):
temp = self.head
while(temp):
print temp.data
temp = temp.next
#push the value at the first loaction
def push(self, new_data):
temp = Node(new_data)
temp.next = self.head
self.head = temp
# delete the first occurance of the key
def deleteNode(self, key):
#stire the head node
temp = self.head
# if head node itself hold the key to be deleted
if(temp is not None):
if temp.data == key:
self.head = temp.next
temp = None
return
#search for the key to be deleted
while(temp is not None):
if temp.data==key:
break
prev = temp
temp = temp.next
# if key ins not present in linked list
if temp is None:
return
# unlink the node from the linklist
prev.next = temp.next
temp = None
# insert a new node aftera given node
def insertAfter(self, prev_node, new_data):
#check if previous node exist
if prev_node is None:
print "The given previous node must be in linkedlist"
return
#crete a new node with given new dat
new_node = Node(new_data)
# Make next of new node as next of prev node
new_node.next = prev_node.next
# Make next of prev_node as new Node
prev_node.next = new_node
#insert a new node at the end
def append(self, new_data):
#create a new node and put in the data
new_node = Node(new_data)
# is linked list ios empty
if self.head is None:
self.head = new_node
return
# Else traverse till the last node
last = self.head
while(last.next):
last = last.next
# change the next of last node
last.next = new_node
# get count of linklist
def getCount(self):
temp = self.head
count = 0
while(temp):
count +=1
temp = temp.next
return count
#code execution start here
if __name__ =='__main__':
#start with the empty liked list
llist = LinkedList()
llist.head = Node(1)
second = Node(2)
third = Node(3)
"thre node have been created we have refrence these blocks as first, second and third"
"now every node has None next "
llist.head.next = second # link first with the secobd
"Now `next of the first is refrence to the the second, same we have to do for second and third"
second.next = third
llist.push(7)
llist.insertAfter(second, 45)
llist.append(455)
llist.deleteNode(48)
llist.PrintList() # will print he list
print "length of the linklist:", llist.getCount()
|
64777d1e439e36ea1f7850bb8718968d0b2bec31
|
YJL33/LeetCode
|
/old_session/session_1/_461/_461_hamming_distance.py
| 903 | 3.953125 | 4 |
"""
461. Hamming Distance
Total Accepted: 5441
Total Submissions: 7355
Difficulty: Easy
Contributors: Samuri
The Hamming distance between two integers is:
the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 <= x, y < 2^31.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
^ ^
The above arrows point to positions where the corresponding bits are different.
"""
class Solution(object):
def hammingDistance0(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
a, b, cnt = bin(x)[2:].zfill(31), bin(y)[2:].zfill(31), 0
for i in range(31):
if a[i] != b[i]: cnt += 1
return cnt
def hammingDistance(self, x, y):
# shorter:
return bin(x^y).count('1')
|
82a166324187ccbaecb15c00f31a4885eab075f7
|
Vijay1234-coder/data_structure_plmsolving
|
/GRAPHS/DirectedGraph.py
| 889 | 3.953125 | 4 |
class Graph:
def __init__(self,Nodes,is_directed =False):
self.nodes = Nodes
self.adj_lis = {}
self.is_directed = is_directed
for node in self.nodes:
self.adj_lis[node] = []
def add_edge(self,u,v):
self.adj_lis[u].append(v)
if self.is_directed==False: # if graph is directed mean if we connect u to v then it is not connected back
self.adj_lis[v].append(u)
def degree(self,node):
deg = len(self.adj_lis[node])
return deg
def print_adj_lis(self):
for node in self.nodes:
print(node,"->",self.adj_lis[node])
nodes = ["A","B","C","D","E"]
all_edges = [("A","B"),("A","C"),("B","D"),("C","D"),("C","E"),("D","E")]
graph = Graph(nodes,is_directed=True)
for u,v in all_edges:
graph.add_edge(u,v)
graph.print_adj_lis()
print("Degree of C : ",graph.degree("C"))
|
f96de0483e99d36dbc7598014f4a8a954fc10790
|
Uxooss/Lessons-Hellel
|
/Heap/Clocks.py
| 717 | 3.96875 | 4 |
# С начала суток прошло n минут. Определите, сколько часов и минут будут показывать электронные часы в этот момент.
# Программа должна вывести два числа: количество часов (от 0 до 23) и количество минут (от 0 до 59).
# Учтите, что число n может быть больше, чем количество минут в сутках.
n = int(input('\nСколько минут прошло с начала суток:\t'))
h = (n // 60) % 24
m = (n % 60)
print('', '~' * 30, '\n\t На часах:\n\t\t ', str(h), ' : ', str(m), '\n', '~' * 30)
|
85e34346f15da1f2d67a440d6e7d290a5892419e
|
tkshim/leetcode
|
/leetcode_0000_stack.py
| 457 | 3.71875 | 4 |
#!/usr/bin/env python
#coding: utf-8
class mystack():
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
del self.stack[-1]
result = self.stack[-1]
return result
ins001 = mystack()
for i in range(20):
ins001.push(i)
print ins001.stack
for n in range(10):
ins001.pop()
print ins001.stack
#https://www.atmarkit.co.jp/ait/articles/1908/06/news015.html
|
e44eea49e61472185b3c961a2226d949351defe3
|
johann9911/JohannBogota
|
/ejercicios.py
| 4,772 | 4.3125 | 4 |
#!/usr/bin/env python
# coding: utf-8
# # EJERCICIOS DEL LIBRO
#
#
# De acuerdo al libro Qsdfsf se realizaran estos ejercicios de programación con el lenguaje python.
#
# 1.1 Programa que sume dos numero complejos. funcion suma_C
# 2.2
#
#
#
#
# ### 1.1 SUMA DE COMPLEJOS
# Se define los dos numeros complejos en sus respectivos vectores, determinando que la posicion 0 sea la parte real y la posicion 1 la parte imaginaria. Y por definicion se sabe que la suma de complejos es la suma de las partes reales y las partes imaginarias.
# Para mostrar el programa que realice la suma de complejos se toma como ejemplo los numeros 3 + 5i y 2i.
# In[3]:
def suma_C(Cm1,Cm2):
sum_com = [(Cm1[0]+Cm2[0]),(Cm1[1]+Cm2[1])]
real = Cm1[0]+Cm2[0]
img = Cm1[1]+Cm2[1]
print("----------SUMA DE DOS NÚMEROS-------")
#Numero 1
if Cm1[0]==0:
print("Numero complejo 1:",str(Cm1[1])+"i")
elif Cm1[1]==0:
print("Numero complejo 1:",Cm1[0])
elif Cm1[1]<0:
print("Numero complejo 1:",Cm1[0],str(Cm1[1])+"i")
else:
print("Numero complejo 1:",Cm1[0],"+"+str(Cm1[1])+"i")
#Numero 2
if Cm2[0]==0:
print("Numero complejo 2:",str(Cm2[1])+"i")
elif Cm2[1]==0:
print("Numero complejo 2:",Cm2[0])
elif Cm2[1]<0:
print("Numero complejo 2:",Cm2[0],str(Cm2[1])+"i")
else:
print("Numero complejo 2:",Cm2[0],"+"+str(Cm2[1])+"i")
#suma de numeros complejos
if sum_com[0]==0:
print("El resultado es:",str(sum_com[1])+"i")
elif sum_com[1]==0:
print("El resultado es:",sum_com[0])
elif sum_com[1]<0:
print("El resultado es:",sum_com[0],str(sum_com[1])+"i")
else:
print("El resultado es:",sum_com[0],"+"+str(sum_com[1])+"i")
#Si alguna otra función necesita multiplicar dos numeros se devuelve el resultado
return sum_com
# In[4]:
suma_C([3,5],[0,2])
# ### 1.2 Multiplicación
# In[24]:
def Mul_C(C1,C2):
Real = (C1[0]*C2[0])-(C1[1]*C2[1])
imag = (C1[0]*C2[1])+(C2[0]*C1[1])
Resul = [Real,imag]
print("----------MULTIPLICACIÓN DE DOS NÚMEROS-------")
#Numero 1
if C1[0]==0:
print("Numero complejo 1:",str(C1[1])+"i")
elif C1[1]==0:
print("Numero complejo 1:",C1[0])
elif C1[1]<0:
print("Numero complejo 1:",C1[0],str(C1[1])+"i")
else:
print("Numero complejo 1:",C1[0],"+"+str(C1[1])+"i")
#Numero 2
if C2[0]==0:
print("Numero complejo 2:",str(C2[1])+"i")
elif C2[1]==0:
print("Numero complejo 2:",C2[0])
elif C2[1]<0:
print("Numero complejo 2:",C2[0],str(C2[1])+"i")
else:
print("Numero complejo 2:",C2[0],"+"+str(C2[1])+"i")
#Multiplicación de numeros complejos
if Resul[0]==0:
print("El resultado es:",str(Resul[1])+"i")
elif Resul[1]==0:
print("El resultado:",Resul[0])
elif Resul[1]<0:
print("El resultado:",Resul[0],str(Resul[1])+"i")
else:
print("El resultado:",Resul[0],"+"+str(Resul[1])+"i")
#Si alguna otra función necesita multiplicar dos numeros se devuelve el resultado
return Resul
# In[25]:
Mul_C([-5,4],[1,3])
# ### 1.3 CONJUGADO DE UN NUMERO COMPLEJO
# In[28]:
def Conju_C(C1):
print("----------CONJUGADO DE UN NÚMERO-------")
#Numero complejo
if C1[0]==0:
print("Numero complejo 1:",str(C1[1])+"i")
elif C1[1]==0:
print("Numero complejo 1:",C1[0])
elif C1[1]<0:
print("Numero complejo 1:",C1[0],str(C1[1])+"i")
else:
print("Numero complejo 1:",C1[0],"+"+str(C1[1])+"i")
#Conjugado
C1[1] = -C1[1]
Resul = C1
if C1[0]==0:
print("El conjugado del numero complejo:",str(C1[1])+"i")
elif C1[1]==0:
print("El conjugado del numero complejo:",C1[0])
elif C1[1]<0:
print("El conjugado del numero complejo:",C1[0],str(C1[1])+"i")
else:
print("El conjugado del numero complejo:",C1[0],"+"+str(C1[1])+"i")
#Si alguna otra función necesita multiplicar dos numeros se devuelve el resultado
return Resul
# In[29]:
Conju_C([-5,4])
# ### 1.4 DIVISIÓN NÚMEROS IMAGINARIOS
# In[32]:
def Div_C(C1, C2):
Conjugado = Conju_C(C2)
Numerador = Mul_C(C1, Conjugado)
Denominador = Mul_C(C2, Conjugado)
Resul = [Numerador,Denominador]
#División de numeros complejos
if Resul[0]==0:
print("El resultado es:",str(Resul[1])+"i")
elif Resul[1]==0:
print("El resultado:",Resul[0])
elif Resul[1]<0:
print("El resultado:",Resul[0],str(Resul[1])+"i")
else:
print("El resultado:",Resul[0],"+"+str(Resul[1])+"i")
# In[33]:
Div_C([-5,4],[1,3])
# In[ ]:
|
a3dffa2d9fa511e1d2f58e7055f9a3a744bf6560
|
sharmisthaec/python
|
/ML codes/introduction/exampl1.py
| 570 | 3.5625 | 4 |
#standard deviation
import numpy as np
heights = [5.9, 5.5, 6.1, 6.0, 7.2, 5.1, 5.3, 6.0, 5.8, 6.0]
print("Sample average: %.2f" % np.mean(heights))
print("Sample standard deviation: %.2f" % np.std(heights, ddof=1))
print("Improper standard deviation: %.2f\n" % np.std(heights))
large_num_heights = np.random.random(size=100000)*1.5 + 5.0
print("Sample average: %.2f" % np.mean(large_num_heights))
print("Sample standard deviation: %.2f" % np.std(large_num_heights, ddof=1))
print("Less improper standard deviation: %.2f" % np.std(large_num_heights))
#
|
937fc7f1f73084f4ceef6888bf7ad8909d29655c
|
AmberJing88/algorithm-datastructure
|
/Array/ArrayReview378.py
| 2,339 | 3.515625 | 4 |
# Array problems
"""leetcode 378: sorted matrix in ascending order, find the kth smallest element in the matrix"""
def KthSmallest(matrix, k):
m,n = len(matrix), len(matrix[0])
low, high = matrix[0][0], matrix[m-1][n-1]
while low <= high:
cnt = 0
mid = low + (high - low)//2
for i in range(m):
for j in range(n):
if matrix[i][j] <= mid:
cnt += 1
if cnt < k:
low = mid +1
else:
high = mid -1
return low
# method 2 heap queue method
import heapq
def kthsmallest(matrix, k):
rows, cols = len(matrix), len(matrix[0])
if k > (rows *cols)//2:
back = True
k = row *cols -k+1
frontier = [(-matrix[rows-1][cols-1],rows-1,cols-1)]
else:
back = False
frontier = [(matrix[0][0],0,0)]
while k:
val, r, c = heapq.heappop(frontier)
k -= 1
if not back:
if c != len(matrix[0]-1):
heapq.heappush(frontier,(matrix[r][c+1],r, c+1))
if c ==0 and r != len(matrix)-1:
heapq.heappush(frontier,(matrix[r+1][c],r+1,c))
else:
if c != 0:
heapq.heappush(frontier, (matrix[r][c-1], r, c-1))
if c == cols-1 and r != 0:
heapq.heappush(frontier, (-matrix[r-1][c], r-1, c))
return -val, if back else val
"""array 645: set s contains number from 1 to n, but one of numbers gotcopied to
another number in the set, which result in repetation, and loss of another number.
find out the two errors."""
def FindErrorNums(nums):
for num in nums:
if nums[abs(num)-1] < 0:
duplicate = abs(num)
else:
nums[abs(num)-1] *= -1
for i, n in enumerate(nums):
if n >0:
missing = i+1
break
return duplicate, missing
""" array 448: array of integers 1 <= a[i] <= n (size n), some elements appear twice, and
others appear once. find all dispeeared number."""
def FindMissing(nums):
for n in nums:
n = abs(n)
nums[n-1] = -abs(nums[n-1])
return [i+1 for i, n in enumerate(nums) if n>0]
Note: do not use brute force to solve, because nums unsorted, time O(N) >O(n).
|
09e96357bb490e4a45840d53d4af52a3335e5d7d
|
manutdmohit/pythonprogramexamples
|
/accessdatafromthedictionary.py
| 189 | 4.0625 | 4 |
d={100:'durga',200:'ravi',300:'shiva'}
key=int(input('Enter key to find value:'))
if key in d:
print('The corresponding value:',d[key])
else:
print('The specified key not available')
|
0a2b8df4218ebc0a917c54a3902a59bc59a99a31
|
swapnil-sat/helloword
|
/Python-Set Methods_20-3-21.py
| 1,798 | 3.90625 | 4 |
# ====================================================================================||
# || Python- Set Methods ||
# || ||
# || ||
# ||==================================================================================||
# >>Set Methods<<<<
# Method Description
# 1 add() Adds an elements to the sets
# 2.clear() Removes all the elements from the set
# 3.copy() Returns a copy of the set.
# 4.difference() Returns a set containing the difference between two or moresets
# 5.difference_update() Removes the items in this set that are also included in another specified set.
# 6.discard() Remove the specified items.
# 7.intersection() Returns a set,that is the intersection of two other sets.
# 8.intersecton_update()Remove the items in this set that are not present in other specified set(s)
# 9.isdisjoint() Returns whether two sets have a intersection or not
# 10.issubset() Returns whether another set contains this set or not .
# 11.issuperset() Returns whether this set contain another set or not .
# 12.pop() Removes an element from the set.
# 13.remove() Remove the specified element.
# 14.symmetric_difference() Returns a set with the symmetric differences of two sets .
# 15.symmetric_difference_update() insert the symmetric difference from this set and another.
# 16.union() Return a set containing the union of sets .
# 17.update() update the set with the union of this set and other .
|
012d9b5aa13c557ad958343cadf935b73c808a56
|
fsym-fs/Python_AID
|
/month01/teacher/day14/exercise03.py
| 435 | 3.625 | 4 |
"""
定义函数,根据年、月、日计算星期。
0 星期一
1 星期二
....
"""
import time
def get_week(year, month, day):
str_time = "%d-%d-%d" % (year, month, day)
time_tuple = time.strptime(str_time, "%Y-%m-%d")
tuple_week = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")
return tuple_week[time_tuple[6]]
print(get_week(2020, 1, 16))
|
e046f49d63dddaf7abcfc9d8cd230f9f17d47562
|
CP1401/subject
|
/other/score_smiles_functions.py
| 2,040 | 4.0625 | 4 |
"""
CP1401 Example (from Help Session 01/09/2020)
Score -> Result program with menu, accumulation, etc.
(a bit similar to smiley, frowny from prac 4)
Now with added functions.
This version improves on the previous one by removing the duplication (DRY)
of the section that prints the status.
"""
MINIMUM_SCORE = 0
MAXIMUM_SCORE = 10
MENU = """Menu:
- instructions
- enter score
- print status
- quit
> """
def main():
"""Program to determine smileyness of scores"""
total_score = 0
number_of_scores = 0
print(MENU, end="")
choice = input().lower()
while choice != "q":
if choice == 'i':
print("Instructions")
elif choice == 'e':
score = int(input(f"Enter score {number_of_scores + 1}: "))
while score < MINIMUM_SCORE or score > MAXIMUM_SCORE:
print(f"Invalid score. Score must be between {MINIMUM_SCORE} and {MAXIMUM_SCORE}")
score = int(input(f"Enter score {number_of_scores + 1}: "))
# print # of smileys that matches their score
# 3 -> :):):)
for i in range(score):
print(":)", end="")
print() # Note, we could also just use print(":)" * score)
total_score += score
number_of_scores += 1
elif choice == 'p':
print_status(number_of_scores, total_score)
else:
print("Invalid choice")
print(MENU, end="")
choice = input().lower()
print("Finished")
print_status(number_of_scores, total_score)
def print_status(number_of_scores, total_score):
"""Display current status of scores entered so far"""
if number_of_scores > 0:
average = total_score / number_of_scores
print(f"From {number_of_scores} scores, total is {total_score}.")
if average < 5:
status_word = "bad"
else:
status_word = "good"
print(f"The average score is {average}, which is {status_word}.")
else:
print("No scores.")
main()
|
ea69e3751358847c794ad11d04b7922710697d49
|
kseniiaguk/Hellodarkness
|
/2.py
| 814 | 3.5625 | 4 |
def calc(x,y,z):
if y=='+' or y=='-' or y=='*' or y=='/':
if y=='+':
return (x+z)
if y=='-':
return (x-z)
if y=='*':
return (x*z)
if y=='/':
try:
return (x/z)
except ZeroDivisionError:
print ('Нельзя делить на 0')
else:
return ('Неизвестная операция')
a=str(input())
x1=str('')
y1=str('')
z1=str('')
k=0
for i in range(0,len(a)):
if a[i].isdigit()==False and a[i]!='.' and k==0 and i!=0:
k+=1
x1+=a[0:i]
y1+=a[i]
if a[i+1]=='(' and a[i+2]=='-':
z1+=a[i+2:len(a)-1]
else:
z1+=a[i+1:len(a)]
x2=float(x1)
y2=y1
z2=float(z1)
x=calc(x2,y2,z2)
print(x)
|
80225c7cf6741855bac7d6d9283ca6c7cf5b47c0
|
extra-virgin-olive-eul/pe_solutions
|
/17/PE-P17_VSX.py
| 5,481 | 3.609375 | 4 |
#!/usr/bin/env python3
'''
Program: PE-P17_VSX.py
Author: vsx-gh (https://github.com/vsx-gh)
Created: 20171114
Project Euler Problem 17:
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out
in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
forty-two) contains 23 letters and 115 (one hundred and fifteen) contains
20 letters. The use of "and" when writing out numbers is in compliance with
British usage.
'''
import argparse
import math
def process_hundreds(input_int):
""" Converts integer (< 1000) to lexical equivalent """
out_str = ""
items_dict = {} # {'100': <number of hundreds>}, etc.
dec_list = [100, 10, 1]
num_left = input_int
# Find out how many of each place we have
for item in dec_list:
if int(num_left / item) == 0:
items_dict[str(item)] = 0
else:
items_dict[str(item)] = int(num_left / item)
num_left = num_left % item
# Interaction of tens and ones has big effect on lexical display
tens_ones = items_dict['10'] * 10 + items_dict['1'] * 1
if tens_ones < 20 and tens_ones > 0: # 1 - 19
add_to = num_dict[str(tens_ones)]
elif tens_ones >= 20 and tens_ones % 10 == 0: # 20, 30, 40, etc.
add_to = num_dict[str(items_dict['10'] * 10)]
elif tens_ones >= 20 and tens_ones % 10 != 0: # 21, 36, 44, etc.
add_to = num_dict[str(items_dict['10'] * 10)] + '-' \
+ num_dict[str(items_dict['1'] * 1)]
else:
add_to = ''
# Given British English requirements of the assignment, this block is needed
# Otherwise hundreds can be processed like anything else non-tens and non-ones
if items_dict['100'] > 0:
out_str = out_str + num_dict[str(items_dict['100'])] + ' ' \
+ num_dict['100']
if tens_ones > 0:
if lang_type == 'be':
out_str = out_str + ' and ' + add_to
else:
out_str = out_str + ' ' + add_to
else:
out_str += add_to
return out_str
def get_lexical(input_num):
""" Converts any input_num to words. Let's get lexical. """
# Find starting divisor
order_mag = int(10 ** (len(str(input_num)) - 1))
num_as_str = ""
remainder = input_num
# Proceed by thousands; each set will be processed as a group < 1000
# and then we step down
while order_mag >= 1000:
if int(math.log10(order_mag)) % 3 != 0:
order_mag = int(order_mag / 10)
continue
# This is how many of current term we have, i.e., 359 millions
# Go off and process 359, then tack on the place term's name
proc_term = int(remainder / order_mag)
add_num = process_hundreds(proc_term) + ' ' \
+ num_dict[str(order_mag)] + ' '
num_as_str += add_num
# What's left over goes to next round with 1/1000th order of magnitude
remainder = remainder % order_mag
order_mag = int(order_mag / 1000)
num_as_str += process_hundreds(remainder)
return num_as_str
# Should be all the conversions we need; build the rest from these
num_dict = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five',
'6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten',
'11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen',
'15': 'fifteen', '16': 'sixteen', '17': 'seventeen',
'18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty',
'40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy',
'80': 'eighty', '90': 'ninety', '100': 'hundred', '1000': 'thousand',
'1000000': 'million', '1000000000': 'billion',
'1000000000000': 'trillion', '1000000000000000': 'quadrillion'}
# Get inputs
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--inputint',
required=True,
type=int,
help='Input integer to calculate'
)
parser.add_argument('-s', '--startint',
required=True,
type=int,
help='Starting point for integer range'
)
# This was an awesome idea from Caroline
parser.add_argument('-e', '--english',
required=True,
choices=['ae', 'be'],
help='English variant to use (American or British)'
)
all_args = parser.parse_args()
process_int = all_args.inputint
range_start = all_args.startint
lang_type = all_args.english
# Error check
if range_start > process_int:
print('Error: Start of range larger than end. Try again.')
quit()
char_total = 0
# Build some words from numbers in range
for elem in range(range_start, process_int + 1):
stringy_int = get_lexical(elem)
num_chars = len(stringy_int.strip().replace('-', '').replace(' ', ''))
char_total += num_chars
print(stringy_int)
# Total characters in 1..process_int
print('Spelling out numbers using {} between {} and {} is {}'.format(
lang_type.upper(), range_start, process_int, char_total))
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
|
a1b7ca05d958105b0f412ba9f61d147734935d5c
|
bkopjar/django-websites
|
/lab3/zad1.py
| 616 | 4.0625 | 4 |
grades = { "Pero": [2,3,3,4,3,5,3],
"Djuro" : [4,4,4],
"Marko" : [3,3,2,3,5,1]
}
# Ispisi ime studenta koji ima najvisi prosjek. Zadatak treba proci kroz
# sve studente, izracunati prosjek i ispisati ime studenta s navisim prosjekom.
# -- vas kod ide ispod -- #
def average(items):
total = float(sum(items))
return total/len(items)
max = 0
maxv = ""
br = 0
for key,values in grades.items():
avg=0
for element in values:
avg += element
br +=1
avg = avg/br
if max<avg:
max=avg
maxv=key
br = 0
print(max, maxv)
|
20f065f464a6430e7fb41bee06727500c5bbbc0d
|
nekapoor7/Python-and-Django
|
/GEEKS/filehandling/read content.py
| 1,260 | 4.3125 | 4 |
"""Python Program to Read the Contents of a File"""
with open("C:\\Users\\nekapoor\\git\\Python-and-Django\\PYTHON PROGRAMS\\file_data\\data.txt",'r',encoding='utf-8') as file1:
for line in file1.read():
print(line,end='')
"""Python Program to Count the Number of Words in a Text File"""
with open("C:\\Users\\nekapoor\\git\\Python-and-Django\\PYTHON PROGRAMS\\file_data\\data.txt", 'r') as f:
data = f.read()
line = data.splitlines()
words = data.split()
spaces = data.split(" ")
charc = (len(data) - len(spaces))
print('\n Line number ::', len(line), '\n Words number ::', len(words), '\n Spaces ::', len(spaces),
'\n Charecters ::', (len(data) - len(spaces)))
"""Python Program to Count the Occurrences of a Word in a Text File"""
print(open("C:\\Users\\nekapoor\\git\\Python-and-Django\\PYTHON PROGRAMS\\file_data\\data.txt", 'r').read().count(input()))
"""Python Program to Count the Occurrences of Each Word in a Text File"""
from string import ascii_lowercase
from collections import Counter
with open("C:\\Users\\nekapoor\\git\\Python-and-Django\\PYTHON PROGRAMS\\file_data\\data.txt", 'r') as f:
print(Counter(letter for line in f for letter in line.lower() if letter in ascii_lowercase))
|
b8d9a39a8c418dc2d2d484fd6270307f7734d979
|
sainttobs/learning_python
|
/functions/whileloop_infunctions.py
| 492 | 4.0625 | 4 |
# using while loop with a function
def get_name(firstName, lastName):
fullname = firstName + ' ' + lastName
return fullname.title()
while True:
print("\nWhat is your name")
print("Press q at any time to quit this program")
firstName = input("Enter your first name: ")
if firstName == 'q':
break
lastName = input("Enter your last name: ")
if lastName == 'q':
break
name = get_name(firstName, lastName)
print("\nHello " + name)
|
2de2996ed1d47edfc1493a787c5f175b5bc3e0f4
|
di0theDestroyer/blobfish-retropi
|
/blobfish_ascii_trend_plotter.py
| 761 | 3.734375 | 4 |
import aplotter
import math
class AsciiTrendPlotter(object):
def __init__(self):
print ("entered ctor")
def plot(self):
print("entered plot()")
print('****** Sin([0,2pi]) ******')
scale=0.1
n=int(2*math.pi/scale)
plotx=[scale*i for i in xrange(n)]
ploty=[math.sin(scale*i) for i in xrange(n)]
aplotter.plot(plotx,ploty)
print('****** Some discrete data sequence ******')
data=[ord(c) for c in 'ASCII Plotter example']
aplotter.plot(data)
#return asciiPlot
#DEBUG
def main():
print("entered main()")
something = AsciiTrendPlotter()
something.plot()
if __name__ == "__main__":
main()
|
c23f458e847b1376d369e000283ba5c6d9e9e42a
|
sifact/Leet-Code-Problems
|
/leetCode/Array/Medium/Remove Duplicate from Sorted Array 2.py
| 514 | 3.625 | 4 |
def removeDuplicates(nums):
tail = 0
for num in nums:
if tail < 2 or num > nums[tail - 2]:
nums[tail] = num
print(nums)
tail += 1
return tail
def removeDuplicates2(nums):
tail = 0
for num in nums:
if tail < 2 or num > nums[tail - 2]:
nums[tail] = num
print(nums)
tail += 1
print(tail)
return tail
a = list(map(int, input().split()))
print(removeDuplicates2(a))
|
2b4f306edd2e239194d681a2f72c8c2a1abb392b
|
OZ-T/leetcode
|
/1/116_populating_next_right_pointers_in_each_node/main.py
| 1,825 | 3.984375 | 4 |
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect_recursive(self, root: 'Node') -> 'Node':
if not root:
return root
def connect_two_nodes(a, b):
if not a or not b:
return
a.next = b
connect_two_nodes(a.left, a.right)
connect_two_nodes(b.left, b.right)
connect_two_nodes(a.right, b.left)
connect_two_nodes(root.left, root.right)
return root
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
current_level = [root]
while current_level:
next_level = []
for i in range(len(current_level)):
if i != len(current_level)-1:
current_level[i].next = current_level[i+1]
if current_level[i].left:
next_level.append(current_level[i].left)
if current_level[i].right:
next_level.append(current_level[i].right)
current_level = next_level
return root
if __name__ == '__main__':
s = Solution()
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
s.connect(root)
assert root.next == None
assert root.left.next == root.right
assert root.right.next == None
assert root.left.left.next == root.left.right
assert root.left.right.next == root.right.left
assert root.right.left.next == root.right.right
assert root.right.right.next == None
|
137efa4c330a1cf06050d0389e3bc5af0577e1b6
|
trickaugusto/python
|
/exercicios urionlinejudge/1010.py
| 974 | 3.828125 | 4 |
# Neste problema, deve-se ler o código de uma peça 1, o número de peças 1, o valor unitário de cada peça 1, o código de uma peça 2, o número de peças 2 e o valor unitário de cada peça 2. Após, calcule e mostre o valor a ser pago.
# Entrada
# O arquivo de entrada contém duas linhas de dados. Em cada linha haverá 3 valores, respectivamente dois inteiros e um valor com 2 casas decimais.
# Saída
# A saída deverá ser uma mensagem conforme o exemplo fornecido abaixo, lembrando de deixar um espaço após os dois pontos e um espaço após o "R$". O valor deverá ser apresentado com 2 casas após o ponto.
##############################################################
linha = input()
codPeca1, qtdPecas1, valorUnitPeca1 = map(float, linha.split(" "))
linha = input()
codPeca2, qtdPecas2, valorUnitPeca2 = map(float, linha.split(" "))
valorFinal = (valorUnitPeca1 * qtdPecas1) + (valorUnitPeca2 * qtdPecas2)
print("VALOR A PAGAR: R$ %.2f" % valorFinal)
|
1a68ff56556e1a2f9b54264eff08b3e327a13510
|
jwylie/Project-Euler
|
/Python/Problem10.py
| 399 | 3.625 | 4 |
def main():
max = 2000000
numbers = set(range(3, max + 1, 2))
for number in range(3, int(max ** 0.5) + 1):
if number not in numbers:
continue
num = number
while num < max:
num += number
if num in numbers:
numbers.remove(num)
print(2 + sum(numbers))
if __name__ == '__main__':
main()
|
43014808916570fd49e9d1551a9024b419b98d7f
|
AleBark/Python-Basics
|
/list_05/ex_07.py
| 641 | 3.890625 | 4 |
# -*- coding: utf-8 -*-
# An algorithm that reads 4 whole numbers and calculates the sum of those that are even.
def main():
input_list = []
print("----------")
for idx in range(1, 4):
integer = input("Input: ")
if input_is_a_valid_int(integer):
if int(integer) % 2 == 0:
input_list.append(int(integer))
else:
break
print(sum(input_list))
def input_is_a_valid_int(input):
try:
int(input)
return True
except ValueError:
print("Invalid input\n")
return False
if __name__ == '__main__':
while True:
main()
|
33a0ade36fd60e1fa50891c0074e1e0e41b90c4d
|
khaldi505/holbertonschool-web_back_end
|
/0x02-python_async_comprehension/0-async_generator.py
| 303 | 3.5625 | 4 |
#!/usr/bin/env python3
"""
async_generator module
"""
import asyncio
import random
from typing import Generator
async def async_generator() -> Generator[float, None, None]:
"""
async_generator
"""
for x in range(10):
await asyncio.sleep(1)
yield(random.uniform(0, 10))
|
7936553f10a8ee301aa0dd3067ae525140f7f524
|
f-sanges/UDEMY_EXERCISES_The_Complete_Python_Course_Go_From_Beginner_To_Advanced
|
/find_method.py
| 995 | 4.03125 | 4 |
value = "cat picture is cat picture plus picture"
# Find first index of the string
i = value.find("picture")
print("First occurrence of picture: " + str(i))
c = value.rfind("picture") # rfind
print("rfind di picture: " + str(c))
# Find first index of this string after previous index
b = value.find("picture", i + 1)
print("Second occurrence of picture: ", b)
# loop to find the index of every value in a string
location = 0
while True:
location = value.find("picture", location + 1)
if location == -1:
break
print("location: ", location)
# Other method to loop to find the index of every value in a string
value2 = "cat picture is cat picture plus picture"
locazione = len(value2)
print("length of value2: ", locazione)
while True:
locazione = value2.rfind("picture", 0, locazione)
if locazione == -1:
break
print("locazione: ", locazione)
# print(value.find("daog"))
if value.find("dog") == -1:
print("not found")
else:
print("found")
|
732c6772e1de80cd4248d8f6d72b9ab644941033
|
soumasish/leetcodely
|
/python/integer_to_english_words.py
| 1,403 | 3.609375 | 4 |
"""Created by sgoswami on 7/4/17."""
"""Convert a non-negative integer to its english words representation. Given input is guaranteed
to be less than 2^31 - 1."""
class Solution(object):
def __init__(self):
self.units = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven',
'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
self.tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
self.thousands = ['', 'Thousand', 'Million', 'Billion']
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "Zero"
res = ""
for i in range(len(self.thousands)):
if num % 1000 != 0:
res = self.helper(num % 1000) + self.thousands[i] + " " + res
num //= 1000
return res.strip()
def helper(self, num):
if num == 0:
return ""
elif num < 20:
return self.units[num] + " "
elif num < 100:
return self.tens[num // 10] + " " + self.helper(num % 10)
else:
return self.units[num // 100] + " Hundred " + self.helper(num % 100)
if __name__ == '__main__':
solution = Solution()
print(solution.numberToWords(23))
|
3de2b884bdc5c1029195dcddfe2f9ac9e8e76482
|
handaeho/lab_python
|
/scratch11_KNN/ex02_knn_위스콘신.py
| 2,479 | 3.828125 | 4 |
"""
R을 활용한 머신러닝에서 사용한 '위스콘신 대학교의 암 데이터'에 대한, scikit-learn 패키지 활용
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
if __name__ == '__main__':
# 1. csv 파일을 DataFrame으로
dataset = pd.read_csv('wisc_bc_data.csv')
print(dataset.info())
print(dataset.describe())
print(dataset.head())
# 2. 데이터를 데이터(포인트)와 레이블로 구분
X = dataset.iloc[:, 2:].to_numpy()
Y = dataset.iloc[:, 1].to_numpy()
# 3. train set 8 / test set 2 구성
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
# 4. z-score 표준화
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
for col in range(len(dataset.iloc[0]) - 2):
print(f' X_train 평균 = {X_train[:, col].mean()} / X_train 표준편차 = {X_train[:, col].std()}')
print(f'X_test 평균 = {X_test[:, col].mean()} / X_test 표준편차 = {X_test[:, col].std()}')
# 5. k-nn 분류기 생성
classifier = KNeighborsClassifier(n_neighbors=5) # k 값은 5
# 6. 분류기 학습
classifier.fit(X_train, Y_train)
# 7. 학습한 분류기로 예측
y_pred = classifier.predict(X_test)
print(y_pred)
# 8. 모델 평가 - 혼동 행렬
conf_matrix = confusion_matrix(Y_test, y_pred)
print(conf_matrix)
# [[73 1]
# [ 0 40]]
# 9. 상세 결과 분석
report = classification_report(Y_test, y_pred)
print(report)
# 10. 모델 성능 개선 위한 k값 변화(평균 오차율 분석)
errors = []
for i in range(1, 41):
knn = KNeighborsClassifier(n_neighbors=i) # k값을 1 ~ 40까지 변화 시킴
knn.fit(X_train, Y_train)
pred_i = knn.predict(X_test)
errors.append(np.mean(pred_i != Y_test)) # 예측값(pred_i)과 실제값(Y_test)이 다른 결과의 평균들을 errors 배열에 추가
print(errors)
# 11. k 값 변화에 따른 평균오차율 시각화
plt.plot(range(1, 41), errors, marker='o')
plt.title('Mean Error with K-Value')
plt.xlabel('k-value')
plt.ylabel('mean error')
plt.show()
|
292efa80277d35a69280b7d5c839230e0041fbc9
|
frithjofhoppe/M122_python
|
/fibonacci-2.py
| 274 | 3.84375 | 4 |
def fibonacci2(wert):
if(wert == 0):
return 0
elif(wert == 1):
return 1
else:
return (fibonacci2(wert-1) + fibonacci2(wert-2))
counter = 0
while True:
print (fibonacci2(counter))
counter+=1
if(counter == 25):
break
|
fb0ce579bb1a84d4f311e451c21bfbecdc72f38d
|
Harinarayan14/p97
|
/p97.py
| 882 | 4.1875 | 4 |
# import random for finding a random number
import random;
# Random Number
number = random.randint(1,100);
# Text
print("Number Guessing Game");
print("Guess from 1 to 100");
print("You have 10 chances.");
#Chances
chances =0;
# While Loop
while chances < 10:
# Input
guess = int(input("Enter your guess "))
# Game win
if (guess == number):
print("Congratulation YOU WON!!!")
print("Chances Taken: ")
print(chances)
break
# Game Continue
elif (guess < number):
print("Your guess was low: Guess a number higher than", guess)
else:
print("Your guess was high: Guess a number lower than", guess)
chances += 1
# Score
print("Chances Taken: ")
print(chances)
print("Chances Left: ")
print(10-chances)
# Game Over
if chances >= 10:
print("YOU LOSE!!! The number is", number)
|
c4619c8b6923dd252b1f4af268cd2b6c0867e576
|
mmunsi2/python
|
/pythonic/Code23_2_depth_first_search.py
| 1,306 | 3.546875 | 4 |
from graph import Node, buildGraph
class FoundNodeException(Exception):
pass
def recursiveDepthFirst(node, soughtValue):
try:
recursiveDepthFirstWorker(node, soughtValue, set())
return False
except FoundNodeException:
return True
def recursiveDepthFirstWorker(node, soughtValue, visitedNodes):
if node.value == soughtValue:
raise FoundNodeException()
visitedNodes.add(node)
for adjNode in node.adjacentNodes:
if adjNode not in visitedNodes:
recursiveDepthFirstWorker(adjNode, soughtValue, visitedNodes)
def depthFirst(startingNode, soughtValue):
''' Using a stack. '''
visitedNodes = set()
stack = [startingNode]
while len(stack) > 0:
node = stack.pop()
if node in visitedNodes:
continue
visitedNodes.add(node)
if node.value == soughtValue:
return True
for n in node.adjacentNodes:
if n not in visitedNodes:
stack.append(n)
return False
if __name__ == "__main__":
vertices = ["A", "B", "C", "D", "E", "F"]
edges = [("A","B"), ("B","C"), ("C","E"), ("E","D"), ("E","F"), ("D","B")]
G = buildGraph(vertices, edges)
print recursiveDepthFirst(G, "F")
print recursiveDepthFirst(G, "G")
print depthFirst(G, "F")
print depthFirst(G, "G")
|
dc01cec503f91f0ab52f8e94c59703bfb46e5cd6
|
shen1993/Drone_project
|
/SCVL.py
| 1,341 | 3.53125 | 4 |
from Display import Display
from Mapping import Mapping
import sys
# A String to Boolean method
def str_to_bool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError("Cannot covert '{}' to a bool. arg2 should only be either 'True' or 'False'".format(s))
# The Display method
def display():
is_test_mode = str_to_bool(sys.argv[2])
if sys.argv[3] == 'all':
scan_ID = sys.argv[3]
elif int(sys.argv[3]) in range(0, 33):
scan_ID = sys.argv[3]
else:
raise ValueError(
"Please fill in the third argument with the correct scan ID or 'all' to display all scans")
ds = Display(is_test_mode, scan_ID)
ds.loadFiles()
ds.convert_files()
ds.print_scans()
# the Mapping method
def mapping():
is_test_mode = str_to_bool(sys.argv[2])
map = Mapping(is_test_mode)
map.draw_lines()
map.grouping()
map.output_result()
map.print_scans()
# Check if all arguments are typed in and run the program
try:
if sys.argv[1] == 'Display':
display()
elif sys.argv[1] == 'Mapping':
mapping()
else:
raise ValueError("Please fill in the first argument with 'Display' or 'Mapping'")
except IndexError:
print("Please fill in all the required arguments to continue.")
|
273f9fc8723c472bef60f332ef35272cb94645d5
|
yz9527-1/1YZ
|
/pycharm/Practice/python 3自学/4-变量.py
| 758 | 3.96875 | 4 |
# 这里介绍 变量
# 变量可以是数字
var1 = 5
print(var1)
# 变量可以是字符
var2 = 'hello'
print(var2)
# 变量可以是运算表达式
var3 = 5 + 67
print(var3)
# 变量可以是函数
var4 = print('hello Python 3')
"""
总结:
变量的命名规范
1、变量名可以包括字母、数字、下划线,但是数字不能做为开头。例如:name1是合法变量名,而1name就不可以。
2、系统关键字不能做变量名使用
3、除了下划线之个,其它符号不能做为变量名使用
4、Python的变量名是除分大小写的,例如:name和Name就是两个变量名,而非相同变量
"""
from pycharm.Practice.common.Sort import Sort
list1=[1,9,15,84,75,65,31,26,94,57]
print(Sort.quick_sort(list1))
|
bafa00b2527292e22de9bd044e6fe329ced8253e
|
TonyBiz9999/python
|
/16. Day 16/main.py
| 217 | 3.5 | 4 |
from turtle import Turtle, Screen
timmy = Turtle()
print(timmy)
timmy.shape("turtle")
timmy.color("red")
timmy.forward(100)
timmy.shapesize(3)
my_screen = Screen()
print(my_screen.canvheight)
my_screen.exitonclick()
|
7cc8b8a9918c46dd2055fc411d64889d1cfcc323
|
pratikskarnik/Leetcode_Solutions
|
/Palindrome Number.py
| 267 | 3.609375 | 4 |
class Solution:
def isPalindrome(self, x: int) -> bool:
y=0
x1=x
while(x>0):
y=y*10+x%10
x=x//10
print(y)
if y==x1:
return True
else:
return False
|
b5bde8ca78ae29233ddc769ef32d42a558e81e0d
|
AbhayKD/jasper-Modules
|
/stopwatch/stopwatch.py
| 197 | 3.65625 | 4 |
import time
b=0
e=0
#t = raw_input("Enter:")
while True:
t = raw_input("Enter:")
if t == "b":
b = time.time()
elif t == "e":
e = time.time()
print str(e-b)[0:3]
|
52fa4a4e67726d6ecbfe5798cf8e57b908861ddf
|
ndvssankar/cspp1-assignments
|
/M6/p3/digit_product.py
| 653 | 4.125 | 4 |
'''
Given a number int_input, find the product of all the digits
example:
input: 123
output: 6
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
int_input = int(input())
product = 1
flag = False
if int_input < 0:
flag = True
int_input = -int_input
if int_input == 0:
print(0)
else:
while int_input != 0:
rem = int_input % 10
product = product * rem
int_input = int_input // 10
if flag:
print(-product)
else:
print(product)
if __name__ == "__main__":
main()
|
80c035b4bde4a2006e56b954046929f4143181e3
|
quangdat191/tranquangdat-fundamental-c4t
|
/Session4/Homework_Lesson4/[8].py
| 230 | 3.71875 | 4 |
# a = input("Nhap tu ")
# import string
# for i in a:
# if 97 <= ord(i) <= 122:
# x = ord(i)-32
# for y in string.ascii_uppercase:
# if ord(y) == x:
# a = a.replace(i, y)
# print(a)
|
dbb9003897c6280a9d11d8e3d34c70c52be8cabe
|
ICS3U-Programming-Layla-M/Unit3-07-Python
|
/dating.py
| 1,041 | 4.21875 | 4 |
#!/usr/bin/env python3
# Created by: Layla Michel
# Created on: May 17, 2021
# This program asks the user to input their age
# and displays whether they are eligible to date
# some grandparents' grandchild.
import constants
def main():
try:
# get the user's age
user_age_as_string = input("Enter your age: ")
user_age_as_int = int(user_age_as_string)
except ValueError:
# error message
print("{} is not a valid number.". format(user_age_as_string))
else:
# display whether they are eligible to date or not
if user_age_as_int > constants.MIN_AGE and\
user_age_as_int < constants.MAX_AGE:
print("You are allowed to date our grandchild.")
elif user_age_as_int >= constants.MAX_AGE:
print("You are too old for our grandchild.")
elif user_age_as_int < 0:
print("Age cannot be a negative number.")
else:
print("You are too young for our grandchild.")
if __name__ == "__main__":
main()
|
e1bc46feaa4e43d6b82216fd2b10e4a57d0dba7a
|
sincerehwh/Arithmetic
|
/liner_list_linked.py
| 10,537 | 3.828125 | 4 |
# 单链表:
#
# ┌───┐
# │ p ├┐
# └───┘│
# │ ┌─────┬──────┐ ┌──────┬──────┐ ┌──────┬──────┐ ┌──────┬──────┐
# └▶│ elem│ next ├────▶│ elem │ next │... │ elem │ next ├────▶│ elem │ blank│
# └─────┴──────┘ └──────┴──────┘ └──────┴──────┘ └──────┴──────┘
#
# 单向链表节点
class SingleDirectionNode(object):
def __init__(self,element,):
self.element = element
self.next = None
# 单向链表
class SingleDirectionLinkList(object):
def __init__(self,node=None):
self.__head = node
def is_empty(self):
return self.__head is None
def length(self):
current = self.__head # 游标
length = 0 # 数据数量
while current != None:
length += 1
current = current.next
return length
def travel(self):
current = self.__head
while current != None:
print(current.element,end = " ")
current = current.next
def add(self,item):
node = SingleDirectionNode(item)
node.next = self.__head
self.__head = node
def append(self,item):
node = SingleDirectionNode(item)
if self.is_empty():
self.__head = node
else:
current = self.__head
while current.next != None:
current = current.next
current.next = node
def insert(self,position,item):
if position <= 0 :
self.add(item)
elif position >= (self.length()-1):
self.append(item)
else:
node = SingleDirectionNode(item)
current = self.__head
count = 0
while count < (position-1):
count += 1
current = current.next
# 循环退出,current指向pos-1
node.next = current.next
current.next = node
def remove(self,item):
current = self.__head
pre = None
while current != None:
if current.element is item:
if current == self.__head:
self.__head = current.next
else:
pre.next = current.next
break
else:
pre = current
current = current.next
def search(self,item):
current = self.__head
while current==None :
if current.element == item:
return True
else:
cur= cur.next
return False
# 双向链表:
# ┌───┐ ┌───┬────────┬───┬───▶┌───┬────────┬───┬───▶┌───┬────────┬───┐
# │ p ├───▶│nil│ element│ n │ │ p │ element│ n │ │ p │ element│nil│
# └───┘ └───┴────────┴───┘◀───┴───┴────────┴───┘◀───┴───┴────────┴───┘
#
# 双向链表节点
class DoubleDirectionNode(object):
def __init__(self,item):
self.element = item
self.next = None
self.prev = None
# 双向链表
class DoubleDirectionLinkList(object):
def __init__(self,node=None):
self.__head = node
def is_empty(self):
return self.__head is None
def length(self):
current = self.__head # 游标
length = 0 # 数据数量
while current != None:
length += 1
current = current.next
return length
def travel(self):
current = self.__head
while current != None:
print(current.element,end = " ")
current = current.next
def add(self,item):
node = DoubleDirectionNode(item)
if self.is_empty():
self.__head = node
else:
node.next = self.__head
self.__head.prev = node
self.__head = node
def append(self,item):
node = DoubleDirectionNode(item)
if self.is_empty():
self.__head = node
else:
current = self.__head
while current.next != None:
current = current.next
current.next = node
node.prev = current
def insert(self,position,item):
if position <= 0:
self.add(item)
elif position > (self.length()-1):
self.append(item)
else:
node = DoubleDirectionNode(item)
current = self.__head
count = 0
while count < (position-1):
count += 1
current = current.next
node.prev = current
node.next = current.next
current.next.prev = node
current.next = node
def remove(self,item):
pass
# if self.is_empty():
# return
# else:
# current = self.__head
# if current.element == item:
# if current.next == None:
# self.__head = None
# else:
# current.next.prev = None
# self.__head = current.next
# return
# while current != None:
# if current.element == item:
# current.prev.next = current.next
# current.next.prev = current.prev
# break
# current = current.next
def search(self,item):
current = self.__head
while current != None:
if current.item == item:
return True
current = current.next
return False
# 单向循环链表
# ┌───┐ │───────────────────────────────────────────────────────────
# │ p ├┐ │ │
# └───┘│ ▼ │
# │ ┌─────┬──────┐ ┌──────┬──────┐ ┌──────┬──────┐ ┌──────┬──┴───┐
# └▶│ elem│ next ├────▶│ elem │ next │... │ elem │ next ├────▶│ elem │ head │
# └─────┴──────┘ └──────┴──────┘ └──────┴──────┘ └──────┴──────┘
class Node(object):
"""节点"""
def __init__(self, item):
self.item = item
self.next = None
class SinCycLinkedlist(object):
"""单向循环链表"""
def __init__(self):
self._head = None
def is_empty(self):
"""判断链表是否为空"""
return self._head == None
def length(self):
"""返回链表的长度"""
# 如果链表为空,返回长度0
if self.is_empty():
return 0
count = 1
cur = self._head
while cur.next != self._head:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历链表"""
if self.is_empty():
return
cur = self._head
print(cur.item)
while cur.next != self._head:
cur = cur.next
print(cur.item)
print("")
def add(self, item):
"""头部添加节点"""
node = Node(item)
if self.is_empty():
self._head = node
node.next = self._head
else:
#添加的节点指向_head
node.next = self._head
# 移到链表尾部,将尾部节点的next指向node
cur = self._head
while cur.next != self._head:
cur = cur.next
cur.next = node
#_head指向添加node的
self._head = node
def append(self, item):
"""尾部添加节点"""
node = Node(item)
if self.is_empty():
self._head = node
node.next = self._head
else:
# 移到链表尾部
cur = self._head
while cur.next != self._head:
cur = cur.next
# 将尾节点指向node
cur.next = node
# 将node指向头节点_head
node.next = self._head
def insert(self, pos, item):
"""在指定位置添加节点"""
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
cur = self._head
count = 0
# 移动到指定位置的前一个位置
while count < (pos-1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
"""删除一个节点"""
# 若链表为空,则直接返回
if self.is_empty():
return
# 将cur指向头节点
cur = self._head
pre = None
# 若头节点的元素就是要查找的元素item
if cur.item == item:
# 如果链表不止一个节点
if cur.next != self._head:
# 先找到尾节点,将尾节点的next指向第二个节点
while cur.next != self._head:
cur = cur.next
# cur指向了尾节点
cur.next = self._head.next
self._head = self._head.next
else:
# 链表只有一个节点
self._head = None
else:
pre = self._head
# 第一个节点不是要删除的
while cur.next != self._head:
# 找到了要删除的元素
if cur.item == item:
# 删除
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
# cur 指向尾节点
if cur.item == item:
# 尾部删除
pre.next = cur.next
def search(self, item):
"""查找节点是否存在"""
if self.is_empty():
return False
cur = self._head
if cur.item == item:
return True
while cur.next != self._head:
cur = cur.next
if cur.item == item:
return True
return False
if __name__ == "__main__":
ll = SinCycLinkedlist()
ll.add(1)
ll.add(2)
ll.append(3)
ll.insert(2, 4)
ll.insert(4, 5)
ll.insert(0, 6)
print("length:",ll.length())
ll.travel()
print(ll.search(3))
print(ll.search(7))
ll.remove(1)
print("length:",ll.length())
ll.travel()
|
8ac08f013ef34d6752c4fd5ebdb730be26a890a3
|
shags07/python
|
/INC0011009_sagar_q18.py
| 308 | 3.703125 | 4 |
def XorLBit(int1,int2):
list1=[]
list2=[]
int1=list1.append(int1)
int2=list2.append(int2)
for value in list1:
a=list1.reverse()
for value in list2:
b=list2.reverse()
return a
return b
return ((a | b) & (~a | ~b))
print (XorLBit(1011,101))
|
9c702a2d490e8d63b3c97d97ea579a893ca7a8eb
|
Labannya969/Hackerrank-practice
|
/python/04. Sets/004. Set add().py
| 169 | 3.859375 | 4 |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n= int(input())
s=set()
for i in range(1,n+1):
country= input()
s.add(country)
print(len(s))
|
711dba79b76ea33db4e54f253dc02fcdb753eb1e
|
fanxiao168/pythonStudy
|
/AIDStudy/01-PythonBase/day04/homework/demo04.py
| 100 | 3.65625 | 4 |
'''
str编码
'''
# 字 --> 数
num = ord('a')
print(num)
# 数 --->字
str1 = chr(97)
print(str1)
|
fcc21665b05b09a5627b42d490aff37ec2cdd2e6
|
Tyler-Henson/Python-Crash-Course-chapter-9
|
/privileges.py
| 743 | 3.59375 | 4 |
"""
Problem 9-8 of Python Crash Course
"""
import loginAttempts2 as lA2
class Admin(lA2.User):
def __init__(self, first_name, last_name, age, sex,):
super().__init__(first_name, last_name, age, sex)
self.privileges = Privileges()
class Privileges:
def __init__(self):
self.privileges = [
'can add post',
'can delete post',
'can ban user',
]
def show_privileges(self):
print("You have the following privileges:")
for privilege in self.privileges:
print(privilege)
if __name__ == '__main__':
me = Admin('tyler', 'henson', 27, 'm')
me.privileges.show_privileges()
me.describe_user()
|
a5d736a2c61ed86189d2c2ab29f8a87f243e63eb
|
Nithanth/Graduate-Algorithm-
|
/Linked List/092. Reverse Linked List II.py
| 1,276 | 4.0625 | 4 |
"""
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def myprint(self):
print(self.val)
if self.next:
self.next.myprint()
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if (n-m)<=0:
return head
dummy=ListNode(0)
dummy.next=head
point=dummy
for _ in range(m-1):
node=point.next
prev=point.next
cur=prev.next
for _ in range(n-m):
next=cur.next
cur.next=prev
prev=cur
cur=next
point.next.next=cur
point.next=prev
return dummy.next
if __name__ == "__main__":
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
result = Solution().reverseBetween(l1, 2,4)
result.myprint()
|
370b5dba7c50774138693e14c68c3969c28c39c6
|
algebra-det/Python
|
/Iterate_btwn_two.py
| 744 | 3.890625 | 4 |
players = [1,0]
choice = 1
for _ in range(10):
current_player = choice
print(current_player)
choice = players[choice]
print("val")
#OR
val =1
for _ in range(10):
val = 1 -val
print(val)
print("itertools 1")
# OR using itertools import cycle
from itertools import *
myIterator = cycle(range(2))
for _ in range(10):
print(myIterator.__next__())
print("itertools 2")
#OR
for _ in range(10):
print(next(myIterator))
for char in "hello my name is akash chauhan":
print(char,end=",")
print()
x = [1,2,3,4] # iterable
n = cycle(x) # iterator! ..also iterable , iterator are the object which work on iterableef
y = iter(x) # iterator! ..also iterable
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.