blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fc42d01d6b1c0f3401ae9a8ba61b2c3c317c0e71 | nurseybushc/Udacity_IntroToSelfDrivingCars | /Module 2 - Bayesian Thinking/parallel_parking.py | 897 | 3.796875 | 4 | # CODE CELL
#
# Write the park function so that it actually parks your vehicle.
from Car import Car
import time
def park(car):
# TODO: Fix this function!
# currently it just drives back and forth
# Note that the allowed steering angles are
# between -25.0 and 25.0 degrees and the
# allowed values for gas are between -1.0 and 1.0
# back up for 3 seconds
car.steer(20.0)
car.gas(-0.4)
time.sleep(3.5) # note how time.sleep works
# back up for 3 seconds
car.steer(-20.0)
car.gas(-0.4)
time.sleep(2.5) # note how time.sleep works
# forward for 2 seconds
car.steer(8.0)
car.gas(0.25)
time.sleep(2.0)
#car.gas(-0.025)
#time.sleep(0.1)
# back again...
car.gas(-0.1)
time.sleep(1.5)
car.gas(0)
# forward...
#car.gas(0.1)
#time.sleep(1.0)
car = Car()
park(car) |
c8c5b5a547bd49fb679d4e7c722c5f8286bb0aa4 | bherren98/data-science-is-our-passion | /DataCleanlinessLyrics.py | 1,422 | 4.125 | 4 | #Project 1: for cleaning the data for lyrical data
import pandas as pd
import numpy as np
def main():
myData = pd.read_csv('LyricData.csv', encoding='latin1') #reading csv file directly into panda object
missingValues(myData) #call to find the missing values of the pandas dataframe
def missingValues(myData):
for i in list(myData.columns.values): #iterate through each column
print("The fraction of missing values for " + str(i) + " is: " + str(columnValues(myData, i)/len(myData)) + "\n") #print the fraction of missing values for each column
print("The fraction of noise values are: " + str(noiseValues(myData)/(len(myData)*3))) #print the fraction of noise values in the dataframe
#missingValues
def columnValues(myData, column): #pass in the dataFrame and the column name
count = 0
for i in myData[column]: #for each item in the column
if i == "": #if the item is empty
count = count + 1 #add 1 to count
return count #return the count
def noiseValues(myData):
noisecount = 0
for index, row in myData.iterrows(): #iterate through each row
for item in row.iteritems(): #iterate through each item in the row
if type(item) != tuple: #if the item is not equal to a tuple
noisecount = noisecount + 1 #increment the noisecount by 1
return noisecount #return the noisecount
#columnValues
main()
|
a2eb2ddca67ae4ebc1844eff7aec36f2e6adfe37 | YaniLozanov/Software-University | /Python/PyCharm/02.Simple Calculations/09. Celsius to Fahrenheit.py | 343 | 4.3125 | 4 | # Problem:
# Write a program that reads degrees on the Celsius scale (° C) and converts them to degrees Fahrenheit (° F).
# Look for an appropriate formula on the Internet to make the calculations.
# Round the score to 2 decimal places.
celsius = float(input())
fahrenheit = celsius * 9/5 + 32
print(float("{0:.2f}".format(fahrenheit)))
|
59ddfaebf0a81f46c28fb72b0445a4533899120c | FelpsFon/curso_python | /1/matematica.py | 96 | 3.59375 | 4 | numero1 = 20
numero2 = 2
resultado = (numero1-numero2)**numero2*6
resultado = 20+3
print(22%5) |
6955a27ab909bd7a55235829d2eb3390cbdb75f8 | rekikhaile/Python-Programs | /4 file processing and list/list_examples.py | 828 | 4.28125 | 4 | # Initialize
my_list = []
print(my_list)
my_list = list()
print(my_list)
## Add element to the end
my_list.append(5)
print(my_list)
my_list.append(3)
print(my_list)
# notice, list can contain various types
my_list.append('Im a string')
print(my_list)
## more operations on lists
my_list.remove('Im a string')
print(my_list)
print(my_list.index(5))
last = my_list.pop()
print(last)
my_list.insert(1, 10)
print(my_list)
print([1, 1, 2, 1, 3].count(1))
## built-in functions
# inplace
my_list.reverse()
my_list.sort()
# with a return value
my_list_copy = sorted(my_list)
my_list_reversed = reversed(my_list)
n = sum(my_list)
print('sum is', n)
my_max = max(my_list)
my_min = min(my_list)
print ('max is %s, min is %s.' % (my_max, my_min))
## list addition
print([2, 3, 4] + [5, 9, 8])
## check the documentation for more
|
19e092c8f33e2c1f43d577a2c11049ac923a1b91 | claudiosouzabrito/UFPB | /PO/teste.py | 68 | 3.578125 | 4 | a = ['a', 'b', 'c', 'd', 'e']
b = [1,0,1,1,0]
print(a[i] for i in a) |
386a0ce6fd362f09cefc33394e584fec92b7aa5e | MontyPy1212/IronAnne | /Labs/07_Pandas/Old Files/Pandas Lab.py | 6,163 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 17 11:11:47 2021
@author: Annie
"""
li
#Activity 1
#Pandas official documentation: https://pandas.pydata.org/docs/index.html
#1. Aggregate data into one Data Frame using Pandas.
import pandas as pd
print(pd.__version__)
insurance_df = pd.read_csv('/Users/Annie/Documents/GitHub/IronAnne/Labs/Pandas/file1.csv')
print(insurance_df)
insurance_df_two = pd.read_csv('/Users/Annie/Documents/GitHub/IronAnne/Labs/Pandas/file2.csv')
print(insurance_df_two)
#Are they the same? If no, then move on
print(pd.DataFrame.equals(insurance_df, insurance_df_two))
#Check if columns are the same?
#sometimes you have to rearrange columns, but Pandas is recognizing them automatically
print(insurance_df.columns)
print(insurance_df_two.columns)
# Data blending
insurance_df_all = pd.concat([insurance_df, insurance_df_two], axis=0, ignore_index=True)
print(insurance_df_all)
"""
column_names = file1.columns
data = pd.DataFrame(columns=column_names)
data = pd.concat([data,file1, file2], axis=0)
data.shape
"""
#2. Deleting and rearranging columns (https://www.educative.io/edpresso/how-to-delete-a-column-in-pandas)
#2.1. Delete the column "customer" as it is only a unique identifier for each row of data
"""Why do we have to kill the unique identifier?"""
insurance_df_all.drop(columns="Customer", inplace=True)
print(insurance_df_all)
#OR del df['customer']
#2.2. Standardizing header names
# display the dataframe head
print(insurance_df_all.head(10))
# settings to display all columns
pd.get_option("display.max_columns")
pd.set_option("display.max_columns", None)
#2.2.1. Convert column header to string
#df.columns = df.columns.astype("str")
#2.2.2. Format column header with cases
#Index.str method
#df.columns = df.columns.str.upper()
insurance_df_all.columns = insurance_df_all.columns.str.lower()
print(insurance_df_all)
###2.2.3. Rename columns
insurance_df_all_new = insurance_df_all.rename(columns = {'st': 'state'}, inplace = False)
print(insurance_df_all_new)
#Index.map method
#df.columns = df.columns.map(str.upper)
#Python built-in map method
#df.columns = map(str.upper, df.columns)
#2.2.3. Replace characters in column header
#df.columns = df.columns.map(lambda x : x.replace("-", "_").replace(" ", "_"))
# Or
#df.columns = map(lambda x : x.replace("-", "_").replace(" ", "_"), df.columns)
#2.2.4. Add prefix or suffix to column header
#adding prefix with "Label_"
#df.columns = df.columns.map(lambda x : "Label_" + x)
#adding suffix with "_Col"
#df.columns = df.columns.map(lambda x : x + "_Col")
#2.3. Reorder columns
#provide within the brackets a list with the new column name order
#df[ list_of_columns ]
"""
#3. Explore
df.head()
#range of values for numerical columns
df.describe()
#same object column use
df[‘colname’].value_counts()
#get unique values
df[‘colnames’].unique()
"""
#3.1. Check Data Type
#Check the data types of all the columns and fix the incorrect ones (for ex. customer lifetime value and number of complaints)
check_column_type = insurance_df_all_new.dtypes
print(check_column_type)
#Fix column CLV
##Convert type with astype conversion method --> works only if data is clean and has no symbols (e. g. $) and if you want to convert a number to string
#insurance_df_all_new["customer lifetime value"].astype('str')
#insurance_df_all_new['customer lifetime value'] = pd.to_numeric(insurance_df_all_new['customer lifetime value'])
def convert_column_clv(i):
if i != i:
pass
i = str(i).replace("%", "")
return float(i)/100
#remove_percent = [i.replace('%','') for i in insurance_df_all_new["customer lifetime value"]]
#print(remove_percent[0:10])
insurance_df_all_new["customer lifetime value"] = insurance_df_all_new["customer lifetime value"].apply(convert_column_clv)
print(insurance_df_all_new["customer lifetime value"].head(10))
#test = insurance_df_all_new['customer lifetime value'].apply(lambda x: x.replace('%', '')).astype('float') / 100
def convert_column_complaints(i):
if i != i:
return 0
i = str(i)
return int(i[2])
insurance_df_all_new["number of open complaints"] = insurance_df_all_new["number of open complaints"].apply(convert_column_complaints)
print(insurance_df_all_new["number of open complaints"].head(100))
#Removing duplicates
print(insurance_df_all_new.drop_duplicates())
#4. Filtering data and Correcting typos
#4.1. State column
print(insurance_df_all_new["state"].value_counts())
"""
def update_column_state(i):
type1_replace = ["Cali", "California"]
for n in type1_replace:
i = str(i).replace(n , "California")
return i
"""
def update_column_state(i):
if i != i:
pass
if str(i).endswith("li") == True:
i = str(i).replace("Cali", "California")
i = str(i).replace("AZ", "Arizona").replace("WA", "Washington")
return str(i)
insurance_df_all_new["state"] = insurance_df_all_new["state"].apply(update_column_state)
print(insurance_df_all_new["state"].head(20))
print(insurance_df_all_new["state"].value_counts())
#4.2. Gender column
print(insurance_df_all_new["gender"].value_counts())
def group
"""
def update_column_gender(i):
if i != i:
pass
i = str(i).replace("Cali", "California").replace("AZ", "Arizona").replace("WA", "Washington")
return str(i)
insurance_df_all_new["state"] = insurance_df_all_new["state"].apply(update_column_state)
print(insurance_df_all_new["state"].head(20))
print(insurance_df_all_new["state"].value_counts())
#4. Filtering data and Correcting typos
df[condition]
#4.1. Filter the data in state and gender column to standardize the texts in those columns
#6. Replacing null values – Replace missing values with means of the column (for numerical columns)
#Finding Null Values
isna()
isnull()
#Filling NAs
fillna()
#Categorial values - With categorical column types, you can get how many values you have of each applying the method: value_counts() to the corresponding column
""" |
c8809a05f121b19939ce9cb7c5fd033c4535bb9c | swozny13/Python-Introduction | /gui/calculator.py | 2,289 | 3.578125 | 4 | from tkinter import *
class Calculator(Frame):
def __init__(self, master):
super(Calculator, self).__init__(master)
self.grid()
self.create_widgets()
# self.btn7 = 7
def create_widgets(self):
# results
self.results = Text(self, height=3, width=23).grid(row=0, column=0, columnspan=4, sticky=W)
# digits
self.btn7 = Button(self, text=7, height=3, width=5).grid(row=1, column=0, sticky=W)
self.btn8 = Button(self, text=8, height=3, width=5).grid(row=1, column=1, sticky=W)
self.btn9 = Button(self, text=9, height=3, width=5).grid(row=1, column=2, sticky=W)
self.btn4 = Button(self, text=4, height=3, width=5).grid(row=2, column=0, sticky=W)
self.btn5 = Button(self, text=5, height=3, width=5).grid(row=2, column=1, sticky=W)
self.btn6 = Button(self, text=6, height=3, width=5).grid(row=2, column=2, sticky=W)
self.btn1 = Button(self, text=1, height=3, width=5).grid(row=3, column=0, sticky=W)
self.btn2 = Button(self, text=2, height=3, width=5).grid(row=3, column=1, sticky=W)
self.btn3 = Button(self, text=3, height=3, width=5).grid(row=3, column=2, sticky=W)
self.btn0 = Button(self, text=0, height=3, width=5).grid(row=4, column=0, sticky=W)
# point
self.dot = Button(self, text=".", height=3, width=5).grid(row=4, column=1, sticky=W)
# remove
self.delete = Button(self, text="C", height=3, width=5).grid(row=4, column=2, sticky=W)
# functions
self.addition = Button(self, text="+", height=3, width=5).grid(row=1, column=3, sticky=W)
self.subtraction = Button(self, text="-", height=3, width=5).grid(row=2, column=3, sticky=W)
self.multiplication = Button(self, text="*", height=3, width=5).grid(row=3, column=3, sticky=W)
self.division = Button(self, text="/", height=3, width=5).grid(row=4, column=3, sticky=W)
# equal
self.equals = Button(self, text="=", height=3, width=25).grid(row=5, column=0,
columnspan=4,
sticky=W)
window = Tk()
window.title("CALCULATOR")
app = Calculator(window)
app.mainloop()
|
cdfc8f7b424c29e430db0abb60a1e6f43137f70e | oayllon-bf/pythoncourse | /session_4/example_2.py | 546 | 3.828125 | 4 | """
This is the header of the python file
company name: pythoncourse
"""
# csv reader example
import pandas as pd
counts_dict = {}
# Iterate over the file chunk by chunk
for chunk in pd.read_csv("iris.csv", chunksize=10):
# Iterate over the "species" column in DataFrame
for entry in chunk["species"]:
if entry in counts_dict.keys():
counts_dict[entry] += 1
else:
counts_dict[entry] = 1
# for entry in chunk.values:
# for item in entry:
# print(item)
print(counts_dict)
|
1695d8516163e5dc3617d0b9f67c900cf9358c44 | PiterPG00/Lista1 | /Quest3.py | 297 | 3.75 | 4 | #PiterPG
divida = float(input("Valor da Divida: "))
atra = int(input("Dias Atrasados: "))
multa = float(input("Valor da Multa por Dia: "))
print("\nValor da Divida R${:.2f} \n\
Dias Atrasados [{}] \n\
Multa de R${:.2f} \n\
Valor Final: R${:.2f}".format(divida,atra,multa,(multa * atra) + divida)) |
41744c74b183c23309de83a8fe1eace51b418b43 | amanda-shlee/tic-tac-toe-python | /tictactoe_computer.py | 3,150 | 3.828125 | 4 | import random
board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
current_player = "X"
count = 0
winner = False
def print_board():
for rows in reversed(board):
print(rows)
print_board()
def valid_check(x, y):
if -1 < x < 3 and -1 < y < 3:
if board[y][x] == "_":
return True
else:
print("space taken")
else:
print("input between 0 and 2")
def winner_player():
win_combos = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)]
]
for combo in win_combos:
win_condition = []
for i in combo:
win_condition.append(board[i[0]][i[1]])
win_condition = "".join(win_condition)
if win_condition == "XXX":
print("X")
return True
elif win_condition == "OOO":
print("O")
return True
elif count == 9:
print("draw")
return True
def computer_smart():
win_combos = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)]
]
new_coords = []
for combo in win_combos:
win_condition = []
for i in combo:
win_condition.append(board[i[0]][i[1]])
win_condition = "".join(win_condition)
if win_condition.count('_') == 1:
if win_condition.count("X") == 2:
new_coords = combo[win_condition.index('_')]
print(new_coords)
elif win_condition.count("O") == 2:
return(combo[win_condition.index('_')])
# elif new_coords == []:
# new_coords = [random.randint(0, 2), random.randint(0, 2)]
elif ((win_condition.count('_') > 1) and new_coords == []):
new_coords = [random.randint(0, 2), random.randint(0, 2)]
# if new_coords == []:
# new_coords = [random.randint(0, 2), random.randint(0, 2)]
return new_coords
def change_player(player):
global current_player
if player == "X":
current_player = "O"
else:
current_player = "X"
def gameplay(X, Y):
global count
if valid_check(X, Y):
board[Y][X] = current_player
print_board()
count += 1
if winner_player():
return True
change_player(current_player)
while not winner:
print(f"Current Player is {current_player}")
if current_player == 'X':
X = int(input("Input X coordinate"))
Y = int(input("Input Y coordinate"))
if gameplay(X, Y):
winner = True
break
else:
com_coords = computer_smart()
X = com_coords[1]
Y = com_coords[0]
if gameplay(X, Y):
winner = True
break
|
388b31973205c3578083769ae3ed4a745f677366 | NataliaNasu/cursoemvideo-python3 | /PacoteDownload/ex058b.py | 555 | 3.84375 | 4 | #outra maneira, com indicações de mais perto...
from random import randint
print("*** \033[31mADIVINHE O NÚMERO\033[m ***")
pc = randint(0, 10)
acertou = False
maior = menor = tentativas = 0
while not acertou:
jogador = int(input('Número? '))
tentativas += 1
if jogador == pc:
acertou = True
else:
if jogador < pc:
print(f'Tente um número MAIOR...')
elif jogador > pc:
print('Tente um número MENOR...')
print(f'\033[31mPARABÉNS!\033[m')
print(f'Acertou com {tentativas} tentativas!') |
56431d4f85c7c70304b4d1cfb9069d65c5357aa0 | sabrina-boby/practice_some-python | /overriding.py | 264 | 3.5 | 4 |
class Phone:
# def __init__(self):
# print("I am from phone class")
def name(self):
print("my name is boby")
class samsung(Phone):
def __init__(self):
super().name()
print("i am from samsung class")
s=samsung()
|
913278c01669fbf8ca0732a01877a2561221da68 | ajayvenkat10/Competitive | /adaschool.py | 186 | 3.671875 | 4 | t = int(input())
for i in range(t):
line = input().split()
a = int(line[0])
b = int(line[1])
if(a%2==0 or b%2==0):
print("YES")
else:
print("NO")
|
391c1d6b8c48a2f216b18476a66b7038da65f27d | pritishyuvraj/CompetitiveProgramming | /binarySearch/Mortgage.py | 1,510 | 3.78125 | 4 | #Question: TopCoder Statistics (Top Coder Statistics)
#Name: Mortgage
#Link: https://community.topcoder.com/stat?c=problem_statement&pm=2427&rd=4765
#Solution: O(N log n)
#Author: Pritish Yuvraj
import math
class Mortgage:
def __init__(self):
pass
def monthlyPayment(self, loan, interest, term, x = None):
print "\n\nloan ->", loan
print "interest ->", interest/10.0
print "term (in months) ->", term*12
#print self.check(loan, float(interest)/10.0, term, x)
print self.binarySearch(loan, float(interest)/10.0, term)
def binarySearch(self, loan, interest, term):
low = 0
high = loan
while low < high:
mid = low + (high - low)/2
if self.check(loan, interest, term, mid):
#True case
high = mid
else:
#False Case
low = mid + 1
if self.check(loan, interest, term, low):
return low
else:
return -1
def check(self, loan, interest, term, x):
#print "start-> ", loan, x
for i in xrange(term*12 - 1):
loan = loan - x
#print "step -> ", i, loan, x, (1 + (float(interest)/float(12*100)))
loan = math.ceil(loan * (1 + (float(interest)/float(12*100))))
#print "step -> ", i, loan
if loan <= 0: return True
if loan <= x:
return True
return False
if __name__ == '__main__':
mt = Mortgage()
mt.monthlyPayment(1000, 50, 1, 86)
mt.monthlyPayment(1000000, 1000000, 1000, 988143)
mt.monthlyPayment(2000000000, 6000, 1, 671844808)
mt.monthlyPayment(1000000, 129, 30, 10868)
mt.monthlyPayment(1999999999, 1000000, 1, 1976284585)
|
aa55af77dd180538db028bc2c45bf2e33dfd725e | hvr9/lab | /L4.ThresholdValue.py | 1,588 | 4.125 | 4 | """Harsha vardhan reddy
121910313001
Matrix to SparseMatrix using functions and taking input from user"""
#input
def input_matrix():
r= int(input("Enter the number of rows: ")) #size of row
c = int(input("Enter the number of columns: ")) #size of col
matrix = []
#taking in elements
print("Enter elements: ")
for i in range(r):
a =[]
for j in range(c):
k = int(input())
a.append(k)
matrix.append(a)
return matrix
#printing elements
def displaymatrix(matrix):
for i in matrix:
for j in i:
print(j, end=" ")
print()
#SparseMatrix
def sparseMatrix(matrix):
#threshold value
l = int(input("Enter threshold value: "))
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] <l+1:
matrix[i][j] = 0
sparsematrix = [] #declare empty list
#looping and checking for non-zero elements
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
temp=[] #temporary list
temp.append(i) #adding row index
temp.append(j) # adding column index
temp.append(matrix[i][j]) #value of tht non-zero element
sparsematrix.append(temp)
#display sparsematrix
print("\nSparseMatrix:")
displaymatrix(sparsematrix)
x= input_matrix()
print("Given Matrix: ")
displaymatrix(x)
#conversion
sparseMatrix(x)
|
f368c92c05d17dc1155d4fa35825d45cea14ef59 | cuyu/leetcode | /225.用队列实现栈.py | 2,043 | 3.9375 | 4 | #
# @lc app=leetcode.cn id=225 lang=python3
#
# [225] 用队列实现栈
#
from collections import deque
# @lc code=start
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self._in_queue = deque()
self._out_queue = deque()
self._top_in = True
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
if self._top_in:
self._in_queue.append(x)
while len(self._in_queue) != 1:
self._out_queue.append(self._in_queue.popleft())
else:
self._out_queue.append(x)
while len(self._out_queue) != 1:
self._in_queue.append(self._out_queue.popleft())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
if self._top_in:
r = self._in_queue.popleft()
if len(self._out_queue) > 0:
while len(self._out_queue) != 1:
self._in_queue.append(self._out_queue.popleft())
else:
r = self._out_queue.popleft()
if len(self._in_queue) > 0:
while len(self._in_queue) != 1:
self._out_queue.append(self._in_queue.popleft())
self._top_in = not self._top_in
return r
def top(self) -> int:
"""
Get the top element.
"""
if self._top_in:
return self._in_queue[0]
else:
return self._out_queue[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self._in_queue) == 0 and len(self._out_queue) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
# @lc code=end
if __name__ == "__main__":
s = MyStack()
s.push(1)
s.push(2)
s.push(3)
s.pop()
s.pop()
s.pop()
|
aa8a817dc8a9cdfcc63ee555117fdbe89c9d506f | MatthewZheng/UnitsPlease | /unitClass.py | 3,127 | 3.671875 | 4 | #!/usr/bin/python
_author_ = "Matthew Zheng"
_purpose_ = "Sets up the unit class"
class Unit:
'''This is a class of lists'''
def __init__(self):
self.baseUnits = ["m", "kg", "A", "s", "K", "mol", "cd", "sr", "rad"]
self.derivedUnits = ["Hz", "N", "Pa", "J", "W", "C", "V", "F", "ohm", "S", "Wb", "T", "H", "°C", "lm", "lx", "Bq", "Gy", "Sv", "kat"]
def baseCheck(self, userList):
'''Converts elements in str list to base units'''
converted = []
for i in (userList):
isSquared = False
unitPreIndex = ""
#checks if it has a carat in the expression
for ind, j in enumerate(list(i)):
if j == "^":
isSquared = True
unitPreIndex = ''.join(list(i)[:ind])
break
#converts non-unary unit to base unit and checks for squared variables
while(i not in (self.baseUnits or self.derivedUnits) and len(list(i)) != 1 and unitPreIndex not in (self.baseUnits or self.derivedUnits) and len(unitPreIndex) != 1):
orgNameList = list(i)
#identify prefix removed
self.idPrefix = orgNameList.pop(0)
i = ''.join(orgNameList)
print("The program removed the prefix %s and converted your unit to it's base unit: %s." % (self.idPrefix, i))
#checks if it is a special unit
if(i not in (self.baseUnits and self.derivedUnits)):
#append in case for special units
break
else:
#append in case for base unit
break
#Appends base unit
if(i in (self.baseUnits or self.derivedUnits) and isSquared == False):
converted.append(i)
elif(isSquared == True):
toAppend = []
numReps = []
#run once to get number of times the unit is squared
for index, val in enumerate(list(i)):
if val == "^":
numStart = index+1
numReps.append(''.join(list(i)[numStart:]))
toAppend.append(''.join(list(i)[:index]))
break
#convert numReps into an int
intReps = int(''.join(numReps))
#append number of units specified by the carat
for l in range (intReps):
if(''.join(toAppend) not in (self.baseUnits or self.derivedUnits)):
print("Your variable %s was not in the commonly used units OR it is a derived unit such as N, newtons -- we will add it to the product regardless." % ''.join(toAppend))
converted.append(''.join(toAppend))
#Exception for special units
else:
print("Your variable %s was not in the commonly used units OR it is a derived unit such as N, newtons -- we will add it to the product regardless." % i)
converted.append(i)
return(converted)
|
3bd14c1a990439011e62d81d440ec4b44b444190 | YinzhanTang/Week-2-Python-Basics | /erroraise.py | 332 | 4 | 4 | price = int(input('Price: '))
while price <= 0:
print ('Declined.Price must be non negative')
price = int(input('Please input again: '))
print ('price accepted ')
population = int(input('Population: '))
while population <= 0:
raise ValuError ('Declined.Population must be non negative')
print ('population accepted')
|
0a509e46940d4bed61b110e5b197e0b45bc0764d | yafeile/Simple_Study | /Simple_Python/standard/decimal/new/decimal_2.py | 141 | 3.5625 | 4 | #! /us/bin/env/python
# -*- coding:utf-8 -*-
import decimal
# Tuple
t = (1,(1,1),-2)
print 'Input :',t
print 'Decimal :',decimal.Decimal(t) |
cae3545a25a77669d3d850b1037a5cc423706796 | christophergeiger3/Tutoring-Pset | /TeachingSet/2BasicOperations.py | 269 | 4 | 4 | """
1. Adding
2. Subtracting
3. Multiplying
4. Dividing
"""
# Do this part in the Python shell
"""
Why doesn't print("Five plus five: " + 5+5) work?
Type casting:
str(), int(), float(), bool(), list(), tuple()
If you don't know what type a value is, do: type()
"""
|
6932166d14f1f7d70aafeb62d811a3ebb51d83a3 | seandlg/liveoverflow | /bin-series/protostar/05-stackfive/exploration/addressrange.py | 138 | 3.703125 | 4 | #!/usr/bin/python
base = 0xbffffdf0
r = range(0xff)
for i in range(-0xff, 0xff+1):
value = base+i
print("0x%X" % value)
|
a0b0562d2889a0c9227975e031ee30df1c1be8f8 | danieltshibangu/Mini-projects | /rps_game.py | 1,934 | 4.375 | 4 | # program lets users play rock paper scissors
#import the random module
import random
# define variables
rock = 1
paper = 2
scissors = 3
player_choice = 0
com_choice = 0
#define limits
CHOICE_LIMIT = 3
# main function will ask for user
# choice and call oppoenent_choice function
# then display the results
def main():
intro()
player_choice = input( "\nEnter your choice: " )
com_choice = random.randint( 1, CHOICE_LIMIT )
com_choice_trans( com_choice )
rps_game( player_choice, com_choice )
print( "\nThe computer chose", com_choice_trans( com_choice ) )
print( rps_game( player_choice, com_choice ) )
# intro function informs player of
# whatr they need to do and win game
def intro():
input( "Press enter to proceed with prompts." )
input( "Welcome to Rock, Paper, Scissors!" )
input( "Your opponent will be COM 1," )
input( "Please enter your choice of 'rock' " +
"'paper' or 'scissors'." )
# com_choice_trans function will equate the
# integer numbers to rock,paper or scissor
def com_choice_trans( com_choice ):
if com_choice == 1:
return "rock"
elif com_choice == 2:
return "paper"
else:
return "scissors"
# rps_game function will initiate the game
# and choose the winner, display results
def rps_game( player_choice, com_choice ):
if player_choice == "rock":
if com_choice == 3:
return "You won!"
elif com_choice == 2:
return "You lost!"
elif player_choice == "paper":
if com_choice == 1:
return "You won!"
elif com_choice == 3:
return "You lost!"
elif player_choice == "scissors":
if com_choice == 2:
return "You won!"
elif com_choice == 1:
return "You lost"
else:
return "It's a tie!!"
#call the main function
main()
# incomplete, no code for game tie
|
09a0733aa76c0e73769c3c0692236634f48a75ef | frederico-prog/python | /Scrips-Python/adivinhacao1.py | 2,569 | 3.703125 | 4 | numero_secreto = 42
total_de_pontos = 1000
nivel = int(input('Selecione o nível para o jogo: \n1- 20 Tentativas \n2- 10 Tentativas \n3- 5 Tentativas \n'))
if nivel == 1:
total_tentativa = 20
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada+1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
elif nivel == 2:
total_tentativa = 10
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada + 1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
else:
total_tentativa = 5
for rodada in range(0, total_tentativa):
print(f'Tentativa {rodada + 1} de {total_tentativa}.')
chute = int(input('Digite o seu número: '))
print(f'Você digitou {chute}.')
acertou = numero_secreto == chute
maior = chute > numero_secreto
menor = chute < numero_secreto
if acertou:
print('Você acertou!')
break
elif maior:
print('Você errou! O seu chute é maior que o número secreto.')
total_de_pontos = total_de_pontos - (chute - numero_secreto)
elif menor:
print('Você errou! O seu chute é menor que o número secreto.')
total_de_pontos = total_de_pontos - (numero_secreto - chute)
print('Fim de jogo!')
print(f'O seu total de pontos foi {total_de_pontos}.')
|
ce563d83554c937323dad1109f77b7b835443ceb | guilhermeribg/pythonexercises | /buzz.py | 80 | 3.75 | 4 | num= int(input("Número "))
if num%5==0:
print("Buzz")
else:
print(num) |
93be8b8aad2b00bb457be8916951cc1d1967a0a2 | Ben-Morrison/MyMovieList-Python-Interface | /Main.py | 2,936 | 3.5625 | 4 | from Movie import *
from User import *
from Database import *
import sys
import getpass
import mysql.connector
dbserver = "192.168.1.3"
dbname = "mymovielist_db"
dbuser = "user_defaultddd"
dbpassword = "password"
conn = None
running = False
try:
conn = Database(dbserver, dbname, dbuser, dbpassword)
running = True
except Exception as e:
print(e)
menuMain = ["1. Users", "2. Movies", "3. People", "4. Other", "9. Exit"];
userInput = 0
def menuUserAdd():
"Menu for adding a User to the database"
username = None
password1 = None
password2 = None
email = None
looping = True
while looping == True:
username = input("Enter a username")
try:
result = User.validateUsername(conn, username)
if result == True:
print("Username already exists")
else:
print("User can be added")
looping = False
except Exception as e:
print(e)
looping = True
while looping == True:
password1 = input("Enter a password")
password2 = input("Confirm your password")
if password1 != password2:
print("Your passwords must match")
if password1 == password2:
looping = False
looping = True
while looping == True:
email = input("Enter an email address")
try:
result = User.validateEmail(conn, email)
if result == True:
print("Email already exists")
else:
print("Email is valid")
looping = False
except Exception as e:
print(e)
try:
User.addUser(conn, username, password1, email)
print("User successfully added")
except Exception as e:
print(e)
return
def menuUserQuery():
query = input("Enter a condition")
try:
users = User.queryUser(conn, query)
print("-------------")
print("Listing Users")
User.displayUsers(users)
print("-------------")
except Exception as e:
print(e)
return
def menuUser():
print("User Menu")
menu = ["1. List All", "2. List Users with Condition", "3. Add User", "9. Back"];
looping = True
while looping:
for x in range(0, len(menu)):
print (menu[x])
userInput = input("")
if userInput == '1':
try:
Users = User.getUsers(conn)
print("-------------")
print("Listing Users")
for x in Users:
x.displayUser()
print("-------------")
except mysql.connector.Error as e:
print("There was an error with the Database")
elif userInput == '2':
menuUserQuery()
elif userInput == '3':
menuUserAdd()
elif userInput == '9':
looping = False
else:
print("Enter a valid option")
return
while running:
print("Welcome to the Python interface for MyMovieList")
for x in range(0, len(menuMain)):
print (menuMain[x])
userInput = input("")
if userInput == '1':
menuUser()
elif userInput == '2':
print("Movies")
elif userInput == '3':
print("People")
elif userInput == '4':
print("Other")
elif userInput == '9':
conn.closeConnection()
running = False
#sys.exit()
else:
print("Enter a valid option")
|
67776ac67015ce159fe2e4c884b0fbf2d7c42717 | Al-Ip/Python-Client---Server-Program | /Python_Client-Server/PythonServer2.py | 1,673 | 3.671875 | 4 | #!/usr/bin/python
# imports
import socket
# create the socket
sock = socket.socket()
print "Socket successfully created"
# setting the server port
port = 1050
#Kill proccesses assosiated with the port number
#sudo fuser -k 1050/tcp
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to the port
sock.bind(('', port))
# print a message saying that the socket is binded to the port
# note: need to use the percent symbol to concatenate strings and ints
print "socket binded to Port: %s "%(port)
# set the server to listen for any client requests
sock.listen(5)
print "Waiting for client Requests"
# setting the server to run for ever, so we can handle multple client requests
while True:
# Establish connection with client.
c, clientAddress = sock.accept()
# message holds the clients message that he has sent
#message = c.recv(1024)
#message = int(numArr)
# printing out the clients message
#print type(message)
#print len(numArr)
for x in range (4):
numArr = [c.recv(1024)]
print numArr[2]
counter = 1;
#while counter <= 4:
#numArr = [message]
message= 5
print "Message from Client: %s"% message
# print a statement saying that a client has connected to the server and print the server addres
print 'Got connection from', clientAddress
def is_power2(message):
return message != 0 and ((message & (message -1)) ==0)
if(is_power2(message)):
print "True"
c.send('True')
else:
print "False"
c.send('False')
# Close the connection with the client
c.close()
|
ddd5ca2eb072153759f47c085dc611549fd7376b | stban94diaz/technical_test | /queens2.py | 703 | 3.53125 | 4 | n = 8
def queens(nR=0, solution=[-1 for i in range(n)], cols=[], d45=[], d135=[]):
if nR == n:
m = [['0' for i in range(n)] for j in range(n)]
for i in range(len(solution)):
m[i][solution[i]] = 'x'
for row in m:
print(row)
input("Press key ENTER")
else:
for i in range(n):
if not (i in cols) and not (i-nR in d45) and not (i+nR in d135):
solution[nR] = i
cols.append(i)
d45.append(i-nR)
d135.append(i+nR)
queens(nR+1, solution, cols, d45, d135)
cols.pop()
d45.pop()
d135.pop()
queens()
|
dd6a9a2ac0e6ac0bd0ea7fd6a787170a41f998d7 | qcianna/Python | /lab7/mod1.py | 292 | 3.875 | 4 | import math
def newton(n,k):
if(n >= k):
return math.factorial(n)//(math.factorial(k)*math.factorial(n-k))
else:
return 0
def pascal(n):
for i in range(n):
for j in range(n-i):
print(end = " ")
for j in range(i+1):
print(newton(i,j), end=" ")
print()
|
cc4dfe837bf76574c976b880196ac26e0838d864 | kongtianyi/cabbird | /leetcode/search_for_a_range.py | 425 | 3.5625 | 4 |
def searchRange(nums, target):
start=0
end=len(nums)-1
res=[]
while start<=end:
if nums[start]==nums[end]==target:
res.append(start)
res.append(end)
break
if nums[start]!=target:
start+=1
if nums[end]!=target:
end-=1
if not res:
res=[-1,-1]
return res
if __name__=="__main__":
print searchRange([1],0)
|
6628ffedd57fc14840b5be7ee37e875a87507f71 | tommymag/CodeGuild | /python/practice:wall-painting.py | 800 | 4.1875 | 4 | # All our friends are re-painting one wall of their rooms.
# They want us to figure out how much it’s going to cost.
# Assume one gallon of paint covers 400 square feet.
# Ask the user for:
# Width of the wall
# Height of the wall
# How much a gallon of paint costs
# Figure out then print how much it will cost to paint the wall with one coat.
import math
def cost_to_paint():
width = int(input("Overall, just how much wall are we talking here?? \nWidth: "))
height = int(input("Height: "))
pp = float(input("How much is a gallon of your paint going for?: "))
gallons_needed = math.ceil((width * height)/400)
# print(gallons_needed)
answer = "{:.2f}".format(gallons_needed * pp)
print("$", answer)
# need help with data type and rounding
cost_to_paint()
|
70357d52ddc99d4a2e794cd75b9d8bdf84b2fb08 | gaurang1703/algorithm-practice-python | /python/programmers/lv_one_027.py | 885 | 3.5 | 4 | class Solution:
""" 자릿수 더하기
자연수 N이 주어지면, N의 각 자릿수의 합을 구해서 return 하는 solution 함수를 만들어 주세요.
예를들어 N = 123이면 1 + 2 + 3 = 6을 return 하면 됩니다.
제한사항
N의 범위 : 100,000,000 이하의 자연수
입출력 예
N answer
123 6
987 24
"""
def my_solution(self, n: int) -> int:
if n < 10:
return n
answer = 0
for i in range(str(n)):
answer += int(i)
return answer
def best_solution_i_think(self, n: int) -> int:
if n < 10:
return n
return (n % 10) + self.best_solution_i_think(n // 10)
def other_solution_one(self, n: int) -> int:
return sum(map(int, str(n)))
|
ac7b18a8dec2eb04b592fc24bdd49b168d186efa | dariianastasia/Instructiuni-de-introducere-aplicatie-practica- | /exercitiul.7.py | 511 | 3.765625 | 4 | """Marina vrea sa verifice daca greutatea si inatimea ei corepunde virstei pe care o are.Ea gasit intr-o carte urmatoarele formule de calcul ale greutatii si inaltimiiunui copil , v fiind virsta:greutatea=2*v+8(in kg), inaltimea= 5*v+80(in cm).Realizati un program care sa citeasca virsta unui copil si sa afiseze greutatea si inaltimea ideala, folosind aceste formule."""
v=int(input("Introdu virsta sa:"))
g=2*v+8
i=5*v+80
print("Greutatea voastra este", g,"kg")
print("Inaltimea voastra este", i ,"cm") |
7e85bb671bcdd14ba7960a2b0565e17408d27bd5 | iezyzhang/Project | /Demo/第一季/基础知识/printformat.py | 2,523 | 3.671875 | 4 |
if __name__ == "__main__":
# num01, num02, = 200, 300
# print("八进制输出:%0o, %0o" % (num01, num02))
# print("十六进制输出:0x%x, 0x%x" % (num01, num02))
# print("二进制", bin(num01), "二进制", bin(num02))
#
# num01 = 1234567.8912
# print("标准的模式:%f" % num01)
# print("保留两位有效数字:%.2f" % num01)
# print("e的标准模式:%.2e" % num01)
# print("g的标准模式:%g" % num01)
# print("g保留两位有效数字:%.2g" % num01)
# 字符串的格式化输出
str01 = "www.jasdkl.com"
print("s标准输出:%s" % str01)
print("s固定空间中输出:%20s" % str01) # 右对齐 默认
print("s固定空间输出:%-20s" % str01) # 左对齐
print("s截取:%.3s" % str01) # 截取前三个字符
print("s截取:%10.3s" % str01) # 在固定10个字符空间中 截取前三个字符输出,靠右对齐
print("s截取:%-10.3s" % str01)
# format输出
name = "Alice"
gender = "男"
age = 23
print("姓名:{} 性别:{} 年龄:{}" .format(name, gender, age))
print("姓名:{0} 性别:{1} 年龄:{2} 学生姓名: {0}".format(name, gender, age))
print("姓名:{name} 性别:{gender} 年龄:{age} 学生姓名: {name}".format(name=name, gender=gender, age=age))
print("姓名: {:10}".format(name)) # 默认左对齐
print("姓名: {:<10}".format(name)) # 左对齐
print("姓名: {:>10}".format(name)) # 右对齐
print("姓名: {:^10}".format(name)) # 中间对齐
print("{:.2}".format(3.1415967)) # 保留两位有效数字 左对齐
print("{:10.2}".format(3.1415967)) # 保留两位有效数字。在10 个字符空间中打印 ,默认右对齐
print("{:<10.2}".format(3.1415967))
print("{:^10.2}".format(3.1415967))
num01, num02 = 100, 200
print("十六进制打印: {0:x} {1:x}".format(num01, num02))
print("八进制打印: {0:o} {1:o}".format(num01, num02))
print("八进制打印: {0:b} {1:b}".format(num01, num02))
print("{:c}".format(76)) # 打印ASK码
print(("{:e}".format(123456.666756)))
print(("{:0.2e}".format(123456.666756))) # 小数点后保留两位
print("{:g}".format(12323.654))
print("{:0.2g}".format(12323.654)) # 保留两位有效数字
print("{:0.2%}".format(0.2))
print("{:%}".format(0.2))
print("{:0.0%}".format(0.2))
# 千位分隔符
print("{:,}".format(123456789))
|
74762dd3ea498c6f4f6ff432f0fb3baf9873be93 | Juicechuan/workspace | /cs134-SNLP_PA/SNLP-PA2-HANDIN/evaluator.py | 5,895 | 3.515625 | 4 | """Evaluator functions
You will have to implement more evaluator functions in this class.
We will keep them all in this file.
"""
def split_train_test(classifier, instance_list, proportions):
"""Perform random split train-test
Train on x proportion of the data and test the model on 1-x proportion
return the performance report
Args :
classifier - a subclass of BaseClassifier
instance_list - dataset to perform cross-validation on
proportions - a list of two numbers. sum(proportions) == 1
proportions[0] is the train proportion
proportions[1] is the test proportion
Returns :
Accuracy rate
"""
train_len = (int)(proportions[0]*len(instance_list))
test_len = (int)(proportions[1]*len(instance_list))
train_set = instance_list[:train_len]
test_set = instance_list[-test_len:]
classifier.train(train_set)
total_size = 0.
correct_count = 0.
for ins in test_set:
label_list = ins.label
predict_label = classifier.classify_instance(ins)
total_size += len(label_list)
for i,j in zip(label_list,predict_label):
if classifier.label_codebook.get_index(i) == j:
correct_count+=1
accuracy=correct_count/total_size
return accuracy
if len(proportions) != 2:
raise ValueError("Proportion must be a list of length 2. Got %s." % proportions)
pass
def test_classifier(classifier, test_data):
"""Evaluate the classifier given test data
Evaluate the model on the test set and returns the evaluation
result in a confusion matrix
Returns:
Confusion matrix
"""
confusion_matrix = ConfusionMatrix(classifier.label_codebook)
for instance in test_data:
prediction = classifier.classify_instance(instance)
confusion_matrix.add_data(prediction, instance.label)
return confusion_matrix
import numpy
class ConfusionMatrix(object):
def __init__(self, label_codebook):
self.label_codebook = label_codebook
num_classes = label_codebook.size()
self.matrix = numpy.zeros((num_classes,num_classes))
def add_data(self, prediction_list, true_answer_list):
for prediction, true_answer in zip(prediction_list, true_answer_list):
self.matrix[prediction, self.label_codebook.get_index(true_answer)] += 1
def compute_precision(self):
"""Returns a numpy.array where precision[i] = precision for class i"""
precision = numpy.zeros(self.label_codebook.size())
for i in range(0,self.label_codebook.size()):
precision[i] = self.matrix[i,i]/self.matrix[i].sum()
return precision
def compute_recall(self):
"""Returns a numpy.array where recall[i] = recall for class i"""
recall = numpy.zeros(self.label_codebook.size())
for i in range(0,self.label_codebook.size()):
recall[i] = self.matrix[i,i]/self.matrix.sum(0)[i]
return recall
def compute_f1(self):
"""Returns a numpy.array where f1[i] = F1 score for class i
F1 score is a function of precision and recall, so you can feel free
to call those two functions (or lazily load from an internal variable)
But the confusion matrix is usually quite small, so you don't need to worry
too much about avoiding redundant computation.
"""
f1 = numpy.zeros(self.label_codebook.size())
precision = self.compute_precision()
recall = self.compute_recall()
f1 = 2*precision*recall/(precision+recall)
return f1
def compute_accuracy(self):
"""Returns accuracy rate given the information in the matrix"""
correct_counts = 0.
for i in range(0,self.label_codebook.size()):
correct_counts += self.matrix[i][i]
accuracy = correct_counts/self.matrix.sum()
return accuracy
def print_out(self):
"""Printing out confusion matrix along with Macro-F1 score"""
#header for the confusion matrix
header = [' '] + [self.label_codebook.get_label(i) for i in xrange(self.label_codebook.size())]
rows = []
#putting labels to the first column of rhw matrix
for i in xrange(self.label_codebook.size()):
row = [self.label_codebook.get_label(i)] + [str(self.matrix[i,j]) for j in xrange(len(self.matrix[i,]))]
rows.append(row)
print "row = predicted, column = truth"
print matrix_to_string(rows, header)
# computing precision, recall, and f1
precision = self.compute_precision()
recall = self.compute_recall()
f1 = self.compute_f1()
for i in xrange(self.label_codebook.size()):
print '%s \tprecision %f \trecall %f\t F1 %f' % (self.label_codebook.get_label(i),
precision[i], recall[i], f1[i])
print 'accuracy rate = %f' % self.compute_accuracy()
def matrix_to_string(matrix, header=None):
"""
Return a pretty, aligned string representation of a nxm matrix.
This representation can be used to print any tabular data, such as
database results. It works by scanning the lengths of each element
in each column, and determining the format string dynamically.
the implementation is adapted from here
mybravenewworld.wordpress.com/2010/09/19/print-tabular-data-nicely-using-python/
Args:
matrix - Matrix representation (list with n rows of m elements).
header - Optional tuple or list with header elements to be displayed.
Returns:
nicely formatted matrix string
"""
if isinstance(header, list):
header = tuple(header)
lengths = []
if header:
lengths = [len(column) for column in header]
#finding the max length of each column
for row in matrix:
for column in row:
i = row.index(column)
column = str(column)
column_length = len(column)
try:
max_length = lengths[i]
if column_length > max_length:
lengths[i] = column_length
except IndexError:
lengths.append(column_length)
#use the lengths to derive a formatting string
lengths = tuple(lengths)
format_string = ""
for length in lengths:
format_string += "%-" + str(length) + "s "
format_string += "\n"
#applying formatting string to get matrix string
matrix_str = ""
if header:
matrix_str += format_string % header
for row in matrix:
matrix_str += format_string % tuple(row)
return matrix_str
|
85cdf30ccb812243c2a1429ce2a0f5d5c8d2ce3f | bus1029/HackerRank | /Python_30days/Day 03_Intro To Conditional Statements/ConditionalStatement.py | 385 | 3.84375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
if int(N) % 2 == 1:
print("Weird")
elif int(N) % 2 == 0 and 2 <= int(N) <= 5:
print("Not Weird")
elif int(N) % 2 == 0 and 6 <= int(N) <= 20:
print("Weird")
elif int(N) % 2 == 0 and 20 < int(N):
print("Not Weird") |
adfff7b06f3b3031891ceff2683e2dc5235927d8 | Anandhakrishnan2000/Python_PS_Programs | /test.py | 636 | 3.765625 | 4 | from array import *
a = 5
b = 6
a=a+b
b=a-b
a=a-b
print("The value of a is: ")
print(a)
print("The value of b is ")
print(b)
x= int(input("Enter the first number"))
y= int(input("Enter the second number"))
s = x+y
print("The sum is" ,s)
result = eval(input("Enter an expression"))
print(result)
if result%2 == 0:
print("The result is even")
else:
print("The result is odd")
while a<=10:
print(a)
a=a+1
print("\n")
for i in range(1,10):
print(i)
z = 'ANANDHAKRISHNAN'
for i in z:
print(i)
l = [23,45,67,89]
for i in l:
print(i)
vals = array('i',[12,34,-5])
print(vals)
newArr = array(vals.typecode, (a for a in vals)) |
140fd943d28f9bf159accc19388d535495396d48 | dagomty/datatranslator_tarea | /String Warm-up.py | 2,916 | 4.53125 | 5 | # String Warm-up
# 1. Look at the code in `warmup1.py`. What is the letter at index 14 of `my_str`? Think about this first, then feel free to print just that letter to check your answer.
my_str = 'This String was not Chosen Arbitrarily...'
print(my_str.upper())
a=my_str[13]
print("Letter at index 14 is: "+str(a))
#2. In line 1 of `warmup1.py`, change the definition of `my_str` to use the contraction "wasn't" instead of "was not". What letter is at index 14 now?
my_str = "This String wasn't Chosen Arbitrarily..."
print(my_str.upper())
a=my_str[13]
print("Letter at index 14 is: "+str(a))
#3. Change `warmup1.py` to print `my_str` with only lowercase letters.
my_str = "This String wasn't Chosen Arbitrarily..."
print(my_str.lower())
a=my_str[13]
print("Letter at index 14 is: "+str(a))
# 4. Add a line between lines 1 and 2 that adds the string `"oR wAs it??"` to the end of `my_str`. When you print `my_str` with no uppercase letters now, it should display: `this string wasn't chosen arbitrarily...or was it??`. (**Hint**: use string concatenation with `+=` to redefine `my_str`)
my_str = "This String wasn't Chosen Arbitrarily..."
your_str="oR wAs it??"
sum_str=my_str+your_str
print(sum_str.lower())
#5. Using indexing, print only the `"oR wAs it"` in `my_str`. You're going to have to use `[start_index:end_index]` notation to do this.
print("Ex #5 ---------------")
my_str = "This String wasn't Chosen Arbitrarily..."
your_str="oR wAs it??"
sum_str=my_str+your_str
indexing_str=sum_str[40:52]
print(indexing_str)
#6. Find a different way to index into `my_str` to print only the `"oR wAs it"`. This time, though, print all the letters in uppercase.
print("Ex #6 ---------------")
print(sum_str[-11::].upper())
#7. Add the line `user_input = input('Add "oR wAs it??" (y/n)? ')` at the top of `warmup1.py`. This will prompt the user to enter a `y` or an `n`. Now add an `if` statement to your code that only adds the string `"oR wAs it??"` to `my_str` if the user inputs a `y`. If the user inputs an `n`, don't add `"oR wAs it??"` to `my_str`. Print `my_str` at the end of the script.
print("Ex #7 ---------------")
user_input = input('Add "oR wAs it??" (y/n)? ')
if user_input=="y":
print(sum_str)
else:
print(my_str)
#8. Change the first line of `warmup1.py` to `user_input = input('String to add to end of my_str: ')`. Add `user_input` to the end of `my_str` instead of `"oR wAs it??"` and print `my_str`. Note, you'll have to remove the `if` you have in your code from the previous question.
print("Ex #8 ---------------")
user_input = input('String to add to end of my_str: ')
print(my_str+user_input)
# #9. Now, only add `user_input` to `my_str` if it's shorter than 10 characters. No matter what, print `my_str`.
print("Ex #9 ---------------")
user_input = input('New user input: ')
if len(user_input)<10:
print(my_str+user_input)
else:
print(my_str) |
bded95306672a7ee20909f5bdf4aa86c1908fc56 | bach2o/NguyenNgocBach-fundamentals-c4e15 | /Session2/sum.py | 59 | 3.734375 | 4 | i=int(input("Enter the number:"))
sum=i*(i+1)/2
print(sum)
|
733e65471d5c4c5361f8912d2932ec615f75939c | abhik12295/Show-me-the-Data-Structure | /problem_1.py | 3,269 | 3.671875 | 4 | # Your work here
# Using Hash map and Doubly Linked List
# LRU CACHE
class Node:
# creating DLL
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
class LRU_Cache(object):
# defining DLL nodes
def __init__(self, capacity):
self.capacity = capacity # max capacity to hold
self.hash_map = {} # creating hash map
self.head = Node(0, 0) # creating dummy head node(0,0)
self.tail = Node(0, 0) # creating dummy tail node(0,0)
# linking head and tail to each other
self.head.next = self.tail
self.tail.prev = self.head
# None definition
self.head.prev = None
self.tail.next = None
def add(self, key, value):
# created new_node
new_node = Node(key, value)
# set curr to tail
curr = self.head.next
# linking new_node to tail part or curr pointer
new_node.next = curr
curr.prev = new_node
# linking new_node to head part
self.head.next = new_node
new_node.prev = self.head
# added new_node to hashmap
self.hash_map[key] = new_node
def delete(self, node):
# take 2 pointer nxt and prev to node
nxt = node.next
prev = node.prev
# assign and deleted node
nxt.prev = prev
prev.next = nxt
node.next = None
node.prev = None
node = None
def get(self, key):
# if key in dictionary
if key in self.hash_map:
# delete node and get
self.delete(self.hash_map[key])
# and add to the most recent
self.add(key, self.hash_map[key].value)
return self.hash_map[key].value
return -1
def set(self, key, value):
# if key already in dictionary
if key in self.hash_map:
self.delete(self.hash_map[key]) # delete the node at that key
del self.hash_map[key] # delete the value at that key
self.add(key, value) # add node to that key
# else if len of hash_map == capacity
elif len(self.hash_map) == self.capacity:
# delete LRU node from dict
del self.hash_map[self.tail.prev.key]
# delete LRU node
self.delete(self.tail.prev)
# add new_node
self.add(key, value)
else:
# add node to DLL and add to hash_map if key not in dict
# add 1,2,3,4 limit 5
self.add(key, value)
our_cache = LRU_Cache(5)
our_cache.set(1, 1);
our_cache.set(2, 2);
our_cache.set(3, 3);
our_cache.set(4, 4);
our_cache.get(1) # returns 1
our_cache.get(2) # returns 2
our_cache.get(9) # returns -1 because 9 is not present in the cache
our_cache.set(5, 5)
our_cache.set(6, 6)
our_cache.get(3) # returns -1 because the cache reached it's capacity and 3 was the least recently used entry
#new edge cases
our_cache = LRU_Cache(0)
our_cache.set(1, 1)
# Error occur, and can show message using try that "Can't perform cache operations on 0 capacity"
print(our_cache.get(1))
# should return -1
our_cache = LRU_Cache(-1)
our_cache.set(1, 1)
print(our_cache.get(1))
#should return 1 |
f61ae959d44a7a58bcaf34518c01998873137f81 | sunil1745/py3 | /asin10.1.py | 327 | 3.53125 | 4 | f=input('Enter file')
fhand=open(f)
mails=dict()
for lines in fhand:
lines=lines.split()
if len(lines)<3 or lines[0]!='From':continue
mails[lines[1]]=mails.get(lines[1],0)+1
#print (mails)
lst=list()
for k,v in mails.items():
lst.append((v,k))
lst=sorted(lst,reverse=True)
#print(lst)
for v,k in lst[0:1]:
print(k,v)
|
fb1891bb40a5292cdf8ac86d2102b5a0d985ebe8 | ddx-510/python | /practical4/q4_print_reverse.py | 174 | 4.21875 | 4 | # reverse a number
def reverse_int(n):
if len(n)==1:
return n
return n[-1]+reverse_int(n[:-1])
number = input("Enter a number: ")
print(reverse_int(number))
|
39d620e7a106543406cb5ae1b6e0b3374ee4ba45 | luzzetti/HackerRank_Solutions | /Python/02 - Basic Data Types/[Easy] - Nested Lists.py | 593 | 3.53125 | 4 | if __name__ == '__main__':
L = []
for _ in range(int(input())):
name = input()
score = float(input())
L.append([score,name])
#Codice che mi vergogno di aver scritto
T = []
L.sort(reverse=True)
T.append(L.pop())
for l in L:
if l[0] == T[0][0]:
T.append(L.pop())
Ta = []
Ta.append(L.pop())
for l in L:
if l[0] == Ta[0][0]:
Ta.append(L.pop())
Tar = []
for ta in Ta:
Tar.append(ta[1])
Tar.sort()
for tar in Tar:
print(tar)
|
c70a4bffe0324383fdc34a31df82c28bdc48ba84 | kamiloleszek/2017win_gr_kol3 | /kol1.py | 1,889 | 4.21875 | 4 | #Banking simulator. Write a code in python that simulates the banking system.
#The program should:
# - be able to create new banks
# - store client information in banks
# - allow for cash input and withdrawal
# - allow for money transfer from client to client
#If you can thing of any other features, you can add them.
#This code shoud be runnable with 'python kol1.py'.
#You don't need to use user input, just show me in the script that the structure of your code works.
#If you have spare time you can implement: Command Line Interface, some kind of data storage, or even multiprocessing.
#Do your best, show off with good, clean, well structured code - this is more important than number of features.
#After you finish, be sure to UPLOAD this (add, commit, push) to the remote repository.
#Good Luck
class Bank(object):
def __init__(self):
self.clients = [];
def addClient(self, client):
self.clients = [self.clients, client]
def transfer(self, clientFrom, clientTo, value):
if(value>=0 and clientFrom.cash >= value):
clientFrom.withdraw(value)
clientTo.input(value)
class Client(object):
def __init__(self, name):
self.cash = 0
self.name = name
def input(self, value):
if value>0:
self.cash = self.cash + value
def withdraw(self, value):
if value<self.cash:
self.cash = self.cash - value
return value
client1 = Client("jeden")
client2 = Client("dwa")
bank = Bank()
bank.addClient(client1)
bank.addClient(client2)
client1.input(2)
client1.withdraw(3)
bank.transfer(client1, client2, 1)
print("Client 1 cash: ")
print(client1.cash)
print("Client 2 cash: ")
print(client2.cash)
client3 = Client("trzy")
bank.addClient(client3)
bank.transfer(client1, client3, 1)
print("Client 3 cash: ")
print(client3.cash)
client3.withdraw(0.5)
print("Client 3 cash after withdraw: ")
print(client3.cash)
|
cc3761a1130f1b7accf90bcc93119341927c4ebd | Caleb-Mitchell/code_in_place | /discord_extension/Mindset/mindset_build.py | 1,572 | 4.21875 | 4 | import json
START_YEAR = 1800
END_YEAR = 2015
N_YEARS = END_YEAR - START_YEAR + 1
'''
Creates a file mindset.json that stores the data as a giant dictionary.
The dictionary associates years with all data for that year.
Each year is a dictionary from country name to country data. For example:
{
"1800":{
"Afghanistan":{"life":28.21, "pop":3280000, "gdp":603.0},
"Albania":{"life":28.2, "pop":3284351, "gdp":604.0},
...
"Zimbabwe":{"life":20.8, "pop": 12226542, "gdp":98.0}
},
...
}
'''
def main():
print('cleaning data...')
data = {}
add_data(data, 'life.csv')
add_data(data, 'pop.csv')
add_data(data, 'gdp.csv')
# saves data as json file!
json.dump(data, open('mindset.json', 'w'))
def add_data(data, file_name):
'''
The file_name is of the format <key>.txt where
key is one of "life", "pop", "gdp"
Each file is a list of rows formatted like:
Afghanistan,28.21,28.2,28.1 ...
'''
key = file_name.split('.')[0]
for line in open(file_name):
line = line.strip()
# ['Afghanistan', '28.21', ... ]
parts = line.split(',')
country = parts[0]
for i in range(N_YEARS):
value = float(parts[i + 1])
year = START_YEAR + i
print(country, year, key, value)
if not year in data:
data[year] = {}
if not country in data[year]:
data[year][country] = {}
data[year][country][key] = value
if __name__ == '__main__':
main()
|
87829c2ef595635d684bf5231e6baea056163c95 | jeongmingang/python_study | /chap05/file02.py | 371 | 3.734375 | 4 | def fopen1(filename):
file = open(filename, "w")
file.write("Hello Python Programming...")
file.close()
def fopen2(filename):
with open(filename, "w") as f:
f.write("Hello Python Programming...!")
# read
def f_read(filename):
with open(filename, "r") as f:
contents = f.read()
return contents
c = f_read("basic3.txt")
print(c)
|
fb053616991964f42293dd721635bdcd159bdb96 | kiteros/TPE-enigma-replica | /rsa/Chiffrement RSA.py | 2,359 | 3.671875 | 4 | from time import *
# encoding: utf-8
# L'utilisateur entre p
p = int(input('Entrez un grand nombre premier p : '))
# L'utilisateur entre q
q = int(input('Entrez un grand nombre premier q : '))
# On calcule n
n = p*q
print ("\nn = ",n,)
# On calcul phi(n)
phiden = (p-1)*(q-1)
print ("\nphi de n = ",phiden,)
# Variables de la boucle
compteur = 0
PGCD1 = 0
# Notre e qui s'incrémentera
e = 0
# La fonction PGCD avec ses 2 arguments a et b
# La fonction PGCD avec ses 2 arguments a et b
def pgcd(a,b):
# L'algo PGCD
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a;
# Tant que PGCD de e et phi(n) différents de 1
while PGCD1 != 1 :
# Tant que compteur=0
while compteur == 0 :
# Si p inférieur à e et si q inférieur à e et si e inférieur à n
if((p < e)and(q < e)and(e < phiden)) :
# La boucle se coupe (on peut aussi mettre le mot-clé : break
compteur = 1
# Tant que rien n'est trouvé, e s'incrémente
e = e + 1
# On récupère le résultat du pgcd
PGCD1 = pgcd(e,n)
# On affiche notre clé publique
print ("\nCle publique (",e,",",n,")")
# On demande d'entrer le texte à chiffrer
mot =input('\nEntrez le mot ou la phrase à chiffrer : ')
# On récupère le nombre de caractères du texte.
taille_du_mot = len(mot)
i=0
phraseCrypt=[]
# Tant que i inférieur aux nombres de caractères
while i < taille_du_mot :
# Comme i s'incrémente jusqu'à egalité avec la taille du mot, à chaque passage dans la fonction chaque lettre sera converti.
ascii = ord(mot[i])
# On crypte la lettre ou plutot son code ASCII
lettre_crypt = pow(ascii,e)%n
# Si le code ASCII est supérieur à n
if ascii > n :
print ("Les nombres p et q sont trop petits veulliez recommencer")
# Si le bloc crypté est supérieur à phi(n)
if lettre_crypt > phiden :
print ("Erreur de calcul")
# On affiche chaque blocs cryptés
phraseCrypt.append(lettre_crypt)
# On incrémente i
i = i + 1
# On bloque le programme avant la fermeture
print('élément crypté :\n')
for f in range(len(phraseCrypt)):
print(phraseCrypt[f],end=' ')
input('\n\nFin\n\n') |
603ba5d0c5dced7fa276dac52783a9d251993b50 | forbearing/mypython | /Scrapy/1/2_网络爬虫/7_动态渲染/2.7_selenium_延时等待.py | 3,319 | 3.796875 | 4 | 延时等待
1:在 Selenium 中, get() 方法会在网页框架家在结束后结束执行,此时如果获取 page_source,
可能并不是浏览器完全加载完成的页面. 如果某些页面有额外的 Ajax 请求.我们在网页中
也不一定能成功获取到, 需要延迟等待一定时间,确保节点都加载出来.
2:等待方式由隐式等待,显式等待
1:隐式等待
1:当使用隐式等待执行测试的时候,如果 Selenium 没有在 DOM 中找到节点,将继续等待,超出
设定时间后,则抛出找不到节点的异常
2:当查找节点而节点没有立即出现的时候,隐式等待将等待一段是时间再查找 DOM, 默认的时间时0
from selenium import webdriver
browser = webdriver.Chrome()
browser = implicitly_wait(10)
browser.get('https://www.zhihu.com/explore')
input = browser.find_element_by_class_name('zu-top-add-question')
print(input)
# 使用 implicitly_wait() 实现了隐式等待
2:显式等待
1:隐式等待的效果其实并没有那么好,因为只规定了一个固定时间,而页面的加载时间会受到
网络条件的影响.
2:显式等待,指定要查找的节点,然后制定一个最长等待时间,如果在规定时间内加载出来了
这个节点,就返回查找的节点.如果到了规定时间依然没有加载出该节点,则抛出超时异常
3:等待条件有很多, 比如判断标题内容, 判断某个节点内是否出现了某文字等
title_is 标题是某内容
title_contains 标题包含某内容
presence_of_element_located 节点加载出来,传入定位元组
visibility_of_element_located 节点可见,传入定位元组
visibility_of 可见,传入节点对象
presence_of_all_elements_located 所有节点加载出来
text_to_be_present_in_element 某个节点文本包含某文字
text_to_be_present_in_element_value 某个节点值包含某文字
frame_to_be_available_and_switch_to_it 加载并切换
invisibility_of_element_located 节点不可见
element_to_be_clickable 节点可点击
staleness_of 判断一个节点是否扔在 DOM, 可判断页面是否已经刷新
element_to_be_selected 节点可选择,传节点对象
element_located_to_be_selected 节点可选择,传入定位元组
element_selection_state_to_be 传入节点对象以及状态,相等返回 True,否则返回 False
element_located_selection_state_to_be 传入定位元组以及状态,相等返回 True,否则返回 False
alert_is_present 是否出现警告
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
wait = WebDriverWait(browser, 10)
input = wait.until(EC.presence_of_element_located(By.ID, 'q'))
button = wait.until(EC.element_to_be_clicable((By.CSS_SELECTOR, '.btn-search')))
|
7066e50821005fb4e3c192688d1f2d553ecc775a | ilinaos/task_1 | /prog.py | 578 | 3.640625 | 4 | # entry = input('I\'m waiting for text...\n').lower()
# num_a=0; num_e=0; num_y=0; num_u=0; num_o=0; num_i=0;
# for i in entry:
# if i=='a': num_a+=1
# elif i=='e': num_e+=1
# elif i=='y': num_y+=1
# elif i=='u': num_u+=1
# elif i=='i': num_i+=1
# elif i=='o': num_o+=1
# print (f'a={num_a}, e={num_e}, y={num_y}, u={num_u}, i={num_i}, o={num_o}')
letters = {'a':0, 'e':0,'y':0,'u':0,'i':0,'o':0}
entry = input('I\'m waiting for text...\n').lower()
for i in entry:
if i in letters.keys():
letters[f'{i}']+=1
print (letters)
|
bd6f3d8e132b53814f0829984489fa9ee0b32ecc | pamo18/dbwebb-python | /kmom02/flow/Vilkor-loopar.py | 2,699 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Testar Python
"""
number_of_apples = 9
if number_of_apples > 10:
print("Du har mer än 10 äpplen")
elif number_of_apples <= 10 and number_of_apples > 5:
print("Du blev snabbt mätt och åt bara upp några av dina äpplen")
else:
print("Du har nog varit hungrig och ätit upp dina äpplen")
print("Nu är vi klara med if-satsen")
# skriver ut:
# Du blev snabbt mätt och åt bara upp några av dina äpplen
# Nu är vi klara med if-satsen
type_of_fruit = "päron"
number_of_fruits = 13
if number_of_fruits > 10:
if type_of_fruit == "äpple":
print("Du har mer än 10 äpplen")
else:
print("Du har mer än 10 frukter")
print("Nu är vi klara med den inre if-satsen")
print("Nu är vi klara med den yttre if-satsen")
# skriver ut:
# Du har mer än 10 frukter
# Nu är vi klara med den inre if-satsen
# Nu är vi klara med den yttre if-satsen
for i in range(10):
print(i)
for number_of_apples in range(3, 15):
if number_of_apples > 10:
print("Du har mer än 10 äpplen")
elif number_of_apples <= 10 and number_of_apples > 5:
print("Du blev snabbt mätt och åt bara upp några av dina äpplen")
else:
print("Du har nog varit hungrig och ätit upp dina äpplen")
for _ in range(5):
print("Python är ett spännande programmeringsspråk")
for letter in "räksmörgås":
if letter in "åäö":
print(letter)
while True:
user_input = input("Skriv in antal äpplen (eller q för avslut): ")
if user_input == "q":
print("Du är nu klar med att äta äpplen.")
print("Hej då!")
break
else:
number_of_apples = int(user_input)
if number_of_apples > 10:
print("Du har mer än 10 äpplen")
elif number_of_apples <= 10 and number_of_apples > 5:
print("Du blev snabbt mätt och åt bara upp några av dina äpplen")
else:
print("Du har nog varit hungrig och ätit upp dina äpplen")
while True:
user_input = input("Skriv in antal äpplen (eller q för avslut): ")
if user_input == "q":
print("Du är nu klar med att äta äpplen.")
print("Hej då!")
break
else:
try:
number_of_apples = int(user_input)
except ValueError:
print("Oj! Du skrev inte in en siffra.")
continue
if number_of_apples > 10:
print("Du har mer än 10 äpplen")
elif number_of_apples <= 10 and number_of_apples > 5:
print("Du blev snabbt mätt och åt bara upp några av dina äpplen")
else:
print("Du har nog varit hungrig och ätit upp dina äpplen")
|
9473c758fb0bf5035fc4c814a014d0d2ac4268a9 | HersheyChocode/Python_Spring2019 | /AoPS python/permute.py | 1,578 | 4.3125 | 4 | def anagrams(string):
#Base Cases
if len(string)==0:#If list is empty
return []; #Return empty list
elif len(string) == 1: #If list contains one argument
return [string] #Return that list
#Recursive Case
else: #Otherwise...
anagram = [] #Create empty list
for letter in range(len(string)): #From 0 to length of string - 1
remaining = string[:letter] + string[letter+1:] #Remaining letters
for each in anagrams(remaining): #For each anagram
anagram.append(string[letter]+each) #Add anagram to empty list
return anagram #Return all anagram
def jumble_solve(string):
lst = anagrams(string) #converts "string" to all anagrams of "string"
valid = [] #creates empty list for text file
jumbled = [] #creates empty list for accurate jumbled words
check = open("wordlist.txt","r") #opens and reads the file
for word in check: #for each word in the file
valid.append(word.strip()) #append the word to our empty list
for word in lst: #for each word in our list of anagrams
word = word.lower() #converts to lower case
for line in valid: #for each word in the file
if word == line: #if the both words match
jumbled.append(word) #add the word to list "jumbled"
check.close()
return jumbled #return list "jumbled"
#test cases
print(jumble_solve("CHWAT"))
print(jumble_solve("RAROM"))
print(jumble_solve("CEPLIN"))
print(jumble_solve("YAFLIM"))
|
7d7434a4cc4c6ca507dbcc39c2447c0b3a2d67dd | dgaiero/Resistor-Band-Picture-Creator | /Test Scripts/resistorAlgorithm5Band.py | 4,016 | 3.609375 | 4 | # 2 DECIMAL POINT
#9-3-17
# Initialize resistor colors
BLACK = ['black', 0, 0, 0, 1, None]
BROWN = ['brown', 1, 1, 1, 10, "1%"]
RED = ['red', 2, 2, 2, 100, "2%"]
ORANGE = ['orange', 3, 3, 3, 1000, "3%"]
YELLOW = ['yellow', 4, 4, 4, 10000, "4%"]
GREEN = ['green', 5, 5, 5, 100000, "0.5%"]
BLUE = ['blue', 6, 6, 6, 1000000, "0.25"]
PURPLE = ['purple', 7, 7, 7, 10000000, "0.15%"]
GREY = ['grey', 8, 8, 8, None, "0.05%"]
WHITE = ['white', 9, 9, 9, None, None]
GOLD = ['gold', None, None, None, 0.1, "5%"]
SILVER = ['silver', None, None, None, 0.01, "10%"]
RESISTORCOLORS = [BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, GREY, WHITE, GOLD, SILVER]
currentColorBandDict = {}
newResistorValueList = []
# Ask for user input of resistor value, number of bands, and tolerance value
userInputResistorValue = float(input("Enter the resistor value: "))
#userInputNumBands = int(input("Enter the number of bands: "))
userInputNumBands = 5
print ("Tolerance Values: 0.05% | 0.1% | 0.25% | 0.5% | 1% | 2% | 5% | 10% | 20%")
#userInputToleranceValue = str(input("Enter the tolerance value: "))
userInputToleranceValue = '5%'
# Add each digit in userInputResistorValue to string in a list
oldResistorValueList = list(str(userInputResistorValue))
# Add a '0' to fix input values less than 1 rounded to 1 decimal place
if userInputResistorValue < 10 and (len(oldResistorValueList) == 3 or len(oldResistorValueList) == 4):
oldResistorValueList.append('0')
# Create a new list with digits other than 0 and a decimal point
# Determine if userInputResistorValue is a decimal number
for item in oldResistorValueList:
if item == '.':
if newResistorValueList[0] == 0:
del newResistorValueList[0]
else:
newResistorValueList.append(int(item))
# Executes if 4 band color code is requested
if userInputNumBands == 5:
i = 0 # first band iterator
j = 0 # second band iterator
k = 0 # third band iterator
l = 0 # multiplier iterator
m = 0 # tolerance iterator
# Get firstBandNum and firstBandColor
while i <= 11:
if RESISTORCOLORS[i][1] == newResistorValueList[0]:
currentColorBandDict['firstBandColor'] = RESISTORCOLORS[i][0]
#if DECIMAL == True and userInputResistorValue < 1:
if userInputResistorValue < 1:
firstBandNum = oldResistorValueList[2]
else:
firstBandNum = oldResistorValueList[0]
i += 1
# Get secondBandNum and secondBandColor
while j <= 11:
if RESISTORCOLORS[j][2] == newResistorValueList[1]:
currentColorBandDict['secondBandColor'] = RESISTORCOLORS[j][0]
if userInputResistorValue < 1:
secondBandNum = oldResistorValueList[3]
elif userInputResistorValue >= 1 and userInputResistorValue < 10:
secondBandNum = oldResistorValueList[2]
else:
secondBandNum = oldResistorValueList[1]
j += 1
# Get thirdBandNum and thirdBandColor
while k <= 11:
if RESISTORCOLORS[k][3] == newResistorValueList[2]:
currentColorBandDict['thirdBandColor'] = RESISTORCOLORS[k][0]
if oldResistorValueList[2] == '.':
thirdBandNum = oldResistorValueList[3]
else:
thirdBandNum = oldResistorValueList[2]
k += 1
# Calculate multiplier value
firstSecondAndThirdBandNum = float(firstBandNum + secondBandNum + thirdBandNum)
multiplier = round((userInputResistorValue / firstSecondAndThirdBandNum), 3)
# Get fourthBandColor
while l <= 11:
if RESISTORCOLORS[l][4] == multiplier:
currentColorBandDict['fourthBandColor'] = RESISTORCOLORS[l][0]
l += 1
# Get fifthBandColor
while m <= 11:
if RESISTORCOLORS[m][5] == userInputToleranceValue:
currentColorBandDict['tolerance'] = RESISTORCOLORS[m][0]
m += 1
# Display current color band in the terminal
print (currentColorBandDict)
|
0ccd7a7dc7405c6a5a59c7a52a863c35b2040038 | kmju1997/python_study | /Tkinter/파이썬 1-8.py | 226 | 3.78125 | 4 | import random
target_num= random.randint(1,9)
a = input("숫자를 맞춰보세요! ")
a=int(a)
if a!=target_num :
print("땡! 숫자는 %d이였습니다." %target_num)
else :
print("맞췄습니다! 대단해요!")
|
c3e5367addf98290dac86681eee5105ef5ce95ce | rotus/the-python-bible | /function_basic_add.py | 89 | 3.640625 | 4 | # very simple function examples
def add(x,y):
return x + y
a=5
b=10
print(add(a,b))
|
e51b341a6e280acd65ee8e89d69d15b9f3723062 | antonyalexcm/Bridgelabz_updated | /Data_structures/Balanced_parentheses.py | 1,584 | 4.0625 | 4 | import array as arr
class Stack:
def __init__(self):
self.array = arr.array('u',)
self.count = 0
def push(self):
''' Function to push the opening parentheses to the stack'''
self.array.append('(')
self.count +=1
def string_traversal(self,string):
''' Function to traverse the string and check for parentheses'''
for i in string:
if( i == '('):
new.push()
elif(i == ')'):
new.pop()
if (i == (len(string) - 1 )):
if self.count == 0:
print("True")
else:
print("False")
def isEmpty(self):
''' Function to check whethre the stack is empty'''
if (len(self.array) == 0):
return True
else:
return False
def pop(self):
''' Function to remove the parentheses from the stack'''
self.array.remove('(')
self.count -= 1
def peek(self):
''' Function to get the first element of the array'''
return self.array[0]
def Size(self):
''' Function to get the length of the array'''
return len(self.array)
# Driver function
if __name__ == "__main__":
new = Stack()
string = str(input("Enter the string to check for balanced parantheses: "))
try:
new.string_traversal(string)
print("Is the arithmetic expression balanced: ", new.isEmpty())
except ValueError:
print("\n Wrong input, Try Again!!!")
|
dea0a0490ac4467a22133d68c576811095a337f9 | Taranoberoi/GUI-TKinter | /GUI-1.py | 576 | 3.828125 | 4 | from tkinter import *
# function for button
def funct():
print("Look I got clicked")
root = Tk()
root.title("First Programme")
root.geometry("800x800")
# Label inside the windows
label = Label(root,text="Check this out").grid(row=1,column=2)
label2 = Label(root,text="Check this second statement").grid(row=1,column=5)
ent = Entry(root,text="Enter the string value",bg="yellow",fg="black",width=50).grid(row=3,column=5)
# padx and pady button will resize he Button
button = Button(root,text="Click Me",pady=170, command = funct).grid(row=8,column=5)
root.mainloop()
|
e6fa0a12b4726ca552b1468ba411642840879c72 | ShubhangiDabral13/Data_Structure | /Matrix/Sparse Matrix/Implementation_Of_Sparse_Matrix_Using_Array/Implement_Sparse_Matrix_Using_Array.py | 862 | 4.3125 | 4 | """
2D array is used to represent a sparse matrix in which there are three rows named as
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index – (row,column)
"""
def sparse_matrix(arr):
rows,column = len(arr),len(arr[0])
count = 0
for i in range(rows):
for j in range(column):
if arr[i][j] != 0 :
count += 1
sparse_mat = [[0]*3]*(count+1)
sparse_mat[0] = [rows,column,count]
k = 1
for i in range(rows):
for j in range(column):
if arr[i][j] != 0:
sparse_mat[k] = [i,j,arr[i][j]]
k =k+1
for i in sparse_mat:
print(i)
sparse_matrix([[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]])
|
b46802ad9b76da5fbec9cf5e2fc6f4adef560c66 | Md-Monirul-Islam/Python-code | /Advance-python/Pickling and Unpickling in Python -1.py | 394 | 3.53125 | 4 | import pickle
class Student:
def __init__(self,name,roll,phn):
self.name = name
self.roll = roll
self.phn = phn
def display(self):
print(f"Name : {self.name}, Roll : {self.roll}, Phone : {self.phn}")
with open("student.dat",mode="wb") as f:
Student_1 = Student("Munna","180126","01784905235")
pickle.dump(Student_1,f)
print("Pickle Done!!") |
5833ce94570b2c7f2708385057c9d8968d3bd393 | youngsheep7/datastructure_algorithm_for_python | /programmer_algorithm_interview/prj/production_codes/linkedlist_reverseorder.py | 1,215 | 3.921875 | 4 | import random
class LinkedListNode:
def __init__(self, data, next):
self.data = data
self.next = next
def __init_linkedlist(hashead, i_length, isdatarandom):
'''
:param hashead:
:param i_length:
:param isdatarandom:
:return:
'''
if hashead == True:
head = LinkedListNode(i_length, None)
cur = head
i = 1
while i <= i_length:
tmp = LinkedListNode(random.randint(1,20), None)
print(tmp.data)
cur.next = tmp
cur = tmp
i = i + 1
return head
def __print_linkedlist(head):
'''
:param head:
:return:
'''
cur = head
while cur != None:
print(cur.data)
cur = cur.next
def __reverse_linkedlist(head):
'''
:param head:
:return:
'''
if head == None or head.next == None:
return head
cur = head.next.next
head.next.next = None
while cur!= None:
next = cur.next
cur.next = head.next
head.next = cur
cur = next
return head
if __name__ == '__main__':
# 构造链表
head = __init_linkedlist(True, 10, True)
print('#################################')
# 打印原链表
__print_linkedlist(head)
print('#################################')
# 链表逆序
head = __reverse_linkedlist(head)
# 打印逆序后的链表
__print_linkedlist(head)
print('END') |
a3f5f2a722112234b0af1a23739c7fb204a19334 | JuDa-hku/ACM | /leetCode/81SearchInRotatedSortedArrayII.py | 1,913 | 3.53125 | 4 | class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer}
def search(self, nums, target):
n = len(nums)
if n==0:
return False
return self.searchHelp(nums, target, 0, n-1)
def searchHelp(self, nums, target, start, end):
middle = (start+end)/2
if target ==nums[start]:
return True
if target ==nums[end]:
return True
if target ==nums[middle]:
return True
if end-start <= 1:
return False
if nums[start] == nums[end]:
return self.searchHelp(nums, target, start, end-1)
if nums[middle]>=nums[end] and nums[middle]>=nums[start]:
if target<nums[middle] and target>nums[start]:
return self.searchHelp(nums, target, start, middle)
if target<nums[middle] and target<nums[end]:
return self.searchHelp(nums, target, middle, end)
if target>nums[middle]:
return self.searchHelp(nums, target, middle, end)
else:
return False
if nums[middle]<=nums[end] and nums[middle]<=nums[start]:
if target<nums[middle]:
return self.searchHelp(nums, target, start, middle)
if target>nums[middle] and target<nums[end]:
return self.searchHelp(nums, target, middle, end)
if target>nums[middle] and target>=nums[end]:
return self.searchHelp(nums, target, start, middle)
if nums[middle]<=nums[end] and nums[middle]>=nums[start]:
if target<nums[middle]:
return self.searchHelp(nums, target, start, middle)
if target>=nums[middle]:
return self.searchHelp(nums, target, middle, end)
s = Solution()
nums = [1,3,1,1,1]
for i in range(9):
print s.search(nums, i) |
6508f44971692f005c171c7beda5d76a4752e82e | rluong003/chatApp | /createdb.py | 490 | 4.125 | 4 | import sqlite3
with sqlite3.connect("Login.db") as db:
cursor = db.cursor()
cursor.execute(""" CREATE TABLE IF NOT EXISTS user(
username VARCHAR(20) PRIMARY KEY,
password VARCHAR(20) NOT NULL);""")
cursor.execute("""
INSERT INTO user (username,password)
VALUES("p1", "123")
""")
cursor.execute("""
INSERT INTO user (username,password)
VALUES("p2", "111")
""")
db.commit()
cursor.execute("SELECT * FROM user")
#just to make sure the right things are input
print (cursor.fetchall()) |
624a90e5729410be80668c8497faa63804718513 | robertdavidwest/RealPython | /sql/sqla.py | 1,650 | 4.40625 | 4 | # Create a SQLite3 database and table
# import the sqlite3 library
import sqlite3
import csv
import urllib2
# create a new database if the databasee doesn't already exist
conn = sqlite3.connect("new.db")
# get a cursor object used to execute SQL commands
#cursor = conn.cursor()
# create a table
#cursor.execute("""CREATE TABLE population (city TEXT, state TEXT, population INT)""")
# insert data
#cursor.execute("INSERT INTO population VALUES('New York City', 'NY', 8200000)")
#cursor.execute("INSERT INTO population VALUES('San Francisco', 'CA',800000)")
#conn.commit()
# close the database connection
#conn.close()
'''
# using the 'with' command make sqlite automatically commit the INSERT comannds without having to hit conn.commit() after
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
# insert multiple records using a tuple
cities = [
('Boston','MA', 600000),
('Chicago','IL',2700000),
('Houston','TX',2100000),
('Phoenix','AZ',1500000)]
# insert data into table
c.executemany('INSERT INTO population VALUES(?,?,?)', cities)
# close the database connection
c.close()
'''
# using the 'with' command make sqlite automatically commit the INSERT comannds without having to hit conn.commit() after
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
# open the csv file and assign it to a variable
employees = csv.reader(open("employees.csv","rU"))
# create a table called employeess
#c.execute("CREATE TABLE employees(firstname TEXT, lastname TEXT)")
# insert data into table
c.executemany("INSERT INTO employees(firstname, lastname) values (?, ?)", employees)
|
5f1e635f1e94096caa1b89f6e3216b779e7e1291 | yubajin/FirstPy | /src/Class/Python_test.py | 1,050 | 3.75 | 4 | '''
Created on 2017年8月7日
重写方法__str__对应print()方法, __dir__
创造一个对象,先用__init__函数实例化,然后调用__setattr__给属性赋值,赋值一个属性,调用一下函数
@author: Administrator
'''
class Programer(object):
def __init__(self,name,age):
print('I\'m creating myself!')
self.name = name
if isinstance(age, int):
self.age= age
else:
raise Exception('age must be int')
def __str__(self):
return '%s is %s years old' %(self.name, self.age)
def __dir__(self):
return self.__dict__.keys()
def __setattr__(self,name,value):
print('I\'m setting attribute')
self.__dict__[name] = value
print(name,':',self.__dict__[name])
def __getattribute__(self,name):
print('I\'m getting attribute')
return super(Programer,self).__getattribute__(name)
if __name__ == '__main__':
p = Programer('albert',25)
print (p)
print (dir(p))
|
1fab4af240a632f52f61a01f9f7437b67f3f368e | ihaku4/scripts | /pythontest.py | 593 | 3.53125 | 4 | def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
result = add_10(3)
print result
print create_adder(123)(123)
print (lambda x: x > 2)(3)
import math
print dir(math)
import time
import thread
def timer(no, interval):
cnt = 0
while cnt<10:
print 'Thread:(%d) Time:%s\n'%(no, time.ctime())
time.sleep(interval)
cnt+=1
thread.exit_thread()
def test():
thread.start_new_thread(timer, (1,1))
thread.start_new_thread(timer, (2,2))
if __name__=='__main__':
test() |
9a41001bf10f73a79a04cb9483aea65699201ee8 | kayyali18/Python | /Python 31 Programs/Ch 10 Challenges/Guess My Number Challenge (Clears every 5 lines).py | 4,026 | 4.125 | 4 | ## Guess My Number Game GUI
from tkinter import *
import random
# put the random number as a global variable so it doesnt change
# with every function call
number = random.randint (1,100)
class Application (Frame):
""" A GUI Game where a user has to guess a number picked by computer """
def __init__ (self, master):
super (Application, self).__init__(master)
self.grid ()
self.number_guess = 0
self.num_guesses = 0
self.lines = 0
self.create_widgets ()
def create_widgets (self):
""" Create widgets to get user input for guess """
# create a label for guess
Label (self,
text = "Your Guess: ",
).grid (row = 1, column = 0, sticky = W)
self.guess_ent = Entry (self)
self.guess_ent.grid (row = 1, column = 1, sticky = W)
# create a click counter button
self.bttn = Button (self)
self.bttn ['text'] = "Total Guesses:\t 0"
self.bttn.grid (row = 3, column = 3, sticky =W)
# create a submit button
Button (self,
text = "Submit",
command = self.give_answer # everytime it is clicked. This method runs
).grid (row = 3, column = 0, sticky = W)
# create text box with prompt displayed when initialised
prompt = """\tWelcome to the Number Guessing Game
I'm going to pick a random number from 1 and 100\n\
I need you to guess it, in the least amount of tries."""
self.answer_txt = Text (self, width = 75, height = 10, wrap = WORD)
self.answer_txt.grid (row = 4, column = 0, columnspan = 4)
self.answer_txt.insert (0.0, prompt)
# def a method to update count
# I was able to make this method work by putting it in the give_answer method
# which is run everytime the submit button is clicked
# as such the update_count method is run everytime the submit button is clicked
# allowing the self.bttn (Button) to update for every click
def update_count (self):
""" Increase click count and display new total"""
guess = self.guess_ent.get ()
if guess != None: # if guess entry box is not empty value run:
self.num_guesses += 1
self.bttn.configure (text = "Total Guesses:\t" + str(self.num_guesses))
def game (self, number, guess, number_guess):
if guess > number:
reply = "You're too high, guess lower\n"
elif guess < number:
reply = "You're too low, guess higher!\n"
elif guess == number:
reply = "You guessed it and it only took you:\n" + str(number_guess)
reply += " tries"
last_guess = "\nYour last guess was:\t" + str(guess) + "\n"
return reply, last_guess
# create a method to clear lines in text box every five lines
def clear_lines (self):
self.lines += 1
if self.lines >= 5:
self.answer_txt.delete(0.0, END)
# create def to give_answer
def give_answer (self):
""" Fill text box with reply to guess """
guess = int(self.guess_ent.get ())
self.update_count ()
self.clear_lines ()
self.number_guess += 1 # put it in initialisation method
# update it everytime give_answer method is run
# in turn it relays as a parameter to the game method
number_guess = self.number_guess
global number #global so it doesn't change everytime although I
# could probably make the random num a method instead. For another day!
new_lines = "\n\n"
game = self.game (number, guess, number_guess)
self.answer_txt.insert (0.0, new_lines)
self.answer_txt.insert (0.0, game)
root = Tk ()
root.title ("Guess My Number")
app = Application (root)
root.mainloop ()
|
b3c96de5c50e7fdde2e7ae70d6d8411ad3824469 | vScourge/Advent_of_Code | /2021/03/2021_day_03_1.py | 2,446 | 4.21875 | 4 | """
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic
report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers which, when
decoded properly, can tell you many useful things about the conditions of the submarine.
The first parameter to check is the power consumption.
You need to use the binary numbers in the diagnostic report to generate two new binary numbers
(called the gamma rate and the epsilon rate). The power consumption can then be found by
multiplying the gamma rate by the epsilon rate.
Each bit in the gamma rate can be determined by finding the most common bit in the corresponding
position of all numbers in the diagnostic report. For example, given the following diagnostic report:
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the
most common bit is 1, the first bit of the gamma rate is 1.
The most common second bit of the numbers in the diagnostic report is 0, so the second bit of
the gamma rate is 0.
The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so
the final three bits of the gamma rate are 110.
So, the gamma rate is the binary number 10110, or 22 in decimal.
The epsilon rate is calculated in a similar way; rather than use the most common bit, the least
common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying
the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198.
Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate,
then multiply them together. What is the power consumption of the submarine? (Be sure to represent
your answer in decimal, not binary.)
"""
import numpy
gamma = ''
epsilon = ''
lines = [ line.strip( ) for line in open( 'input.txt', 'r' ).readlines( ) ]
for i in range( len( lines[ 0 ] ) ):
bits = [ line[ i ] for line in lines ]
most_common_bit = numpy.argmax( numpy.bincount( bits ) )
least_common_bit = numpy.argmin( numpy.bincount( bits ) )
gamma += str( most_common_bit )
epsilon += str( least_common_bit )
gamma = int( gamma, 2 )
epsilon = int( epsilon, 2 )
print( 'gamma =', gamma)
print( 'epsilon =', epsilon )
print( 'answer =', gamma * epsilon )
# 3687446 |
548ce681456ac4c2d275431f4693a3f46ef1dc64 | AspiringOliver/kkb | /课外程序/pdf跳页截取.py | 537 | 3.546875 | 4 | import PyPDF2 as pdf
inputfile = "input.pdf"
outputfile = "output1.pdf"
reader = pdf.PdfFileReader(inputfile)
pages = [1, 3, 5, 7]
getpages = list()
for i in pages:
page = reader.getPage(i - 1) # page number starts with 0
getpages.append(page)
writer = pdf.PdfFileWriter()
for page in getpages:
writer.addPage(page)
with open(outputfile, 'ab') as fh: #pdf文件的的读入方式必须是二进制格式的
writer.write(fh)
# outputStream = open(outputfile, "wb")
# writer.write(outputStream)
# outputStream.close()
|
5a4448a57efd7d71e79c1f652d7fdc8910c92681 | gaoyucai/Python_Project | /数据结构与算法/快速排序.py | 202 | 3.765625 | 4 | # Author:GaoYuCai
def insert_sort(li):
for i in range(1,len(li)):
tmp=li[i]
j=i-1
while j>=0 and li[j] >= tmp:
li[j+1]=li[j]
j=j-1
li[j+1]=tmp |
93db43c5529f82cbf2392ed49296cedc42d0b065 | hooong/TIL | /algorithm/6/1.py | 522 | 3.515625 | 4 | # 최대점수 구하기
def dfs(l, sum, time):
global max_score
if time > m:
return
if l == n:
max_score = max(max_score, sum)
else:
dfs(l+1, sum + problems[l][0], time + problems[l][1])
dfs(l+1, sum, time)
if __name__ == '__main__':
n, m = map(int, input().split())
problems = []
for _ in range(n):
problems.append(list(map(int, input().split())))
max_score = 0
visited = [False] * (n)
dfs(0, 0, 0)
print(max_score)
|
341dbb67f6b118a7a30aff2e2d6292f28c3f2ff5 | JoaoPauloAntunes/Python | /curso-em-video/mundo1/input.py | 55 | 3.75 | 4 | name = input('Name:')
print('Hello, '+name+"!")
input() |
e9ee787c760d6cb93d4f3fa4ce6af485901e4dca | chelsea-banke/p2-25-coding-challenges-ds | /Exercise_46.py | 497 | 3.984375 | 4 | # Find the maximum number in a jagged array of numbers or array of numbers
def maxNum(array):
for elt in array:
max = 0
if isinstance(elt, list):
maxIf = elt[0]
for val in elt:
if val > max:
maxIf = val
else:
maxElse = elt
if elt >= maxElse:
maxElse = elt
if maxIf >= maxElse:
return maxIf
else:
return maxElse
print(maxNum([1, 5, [354, 3], 9])) |
95115bdfb9ee518160c7fff738e5c069c61413ee | SJeliazkova/SoftUni | /Python-Fundamentals/Exercises-and-Labs/list_advance_lab/02_todo_list.py | 305 | 3.796875 | 4 | command = input()
todo_list = [0 for _ in range(11)]
while command != "End":
note = command.split("-")
index = int(note[0])
task = note[1]
todo_list.pop(index)
todo_list.insert(index, task)
command = input()
result = [task for task in todo_list if not task == 0]
print(result) |
85f6e24354205363ba097a3f77cd41238a4ef2d9 | henuliyanying/pythonDemo | /randomNum.py | 103 | 3.59375 | 4 |
#生成指定范围的随机数
import random
#random.randit(a,b) a<=N<=b
print(random.randint(0,9)) |
5cba565fa152d6c937d1b7e390f1c309b7f32514 | srinivas40687/Python_Lab_Assignments | /Lab1/Source/Lab1_D.py | 1,090 | 3.953125 | 4 | #Students who are attending python class are stored in List1:
List_1 = ['Srinivas', 'Kranthi', 'Avinash', 'Sireesha', 'Dinesh', 'Sudheer', 'Pujita']
#Students who are attending Web_Application class are stored in List2:
List_2 = ['Srinivas', 'Girish', 'Dinesh', 'Pujita', 'Prudhvi', 'Sireesha', 'Avinash', 'Yeshwanth', 'Prabha']
print("Students who are attending both python and web_aaplication classes are: \n")
for A in List_1: #Here A is a student in List1
if A in List_2: #This checks if the same student is present in the List2, If Yes prints the student
print(A)
print('\n')
print("Students who are not common in both the python and web_application classes are: \n")
for B in List_1: #Here B is a student in List1
if B not in List_2: #This checks if the same student is present in the List2, If No prints the student
print(B)
for C in List_2: #Here C is a student in List2
if C not in List_1: #This checks if the same student is present in the List1, If No prints the student
print(C) |
0cd980129628c00b467627a81e7cd4641cdd7547 | Raneem91/My-projects | /Paper rock .. scissors Game | 3,317 | 4.25 | 4 | #!/usr/bin/env python3
import random
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
moves = ['rock', 'paper', 'scissors']
"""The Player class is the parent class for all of the Players
in this game"""
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
pass
class HumanPlayer(Player):
def move(self):
move = 'none'
while move not in moves:
move = input('Enter rock, paper or scissors:\n')
if move not in moves:
print('please try again!!!')
return move
class reflectplayer(Player):
def __init__(self):
self.next_move = 'rock'
def move(self):
return self.next_move
def learn(self, my_move, their_move):
self.next_move = their_move
class RandomPlayer(Player):
def move(self):
return random.choice(moves)
class cycleplayer(Player):
def __init__(self):
self.next_move = 0
def move(self):
return moves[self.next_move]
def learn(self, my_move, their_move):
if self.next_move <= 1:
self.next_move = self.next_move+1
elif self.next_move == 2:
return moves[0]
def beats(one, two):
return (
(one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.p1.score = 0
self.p2.score = 0
def keep_score(self, p1, p2):
if beats(p1, p2):
self.p1.score = self.p1.score + 1
print('Player 1 Has Won The Round!!')
elif beats(p2, p1):
self.p2.score = self.p2.score + 1
print('Player 2 Has Won The Round!!')
else:
self.p1.score = self.p1.score
self.p2.score = self.p2.score
print('It is a Tie !!')
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
self.keep_score(move1, move2)
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print(self.p1.score, "-", self.p2.score)
if (self.p1.score > self.p2.score):
print('Player 1 Has Won The Game!!')
elif(self.p1.score < self.p2.score):
print('Player 2 Has Won The Game !!')
print("Game over!")
if __name__ == '__main__':
vaild_input = ['rock', 'reflect', 'random', 'cycle']
player_input = 'none'
while player_input not in vaild_input:
player_input = input('Choose a player random, reflect or cycle: \n')
if player_input not in vaild_input:
print('please try again!!')
my_dictionary = {
"rock": Game(HumanPlayer(), Player()),
"reflect": Game(HumanPlayer(), reflectplayer()),
"random": Game(HumanPlayer(), RandomPlayer()),
"cycle": Game(HumanPlayer(), cycleplayer())}
game = my_dictionary[player_input.lower()]
game.play_game()
|
e4eed096aed81be1e76ca69cf12351f6154eae8a | ajayk01/Python-Programing | /Sort/quicksort.py | 515 | 3.9375 | 4 | def part(a,l,h):
i = (l-1 )
pivot = a[h]
for j in range(l,h):
if a[j] <= pivot:
i = i+1
a[i],a[j] = a[j],a[i]
a[i+1],a[h] = a[h],a[i+1]
return ( i+1 )
def quickSort(a,l,h):
if l< h:
pi = part(a,l,h)
quickSort(a,l, pi-1)
quickSort(a, pi+1, h)
a=[];
n = int(input("Enter the no of the elements"))
for i in range(0,n):
k=int(input());
a.append(k);
print("The entered array is",a);
quickSort(a,0,n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %a[i]),
|
197bb561134e36d715306877a49398ff240852b8 | mdzimmerman/advent2018 | /13/day13.py | 6,759 | 3.546875 | 4 | # -*- coding: utf-8 -*-
from enum import Enum
import numpy as np
class Dir(Enum):
UP = 0
LEFT = 1
DOWN = 2
RIGHT = 3
class Cart:
dir_to_char = {
Dir.RIGHT: '>',
Dir.DOWN: 'v',
Dir.LEFT: '<',
Dir.UP: '^'}
cw = {
Dir.RIGHT: Dir.DOWN,
Dir.DOWN: Dir.LEFT,
Dir.LEFT: Dir.UP,
Dir.UP: Dir.RIGHT}
ccw = {
Dir.RIGHT: Dir.UP,
Dir.UP: Dir.LEFT,
Dir.LEFT: Dir.DOWN,
Dir.DOWN: Dir.RIGHT}
def __init__(self, n, x, y, d):
self.n = n
self.x = x
self.y = y
self.d = d
self.inters = 0
def __repr__(self):
return "Cart(n=%d x=%d y=%d d=%s)" % (self.n, self.x, self.y, self.d)
def as_char(self):
return self.dir_to_char[self.d]
def advance(self):
if self.d == Dir.RIGHT:
self.x += 1
elif self.d == Dir.DOWN:
self.y += 1
elif self.d == Dir.LEFT:
self.x -= 1
elif self.d == Dir.UP:
self.y -= 1
def rotcw(self):
self.d = self.cw[self.d]
def rotccw(self):
self.d = self.ccw[self.d]
def move(self, t):
if t == '-':
# just move straight in current direction
if self.d == Dir.RIGHT or self.d == Dir.LEFT:
self.advance()
else:
raise Exception("bad dir")
elif t == '|':
if self.d == Dir.UP or self.d == Dir.DOWN:
self.advance()
else:
raise Exception("bad dir")
elif t == '/':
if self.d == Dir.UP or self.d == Dir.DOWN:
self.rotcw()
self.advance()
elif self.d == Dir.LEFT or self.d == Dir.RIGHT:
self.rotccw()
self.advance()
else:
raise Exception("bad dir")
elif t == '\\':
if self.d == Dir.RIGHT or self.d == Dir.LEFT:
self.rotcw()
self.advance()
elif self.d == Dir.UP or self.d == Dir.DOWN:
self.rotccw()
self.advance()
else:
raise Exception("bad dir")
elif t == '+':
i = self.inters % 3
if i == 0:
self.rotccw() # turn left
elif i == 1:
pass # go straight
else:
self.rotcw() # turn left
self.inters += 1
self.advance()
else:
pass
@staticmethod
def parsecartdir(c):
if c == '>':
return Dir.RIGHT
elif c == 'v':
return Dir.DOWN
elif c == '<':
return Dir.LEFT
elif c == '^':
return Dir.UP
else:
return None
class Track:
def __init__(self, filename):
self.ncol = 0
self.nrow = 0
self._init_grid(filename)
self._init_carts()
def _init_grid(self, filename):
lines = []
with open(filename, "r") as fh:
for l in fh:
l = l.rstrip()
self.nrow += 1
if len(l) > self.ncol:
self.ncol = len(l)
lines.append(l)
buffer = ""
for l in lines:
buffer += l.ljust(self.ncol, " ")
self.grid = np.array([c for c in buffer],
dtype="str").reshape((self.nrow, self.ncol))
def _init_carts(self):
self.carts = []
self.cart_index = {}
n = 0
for j in range(self.nrow):
for i in range(self.ncol):
d = Cart.parsecartdir(self.grid[j,i])
if d != None:
self.carts.append(Cart(n, i, j, d))
if d == Dir.RIGHT or d == Dir.LEFT:
self.grid[j,i] = '-'
elif d == Dir.UP or d == Dir.DOWN:
self.grid[j,i] = '|'
n += 1
self._index_carts()
def _index_carts(self):
self.cart_index.clear()
for c in self.carts:
i = (c.x, c.y)
if i not in self.cart_index:
self.cart_index[i] = []
self.cart_index[i].append(c)
def printgrid(self):
self._index_carts()
for j in range(self.nrow):
for i in range(self.ncol):
if (i, j) in self.cart_index:
carts = self.cart_index[(i, j)]
if len(carts) > 1:
print('X', end="")
else:
print(carts[0].as_char(), end="")
else:
print(self.grid[j,i], end="")
print()
def run_to_crash(self, verbose=False):
collision = False
t = 0
if verbose:
print("t=%d" % (t,))
self.printgrid()
while not collision:
self.carts.sort(key=lambda c: (c.x, c.y))
for cart in self.carts[:]:
tr = self.grid[cart.y,cart.x]
cart.move(tr)
for othercart in self.carts[:]:
if cart.n != othercart.n and cart.x == othercart.x and cart.y == othercart.y:
collision = True
return (cart.x, cart.y)
t += 1
if verbose:
print("t=%d" % (t,))
self.printgrid()
def run_to_all_crash(self, verbose=False):
t = 0
count = len(self.carts)
if verbose:
print("t=%d carts=%d" % (t, count))
self.printgrid()
while count > 1:
self.carts.sort(key=lambda c: (c.x, c.y))
for cart in self.carts[:]:
tr = self.grid[cart.y,cart.x]
cart.move(tr)
for othercart in self.carts[:]:
if cart.n != othercart.n and cart.x == othercart.x and cart.y == othercart.y:
self.carts.remove(cart)
self.carts.remove(othercart)
self._index_carts()
t += 1
if verbose:
print("t=%d carts=%d" % (t, count))
self.printgrid()
count = len(self.carts)
#self.move_carts()
print("last cart %s" % (self.carts[0],))
t = Track("test.txt")
print(t.run_to_crash(verbose=True))
inp = Track("input.txt")
print(inp.run_to_crash())
t2 = Track("test2.txt")
t2.run_to_all_crash(verbose=True)
inp2 = Track("input.txt")
inp2.run_to_all_crash() |
68ec65a664d54a36f22878076115dd23278550e5 | medha1511/pythonPprograms | /area.py | 460 | 4.21875 | 4 | #arae and circumference of circle
'''r=2
pi=3.14
print(pi*r**2)'''
'''pi=3.14
r=float(input("enter r"))
a=(pi*r**2)
c=2*pi*r
print("area of circle is",a,"circumference is",c)'''
#arae of square
l=float(input("enter side of square"))
area=l**2
print("arae of sqr is",area)
#arae of rect
l=float(input("enter length of rect"))
b=float(input("enter breadth of rect"))
arae=l*b
print("arae of rect is",arae)
|
d4cfddd6735e751ff39658a9aa42e87da72d91cc | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_118/2547.py | 866 | 3.640625 | 4 | import math
import sys
def isPalindrome(x):
palindrome = True
xstr = str(x)
for dindex in range(len(xstr)):
if (xstr[dindex] != xstr[-dindex-1]):
palindrome = False
return palindrome
def solve(a,b):
count = 0
x = math.sqrt(a)
xs = int(x * x)
if (x==int(x)) and isPalindrome(int(x)) and isPalindrome(xs):
count = 1
# print 'pal: ', x, xs
x = int(x) + 1
xs = x*x
while (xs <= b):
if isPalindrome(xs) and isPalindrome(x):
count += 1
# print 'pal: ', x, xs
x = x+1
xs = x*x
return count
filename = sys.argv[1]
fin = open(filename, 'r')
#fout = open('p3res.txt', 'w')
cases = int(fin.readline())
for case in range(cases):
[a, b] = fin.readline().split()
# print a, b
print "Case #{}: {}".format(case + 1, solve(int(a), int(b)))
#fout.write("Case #{}: {}".format(case + 1, solve(int(a), int(b))))
fin.close()
#fout.close()
|
f39fde8d85ed67b93a7c7ccc664758107f38fc8b | Greengon/CheesPuzzleBuilder | /Board/ChessBoard.py | 7,303 | 4.15625 | 4 | from Pieces.NoPiece import NoPiece
from Pieces.Bishop import Bishop
from Pieces.King import King
from Pieces.Knight import Knight
from Pieces.Pawn import Pawn
from Pieces.Queen import Queen
from Pieces.Rook import Rook
class ChessBoard:
"""
This class represent the board itself.
It is build off tiles object and game pieces
objects when the pieces are set
"""
game_tiles = []
original_game_tiles = []
"""
All classes have function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to objects properties,
or other operations that are necessary to do when the object is
being created.
"""
def __init__(self):
self.game_tiles.insert(0, Rook("Black", 0))
self.game_tiles.insert(1, Knight("Black", 1))
self.game_tiles.insert(2, Bishop("Black", 2))
self.game_tiles.insert(3, Queen("Black", 3))
self.game_tiles.insert(4, King("Black", 4))
self.game_tiles.insert(5, Bishop("Black", 5))
self.game_tiles.insert(6, Knight("Black", 6))
self.game_tiles.insert(7, Rook("Black", 7))
for i in range(8, 16):
self.game_tiles.insert(i, Pawn("Black", i))
for i in range(16, 48):
self.game_tiles.insert(i, NoPiece(i))
for i in range(48, 56):
self.game_tiles.insert(i, Pawn("White", i))
self.game_tiles.insert(56, Rook("White", 56))
self.game_tiles.insert(57, Knight("White", 57))
self.game_tiles.insert(58, Bishop("White", 58))
self.game_tiles.insert(59, Queen("White", 59))
self.game_tiles.insert(60, King("White", 60))
self.game_tiles.insert(61, Bishop("White", 61))
self.game_tiles.insert(62, Knight("White", 62))
self.game_tiles.insert(63, Rook("White", 63))
self.original_game_tiles = self.game_tiles.copy()
# Testing function only
def test_print_board(self):
count = 0
for tile in range(64):
print("|", end=self.game_tiles[tile].to_string())
count += 1
if count == 8:
print("|", end='\n')
count = 0
def load_board_from_file_path(self, path):
"""
Load a chess board from .txt file on the local computer.
:param path: The path to the .txt file.
:return: None
"""
count = 0
with open(path) as board_loaded:
for line in board_loaded:
for char in line:
if char != '|' and char != '\n':
if char == '-':
self.game_tiles[count] = NoPiece(count)
count += 1
if char == 'R':
self.game_tiles[count] = Rook("Black", count)
count += 1
if char == 'N':
self.game_tiles[count] = Knight("Black", count)
count += 1
if char == 'B':
self.game_tiles[count] = Bishop("Black", count)
count += 1
if char == 'Q':
self.game_tiles[count] = Queen("Black", count)
count += 1
if char == 'K':
self.game_tiles[count] = King("Black", count)
count += 1
if char == 'P':
self.game_tiles[count] = Pawn("Black", count)
count += 1
if char == 'r':
self.game_tiles[count] = Rook("White", count)
count += 1
if char == 'n':
self.game_tiles[count] = Knight("White", count)
count += 1
if char == 'b':
self.game_tiles[count] = Bishop("White", count)
count += 1
if char == 'q':
self.game_tiles[count] = Queen("White", count)
count += 1
if char == 'k':
self.game_tiles[count] = King("White", count)
count += 1
if char == 'p':
self.game_tiles[count] = Pawn("White", count)
count += 1
self.original_game_tiles = self.game_tiles.copy()
print("Done copying from file")
def get_original_tiles(self):
return self.original_game_tiles
def set_game_tiles(self, tiles_to_copy):
count = 0
for piece in tiles_to_copy:
if piece.to_string() != '|' and piece.to_string() != '\n':
if piece.to_string() == '-':
self.game_tiles[count] = NoPiece(count)
count += 1
if piece.to_string() == 'R':
self.game_tiles[count] = Rook("Black", count)
count += 1
if piece.to_string() == 'N':
self.game_tiles[count] = Knight("Black", count)
count += 1
if piece.to_string() == 'B':
self.game_tiles[count] = Bishop("Black", count)
count += 1
if piece.to_string() == 'Q':
self.game_tiles[count] = Queen("Black", count)
count += 1
if piece.to_string() == 'K':
self.game_tiles[count] = King("Black", count)
count += 1
if piece.to_string() == 'P':
self.game_tiles[count] = Pawn("Black", count)
count += 1
if piece.to_string() == 'r':
self.game_tiles[count] = Rook("White", count)
count += 1
if piece.to_string() == 'n':
self.game_tiles[count] = Knight("White", count)
count += 1
if piece.to_string() == 'b':
self.game_tiles[count] = Bishop("White", count)
count += 1
if piece.to_string() == 'q':
self.game_tiles[count] = Queen("White", count)
count += 1
if piece.to_string() == 'k':
self.game_tiles[count] = King("White", count)
count += 1
if piece.to_string() == 'p':
self.game_tiles[count] = Pawn("White", count)
count += 1
print("Done restarting.")
"""
Make a move on the board.
"""
# TODO: check if it is legal move
def move(self, moved_piece, destination):
if moved_piece.position != destination:
print("moved_piece.position: " + str(moved_piece.position) + " destination: " + str(destination))
self.game_tiles[moved_piece.position] = NoPiece(moved_piece.position)
self.game_tiles[destination] = moved_piece
moved_piece.position = destination
|
fbf2cbe2781bd0d2abc3f0f2341cdacc4f8f06c4 | MerleLiuKun/my-python | /books/flute-py/chap14/sentence_iter.py | 1,074 | 3.96875 | 4 | """
迭代器模式实现
可迭代的对象一定不能是自身的迭代器
可迭代的队形必须实现 __iter__ 方法,但不能实现 __next__ 方法.
迭代器应该一直可以迭代,迭代器的 __iter__ 方法应该返回自身。
"""
import re
import reprlib
RE_WORD = re.compile(r"\w+")
class Sentence:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(self.text)
def __repr__(self):
return "Sentence(%s)" % reprlib.repr(self.text)
def __iter__(self):
return SentenceIterable(self.words)
class SentenceIterable:
def __init__(self, words):
self.words = words
self.index = 0
# 无参 next
def __next__(self):
try:
word = self.words[self.index]
except IndexError:
raise StopIteration
self.index += 1
return word
# 返回本身
def __iter__(self):
return self
if __name__ == "__main__":
s = Sentence("This is sentence v2")
for wd in s:
print(wd)
|
b1da9fd2dfcc4d0ddc3abd2d7a4f694cd61bcb20 | thangarajan8/misc_python | /search.py | 792 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 21:40:44 2020
@author: Thanga
"""
class Search():
def __init__(self,data,search_item):
self.data= data
self.search_item = search_item
pass
def linear(self,search_item=None):
"""
if element is found you will get a postive integer which is the index of
the search element else -1
"""
for index,element in enumerate(self.data):
if element == search_item:
return index
break
return -1
def binary(self):
len_data = len(data) - 1
left = 0
data = [1,2,3]
s = Search([1,2,3],10)
print(s.linear())
right = len(data)-1
left = 0
while left < right:
mid = right/2
break
|
1b6177d4fc5e40532ca5ee792bd706318781470e | chenyur/projecteuler | /7.py | 548 | 3.921875 | 4 | import math
import sys
import pdb
def prime(index):
current = 2
count = 2
while 1:
for i in range(2, current):
if current % i == 0:
break
if i == current - 1:
if count % 100 == 0:
print(current, count)
count += 1
# pdb.set_trace()
if count > int(index):
return current
else: current += 1
def main(index):
print("finding nth prime n = " + str(index))
print(prime(index))
main(sys.argv[1])
|
60fbe0e128e0293877342985692ca10198b305d8 | kateodell/Exercise06 | /wordcount.py | 784 | 4.25 | 4 | # Word Count (Exercise 06)
import operator
from sys import argv
import string
# open, read, and put file into list where each element is delineated by a 'space'
# or period
script, filename = argv
file_text = open(filename)
file_content = file_text.read()
# initialize a dictionary
word_count = {}
words_in_text = file_content.split()
for word in words_in_text:
word = word.strip(string.punctuation)
# word = word.strip('\r\n\t ')
if word != '':
word = word.lower()
word_count[word] = word_count.get(word,0) + 1
# display words with sorting by value and alphabetically
word_count_sorted = sorted(word_count.iteritems(), key= lambda word: (word[1], word[0]), reverse = True)
for word, count in word_count_sorted:
print "The word %s occurs %d times." % (word, count)
|
8a5e6f0cfb3933effedddace26fa905cd5f6b474 | sanjeevseera/Hackerrank-challenges | /Arrey/Array_Manipulation.py | 1,302 | 3.9375 | 4 | """
Input Format
The first line contains two space-separated integers n and m, the size of the array and the number of operations.
Each of the next m lines contains three space-separated integers a, b and k, the left index, right index and summand.
Output Format
Return the integer maximum value in the finished array.
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
Explanation
After the first update list will be 100 100 0 0 0.
After the second update list will be 100 200 100 100 100.
After the third update list will be 100 200 200 200 100.
The required answer will be 200.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
nlist = [0]*(n+1)
for qi in queries:
x, y, incr = qi
nlist[x-1] += incr
if((y)<=len(nlist)):
nlist[y] -= incr;
rmax = tmax= 0
for i in nlist:
tmax=tmax+i;
if(rmax < tmax):
rmax = tmax
return rmax
if __name__ == '__main__':
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
print(result)
|
33a82e90a28dedcaf3eba131b29ddb78d9059dba | rodrigoc-silva/Python-course | /Lab03_functions/exercise-24.py | 1,937 | 4.5625 | 5 |
#This program calculates the area of a triangle.
def getData() -> (float, float):
'''ask for user input the length and height of the triangle'''
length = float(input("Enter the length of the triangle: "))
height = float(input("Enter the perpendicular height of the triangle: "))
return length, height
def trigArea(length:float, height:float) -> (float):
'''Calculate the triangle area'''
area = length * height / 2
return area
def displayData(length:float, height:float, area:float) -> None:
'''output the data'''
print("The length of the triangle is ", length)
print("The height of the triangle is ", height)
print("The area of the triangle is ", area)
def main():
length, height = getData()
area = trigArea(length, height)
displayData(length, height, area)
if __name__=="__main__":
main()
# case 1
# Enter the length of the triangle: 10
# Enter the perpendicular height of the triangle: 10
# The length of the triangle is 10.0
# The height of the triangle is 10.0
# The area of the triangle is 50.0
# case 2
# Enter the length of the triangle: 1
# Enter the perpendicular height of the triangle: 1
# The length of the triangle is 1.0
# The height of the triangle is 1.0
# The area of the triangle is 0.5
# case 3
# Enter the length of the triangle: 7.5
# Enter the perpendicular height of the triangle: 8.7
# The length of the triangle is 7.5
# The height of the triangle is 8.7
# The area of the triangle is 32.625
# case 4
# Enter the length of the triangle: -10
# Enter the perpendicular height of the triangle: -10
# The length of the triangle is -10.0
# The height of the triangle is -10.0
# The area of the triangle is 50.0
# case 5
# Enter the length of the triangle: 2.25
# Enter the perpendicular height of the triangle: 1.75
# The length of the triangle is 2.25
# The height of the triangle is 1.75
# The area of the triangle is 1.96875 |
42693bc3bda20d6c9d63149607862dd5f68f2d0b | GabrielGalucio/Visualiza-o-de-dados-com-Python | /001_grafico_linha.py | 438 | 4 | 4 | # Criando uma demonstração de gráfico em linha com o mtaplotlib.py
# Importanto a Bilbioteca
import matplotlib.pyplot as plt
x = [1, 2, 5] # Definindo a largura
y = [2, 3, 7] # Definindo a altura
# Inserindo um título no gráfico
plt.title("Gráfico com Matplotlib")
# Inserindo um título no eixo X e Y
plt.xlabel("Eixo X")
plt.ylabel("Eixo Y")
# Chamando a função de plotagem plot() dos eixos x e y
plt.plot(x, y)
plt.show()
|
1c8edcffe4217a5279bbfd34002b49c749f9ae9c | jy-hwang/CodeItPython | /j_z/somclass_bad_variableName.py | 627 | 4.1875 | 4 | # 추상화의 안 좋은 예시
class SomeClass:
class_variable = 0.02
def __init__(self, variable_1, variable_2):
self.variable_1 = variable_1
self.variable_2 = variable_2
def method_1(self, some_value):
self.variable_2 += some_value
def method_2(self, some_value):
if self.variable_2 < some_value:
print("Insufficient balance!")
else:
self.variable_2 -= some_value
def method_3(self):
self.variable_2 *= 1 + SomeClass.class_variable
# 이런 x 같은 변수명이랑 클래스 명 쓰는 놈 있으면 뚝배기를 깨버려야 |
0f56cfce193db803403b61faa00270bacfc2d646 | UBC-MDS/prepackPy | /prepackPy/stdizer.py | 4,522 | 4.0625 | 4 | #!/usr/bin/env python
import numpy as np
import pandas as pd
from typing import Any, List
def stdizer(X: Any, method: str = "mean_sd", method_args = None) -> Any:
"""
Standardize a dataset (X) based on a specificed standardization method (method & method_args).
Parameters
----------
X: numpy array, pandas dataframe
an input dataset
method: string
a method of standardization
All columns of standardized X will be calucated using the equation below:
X_std[,i] = (X[,i] - first_value)/second_value
allowable methods include:
1. "mean_sd": subtracting the mean value of each column (first_value) and
dividing by standard deviation value of each column (second_value)
2. "mean": subtracting the mean value of each column (first_value) and dividing by 1 (second_value)
3. "sd": subtracting 0 (first_value) and dividing by standard deviation of each column (second_value)
4. "min_max": subtracting min value of each column (first_value) and
dividing by max value of each column (second_value)
5. "own": subtracting an user specified mean value of each column (first_value) and
dividing by another user specified standard deviation value of each column (second_value)
method_args: list
The value of this argument will be None except when method="own"
Users need to identify the mean (first_value) and standard deviation (second_value) for each column in X,
This will be passed into the function as a list of lists:
[[mean_col_1, std_col_1], [mean_col_2, std_col_2]...[mean_col_n, std_col_n]]
Returns
-------
X_std: numpy array
a dataset standardized based on the method argument
Example
-------
>>> import numpy as np
>>> from prepackPy import stdizer as sd
>>> X = np.array([[-1, 0], [2, 1], [1, -2], [1, 1]])
>>> X
array([[-1, 0],
[ 2, 1],
[ 1, -2],
[ 1, 1]])
>>> X_std = sd.stdizer(X, method="mean_sd", method_args=None)
>>> X_std
array([[-1.60591014, 0. ],
[ 1.14707867, 0.81649658],
[ 0.22941573, -1.63299316],
[ 0.22941573, 0.81649658]])
"""
# Testing that the correct types have been passed into the function
if not isinstance(X, (pd.DataFrame, np.ndarray)):
raise TypeError("X must be of numpy.ndarray or pandas.dataframe type")
if not isinstance(method, str):
raise TypeError("method must be a string type")
if method_args:
if not isinstance(method_args, list):
raise TypeError("Method args must be of type list")
# Make sure only the 5 allowed methods have been passed into the function
if not method in ["mean_sd","mean", "sd", "min_max", "own"]:
raise ValueError("Invalid input for the method argument")
# Transform the dataset (X) to a numpy array
X_stdized: Any = np.asarray(X)
X_stdized = X_stdized.astype(float)
# Make sure the arguments in method_args are valid
if method == "own":
if len(method_args) > X_stdized.shape[1]:
raise ValueError('Too many method arguments have been entered')
if method == "own":
if len({len(i) for i in method_args}) == 2:
raise ValueError('All lists in method_args must numeric and of length 2 (a. mean, b. standard deviation)')
# Create the standardized matrix
if (method == "mean_sd"):
for i in range(0,X_stdized.shape[1]):
mean = np.mean(X_stdized[:,i])
std = np.std(X_stdized[:,i])
X_stdized[:,i] = (X_stdized[:,i] - mean)/std
elif (method == "mean"):
for i in range(0,X_stdized.shape[1]):
mean = np.mean(X_stdized[:,i])
X_stdized[:,i] = (X_stdized[:,i] - mean)
elif (method == "sd"):
for i in range(0,X_stdized.shape[1]):
std = np.std(X_stdized[:,i])
X_stdized[:,i] = (X_stdized[:,i])/std
elif (method == "min_max"):
for i in range(0,X_stdized.shape[1]):
min_val = np.min(X_stdized[:,i])
max_val = np.max(X_stdized[:,i])
X_stdized[:,i] = (X_stdized[:,i] - min_val)/max_val
else:
for i in range(0,X_stdized.shape[1]):
mean = method_args[i][0]
std = method_args[i][1]
X_stdized[:,i] = (X_stdized[:,i] - mean)/std
return X_stdized
|
90cd163a4eb85435049758fbc9b0ca3112ceb5fa | Liguangchuang/base_knowledge | /数据结构基础/面试遇到——编程真题.py | 5,042 | 3.703125 | 4 | ###############################################################################
'''给定4个点,判断是否能组成正方形'''
def calcu_distance(p1, p2):
return (p1[0] - p2[0])*(p1[0] - p2[0]) + (p1[1] - p2[1])*(p1[1] - p2[1])
def is_square(p1, p2, p3, p4):
distance_list = []
distance_list.append(calcu_distance(p1, p2))
distance_list.append(calcu_distance(p1, p3))
distance_list.append(calcu_distance(p1, p4))
distance_list.append(calcu_distance(p2, p3))
distance_list.append(calcu_distance(p2, p4))
distance_list.append(calcu_distance(p3, p4))
len1 = distance_list[0]
for distan in distance_list:
if distan != len1:
len2 = distan
breakz
num1 = 0
num2 = 0
for distan in distance_list:
if distan == len1:
num1 += 1
elif distan == len2:
num2 += 1
if (num1 == 4 and num2 == 2) or (num1 == 2 and num2 == 4):
return True
else:
return False
p1 = [10, 0]
p2 = [10, 1]
p3 = [11, 0]
p4 = [11, 1]
print(is_square(p1, p2, p3, p4))
###求所有的完数(完数:所有的因子的和刚好等于这个数本身)######################################################
def com_baiyi_getPerfectNumbers(n):
arr = []
for m in range(1, n+1):
arr_yinzi = ji_suan_yin_zi(m)
if sum(arr_yinzi) == m:
arr.append(m)
return arr
def ji_suan_yin_zi(m):
arr = []
for i in range(1, m):
if m % i == 0:
arr.append(i)
return arr
print(com_baiyi_getPerfectNumbers(40))
###求两个数的最大公约数###############################################################################
def hfc(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if (x % i == 0) and (y % i == 0):
hcf_ = i
return hcf_
arr_tmp = input().split(' ') ##特别重要
arr = []
for e in arr_tmp:
arr.append(int(e))
x = arr[0]
y = arr[1]
hfc(x, y)
###快速排序###############################################################################
def partition(arr, l_idx, r_idx):
base_value = arr[l_idx] ###指定位置对于快排的质量非常重要!!(现在选定最左边的位置作为指定位置)
while l_idx < r_idx:
while (l_idx < r_idx) and (arr[r_idx] >= base_value):
r_idx -= 1
arr[l_idx] = arr[r_idx]
while (l_idx < r_idx) and arr[l_idx] <= base_value:
l_idx += 1
arr[r_idx] = arr[l_idx]
arr[l_idx] = base_value
return l_idx ##这里是有return的
def quick_sort(arr, l_idx, r_idx):
if l_idx < r_idx:
mid_index = partition(arr, l_idx, r_idx)
self.quick_sort(arr, l_idx, mid_index-1) ##part_index的元素不需要再纳入排序
self.quick_sort(arr, mid_index+1, r_idx)
###找出最小k个数##########################################################################
###稀疏矩阵的乘法##########################################################################
def dense_to_sparse(dense_mat):
size = [len(dense_mat), len(dense_mat[0])]
spare_mat = []
for r in range(0, len(dense_mat)):
for c in range(0, len(dense_mat[0])):
if dense_mat[r][c] != 0:
spare_mat.append((r, c, dense_mat[r][c]))
return spare_mat, size
def sparse_to_dense(spare_mat, size):
dense_mat = [[0] * size[1] for row in range(size[0])]
for tuple_ in spare_mat:
dense_mat[tuple_[0]][tuple_[1]] = tuple_[2]
return dense_mat
def matrix_multiply(A, B):
res = [[0 for c in range(0, len(B[0]))] for r in range(0, len(A))] #先构造一个符合size的全0矩阵
for Ar in range(0, len(A)):
for Ac in range(0, len(A[0])):
if A[Ar][Ac] != 0: #对于是0的元素,就不需要修改res了
for Bc in range(0, len(B[0])):
if B[Ac][Bc] != 0: #对于是0的元素,就不需要修改res了
res[Ar][Bc] += A[Ar][Ac] * B[Ac][Bc]
return res
if __name__ == '__main__':
A = [[1,0,0],[-1,0,3]]
B = [[7,0,0],[0,0,0],[0,0,1]]
result = SparseMatrixMultiply(A, B)
print(result)
##############################################################################
##数组的长度为101,值域为[1,100],有且仅有一个数字重复,找出该数字,要求空间复杂度为O(1),时间复杂度为O(n):
def solu(arr):
for idx in range(0, len(arr)):
if arr[idx] in (arr[0: idx] + arr[idx+1: ]):
return arr[idx]
def solu(arr):
sum_ = 0
for i in range(0, len(arr)):
sum_ += i
res = sum_ - (n(n-1)/2)
return res
##############################################################################
##递归实现阶层函数
def fac(n):
if n == 1:
return 1
elif n <= 0:
return 0
return n * fac(n-1)
|
e030024ceae2acdeb22f0270fe929df5b392c292 | choly1985/liuhua_src | /LearningPython-master/SecondWeek/ForthDay/task.py | 2,698 | 3.953125 | 4 | """
@Name: task
@Version:
@Project: PyCharm Community Edition
@Author: liujinjia
@Data: 2017/11/21
"""
# 第二个作业
class Dog:
def __init__(self,weight,height,hair,type):
self.weight = weight
self.height = height
self.hair = hair
self.type = type
type = '狗'
# type 没有被用到
# 第二个 覆盖了buildin module中的type
def bark(self):
print('汪汪汪')
def display(self):
print(self.weight)
print(self.height)
print(self.hair)
self.bark()
return '我是一只{},我非常忠心。'.format(self.type)
class mole_cricket(Dog):
def __init__(self):
self.weight = '我很轻'
self.height = '我很高'
self.hair = '我的毛发不长'
self.type = '土狗'
super(mole_cricket,self).__init__(self.weight,self.height,self.hair,self.type)
class big_dog(Dog):
def __init__(self):
self.weight = '我很重'
self.height = '我很高'
self.hair = '我的毛发很长'
self.type = '大型犬'
super(big_dog,self).__init__(self.weight,self.height,self.hair,self.type)
class little_dog(Dog):
def __init__(self):
self.weight ='我很轻'
self.height ='我不高'
self.hair = '我毛发长'
self.type = '小型犬'
super(little_dog,self).__init__(self.weight,self.height,self.hair,self.type)
# 第一个作业
from abc import ABCMeta
from abc import abstractmethod
class Animal(metaclass=ABCMeta):
@abstractmethod
def call(self):
"""
叫声
:return:
"""
@abstractmethod
def fly(self):
"""
是否会飞
:return:
"""
@abstractmethod
def swim(self):
"""
是否会游泳
:return:
"""
class DOG(Animal):
def call(self):
print('这是一只会汪汪汪叫的狗')
def fly(self):
print('这是一只不会飞的狗')
def swim(self):
print('狗会游泳')
class CAT(Animal):
def call(self):
print('这是一只会喵喵喵叫的猫')
def fly(self):
print('这是一只不会飞的猫')
def swim(self):
print('猫不会游泳')
class DUCK(Animal):
def call(self):
print('这是一只会嘎嘎嘎叫的鸭子')
def fly(self):
print('这是一只不会飞的鸭子')
def swim(self):
print('鸭子会游泳')
class BIRD(Animal):
def call(self):
print('这是一只会喳喳叫的鸟')
def fly(self):
print('这是一只会飞的小鸟')
def swim(self):
print('会游泳的鸟') |
612d74f610fe076c2034cc90d67593f48a071157 | deepaksng29/computer-science-a2 | /pythonLists/Deepak Ex3.py | 701 | 3.9375 | 4 | # Deepak Singh
# Ex.3
students = []
markList = []
sortedMarks = []
def __init__():
studentName = input('Please enter your name: ')
students.append(studentName)
for i in range(10):
mark = int(input('Please enter your mark: '))
markList.append(mark)
sortedMarks = sorted(markList, reverse = True)
return sortedMarks
sortedMarks = (__init__())
size = len(sortedMarks)
totMarks = 0
for i in sortedMarks:
totMarks += i
avrMark = totMarks / size
print("Student name:" , students[0])
print("Student average mark:", avrMark)
print("Student top 3 marks:", sortedMarks[0:2])
print("Student bottom 3 marks:", sortedMarks[size-4:size-1])
|
aae80f89b3cce4e6a6045ea2245a65fa688e5ae6 | ritlinguine/linguine-python | /linguine/ops/remove_hashtags.py | 378 | 3.734375 | 4 | """
Removes all hashtag tokens, #, from a text.
Returns the text as a single string separated by spaces.
"""
import re
class RemoveHashtags:
def run(self, data):
results = []
for corpus in data:
temp_corpus = re.sub(r'#', '', corpus.contents)
corpus.contents = temp_corpus
results.append(corpus)
return results
|
18270095f604a835771290fa502733c3b7ccef7c | shenmishajing/python | /week12/6-4.py | 478 | 3.578125 | 4 | def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
def PrintFN(m, n):
res = []
cur = 1
cur_number = fib(cur)
while cur_number < n:
if m <= cur_number <= n:
res.append(cur_number)
cur += 1
cur_number = fib(cur)
return res
m, n, i = input().split()
n = int(n)
m = int(m)
i = int(i)
b = fib(i)
print("fib({0}) = {1}".format(i, b))
fiblist = PrintFN(m, n)
print(len(fiblist))
|
925294e9c03ec5c6ba42ad12c90106a2a7bc4fda | sug5806/TIL | /Python/data_struct/Linked_list/dummy_double_linked_list/double_linked_list.py | 5,500 | 3.546875 | 4 | class Node:
def __init__(self, data=None):
self.__data = data
self.__previous = None
self.__next = None
def __del__(self):
print(f"deleted data : [{self.__data}]")
@property
def data(self):
return self.__data
@data.setter
def data(self, data):
self.__data = data
@property
def previous(self):
return self.__previous
@previous.setter
def previous(self, link):
self.__previous = link
@property
def next(self):
return self.__next
@next.setter
def next(self, link):
self.__next = link
class DoubleLinkedList:
def __init__(self):
# 더미의 생성시점은 DLL이 만들어 질때
# head, tail, d_size
self.head = Node()
self.tail = Node()
self.d_size = 0
self.head.next = self.tail
self.tail.previous = self.head
def size(self):
return self.d_size
def empty(self):
if self.d_size == 0:
return True
else:
return False
# insert 계열
# 리스트의 맨 앞(HEAD의 오른쪽)에 데이터 추가
def add_first(self, data):
new_node = Node(data)
# new_node를 연결
new_node.next = self.head.next
new_node.previous = self.head
# 기존 node에 new_node를 연결
self.head.next.previous = new_node
self.head.next = new_node
self.d_size += 1
# 리스트의 맨 뒤(TAIL의 왼쪽)에 데이터 추가
def add_last(self, data):
new_node = Node(data)
# new_node를 연결
new_node.next = self.tail
new_node.previous = self.tail.previous
# 기존 node에 new_node를 연결
self.tail.previous.next = new_node
self.tail.previous = new_node
self.d_size += 1
# 특정 리스트의 오른쪽에 데이터 추가
def insert_after(self, data, node):
if node == None:
print("노드가 존재안함")
return
new_node = Node(data)
# new_node를 연결
new_node.previous = node
new_node.next = node.next
# 기존 node에 new_node 연결
node.next.previous = new_node
node.next = new_node
print(f"{data} 추가 완료")
self.d_size += 1
# 특정 리스트의 왼쪽에 데이터 추가
def insert_before(self, data, node):
if node == None:
print("노드가 존재안함")
return
new_node = Node(data)
# new_node를 연결
new_node.next = node
new_node.previous = node.previous
# 기존 node에 new_node 연결
node.previous.next = new_node
node.previous = new_node
print(f"{data} 추가 완료")
self.d_size += 1
# Search 계열
def search_forward(self, target):
temp = self.head.next
while temp is not self.tail:
if temp.data == target:
return temp
else:
temp = temp.next
return None
def search_backward(self, target):
temp = self.tail.previous
while temp is not self.tail:
if temp.data == target:
return temp
else:
temp = temp.previous
return None
# Delete 계열
def delete_first(self):
if self.empty():
print("connected Node is nothing")
return
self.head.next = self.head.next.next
self.head.next.previous = self.head
self.d_size -= 1
def delete_last(self):
if self.empty():
print("nothing connected Node")
return
self.tail.previous = self.tail.previous.previous
self.tail.previous.next = self.tail
self.d_size -= 1
def delete_node(self, node):
if self.empty():
print("nothing connected Node")
return
node.previous.next = node.next
node.next.previous = node.previous
self.d_size -= 1
# 편의 함수 - gennerator
def traverse(self, start=True):
# 리스트의 첫 데이터부터 순회!
if start:
temp = self.head.next
while temp is not self.tail:
yield temp
temp = temp.next
else:
# 리스트의 마지막 데이터부터 순회!
temp = self.tail.previous
while temp is not self.head:
yield temp
temp = temp.previous
def show_list(d_list):
g = d_list.traverse()
for node in g:
print(node.data, end=" ")
print()
if __name__ == "__main__":
dll1 = DoubleLinkedList()
dll1.add_last(1)
dll1.add_last(3)
dll1.add_last(5)
dll1.add_last(7)
dll1.add_last(9)
dll1.insert_after(4, dll1.search_forward(3))
dll1.insert_before(2, dll1.search_forward(3))
dll1.insert_before(10, dll1.search_forward(4))
show_list(dll1)
# 얘가 4를 가리키고 있으므로 None으로 해주지 않으면 delete 메시지가 뜨지 않음
searched_data = dll1.search_forward(4)
if searched_data:
print(f"searched data : {searched_data.data}")
else:
print("there is no data")
dll1.delete_first()
dll1.delete_last()
dll1.delete_last()
dll1.delete_last()
dll1.delete_node(searched_data)
searched_data = None
show_list(dll1)
print("*" * 100)
|
0e71ddab7103aa963bb99ce00963f12f16cc8eed | sayahna22/sayahna | /python/right shift.py | 73 | 3.578125 | 4 | m=int(input("Enter the no"))
n=int(input("Enter the times"))
print(m>>n)
|
4e6e7c64230eb847fa427d17adeb73b5ba22ed58 | gsrr/leetcode | /hackerrank/Moody_Analytics_Women_in_Engineering_Hackathon/strong_correlation.py | 299 | 3.5625 | 4 | #!/bin/python
import sys
def solve(n, p, d):
# Complete this function
print n, p, d
if __name__ == "__main__":
n = int(raw_input().strip())
p = map(int, raw_input().strip().split(' '))
d = map(int, raw_input().strip().split(' '))
result = solve(n, p, d)
print result
|
993fa53049f1e08e1f4cf786f61040052c6793f9 | ksgifford/data-structures | /src/d_graph.py | 2,523 | 4.15625 | 4 | """Defines data structure for implementing simple directed graph structure."""
# -*- coding: utf-8 -*-
class DGraph(object):
"""Class for implementing our direted graph structure."""
def __init__(self):
"""Initialize an empty dict for storing the graph."""
self._d_graph = {}
def nodes(self):
"""Return list of keys in the dict, which represent node names."""
return list(self._d_graph.keys())
def edges(self):
"""Return a list of edges that originate from each node."""
edge_list = []
for key, val in self._d_graph.items():
for node in val:
edge_list.append('>'.join((key, node)))
return edge_list
def add_node(self, node):
"""Add specified node to graph and intialize an empty set of edges."""
self._d_graph[node] = set()
def add_edge(self, node1, node2):
"""Create new edge from node1 to node2 if it does not already exist."""
self._d_graph.setdefault(node1, set()).add(node2)
self._d_graph.setdefault(node2, set())
def del_node(self, node):
"""Remove specified node from graph."""
try:
del self._d_graph[node]
for k, v in self._d_graph.items():
try:
v.remove(node)
except KeyError:
pass
except KeyError:
raise KeyError("Node not found in graph.")
def del_edge(self, node1, node2):
"""Remove edge from node1 to node2."""
try:
self._d_graph[node1].remove(node2)
except KeyError:
raise KeyError("Edge does not exist from {n1} to {n2}."
"".format(n1=node1, n2=node2))
def has_node(self, node):
"""Return true if node exists and false if not."""
return node in self._d_graph
def neighbors(self, node):
"""Return list of nodes to which the specified node connects."""
try:
return list(self._d_graph[node])
except KeyError:
raise KeyError("{} is not a node in the graph.".format(node))
def adjacent(self, node1, node2):
"""Check if node1 connects to node2, if both exist."""
try:
self._d_graph[node2]
except KeyError:
raise KeyError("{} does not exist.".format(node2))
try:
return node2 in self._d_graph[node1]
except KeyError:
raise KeyError("{} does not exist.".format(node1))
|
078b987ccada7f6daf186226acdc6af757044b18 | Suryamadhan/9thGradeProgramming | /CPLab_15/Practice.py | 526 | 3.78125 | 4 | __author__ = 'Surya'
def main():
check = input("Please enter a String: ")
count = 0
for i in range(0, len(check)):
if check[i] == "s":
count+=1
print("The String " + check + " contains ", count, " ss.")
main()
def contains13(num):
return num % 13 == 0
def main():
number = int(input("Please enter a number: "))
count = 0
for i in range(0, number):
if contains13(i):
count += 1
print("The number ", number, " contains ", count, " 13s.")
main() |
96790c903012003f86ae0ea9ceabb018b8d3a72f | PierreRust/PythonPerformance_RayTracing | /raytracer/vector.py | 5,898 | 4.40625 | 4 | import math
from typing import Union
class Vector3:
"""
Vector3 represents a 3-dimensional vector.
Standard vector operations are provided: cross product, dot product, norm.
All operators a defined for element-wise and scalar operations.
"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def normalize(self) -> "Vector3":
"""
Normalize a vector
Returns
-------
Vector3:
A new vector, which is the input vector normalized.
"""
norm = self.norm()
return Vector3(self.x / norm, self.y / norm, self.z / norm)
def norm(self) -> float:
"""
Vector's norm.
Returns
-------
float:
the norm of the vector (i.e. a scalar)
"""
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
def cross(self, other: "Vector3") -> "Vector3":
"""
Vector cross product.
Parameters
----------
other: Vector3 of scalar
Returns
-------
Vector3:
The cross product of the two vectors.
"""
# aka cross product
nx = self.y * other.z - self.z * other.y
ny = self.z * other.x - self.x * other.z
nz = self.x * other.y - self.y * other.x
return Vector3(nx, ny, nz)
def dot(self, other: "Vector3") -> float:
"""
Vector's dot product.
Parameters
----------
other: Vector3
Returns
-------
float:
the dot product of the two vectors.
"""
# aka dot product, inner product, scalar product
return self.x * other.x + self.y * other.y + self.z * other.z
def __mul__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Multiplication, element-wise and scalar
Parameters
----------
other: Vector3 of scalar
Returns
-------
a Vector3
"""
if isinstance(other, Vector3):
# Element-wise multiplication
return Vector3(self.x * other.x, self.y * other.y, self.z * other.z)
else:
return Vector3(other * self.x, other * self.y, other * self.z)
def __rmul__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Multiplication, element-wise and scalar
Parameters
----------
other: Vector3 of scalar
Returns
-------
a Vector3
"""
if isinstance(other, Vector3):
return Vector3(self.x * other.x, self.y * other.y, self.z * other.z)
else:
return Vector3(other * self.x, other * self.y, other * self.z)
def __add__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Addition, element wise and scalar.
Parameters
----------
other: a Vector3 or a scalar
Returns
-------
a Vector3
Examples
--------
>>> Vector3(1,2,3) + 1
Vector3D(2, 3, 4)
>>> Vector3(1,2,3) + Vector3(-1,0,2)
Vector3D(0, 2, 5)
"""
if isinstance(other, Vector3):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
else:
return Vector3(self.x + other, self.y + other, self.z + other)
def __radd__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Addition, element wise and scalar.
Parameters
----------
other: a Vector3 or a scalar
Returns
-------
a Vector3
Examples
--------
>>> 1+ Vector3(1,2,3)
Vector3D(2, 3, 4)
>>> Vector3(1,2,3) + Vector3(-1,0,2)
Vector3D(0, 2, 5)
"""
if isinstance(other, Vector3):
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
else:
return Vector3(self.x + other, self.y + other, self.z + other)
def __sub__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Subtraction, element wise and scalar.
Parameters
----------
other: a Vector3 or a scalar
Returns
-------
a Vector3
"""
if isinstance(other, Vector3):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
else:
return Vector3(self.x - other, self.y - other, self.z - other)
def __rsub__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Subtraction, element wise and scalar.
Parameters
----------
other: a Vector3 or a scalar
Returns
-------
a Vector3
"""
if isinstance(other, Vector3):
return Vector3(self.x - other.x, self.y - other.y, self.z - other.z)
else:
return Vector3(other - self.x, other - self.y, other - self.z)
def __truediv__(self, other: Union["Vector3", float]) -> "Vector3":
"""
Division, element wise and scalar.
Parameters
----------
other: a Vector3 or a scalar
Returns
-------
a Vector3
"""
if isinstance(other, Vector3):
return Vector3(self.x / other.x, self.y / other.y, self.z / other.z)
else:
return Vector3(self.x / other, self.y / other, self.z / other)
def __eq__(self, other) -> bool:
if not isinstance(other, Vector3):
return False
return other.x == self.x and other.y == self.y and self.z == other.z
def __repr__(self):
return f"Vector3({self.x}, {self.y}, {self.z})"
def as_tuple(self):
return self.x, self.y, self.z
def __iter__(self):
yield self.x
yield self.y
yield self.z
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.