blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f166ebfb983486de4edfc8f25a8fe4070c7af6b3 | paulmcaruana/Dictionaries_and_sets | /fruit.py | 733 | 4.25 | 4 | fruit = {"orange": "a sweet, orange, citrus fruit",
"apple": "good for making cider",
"lemon": "a sour, yellow citrus fruit",
"grape": "a small, sweet fruit growing in bunches",
"Lime": "a sour green citrus fruit"}
print(fruit)
veg = {"cabbage": "every child's favourite",
"sprouts": "mmmm, lovely",
"spinach": "can I have some fruit please"}
print(veg)
# veg.update(fruit) # adds the fruit to the veg dictionary
# print (veg)
#
# print(fruit.update(veg))
# print(fruit)
nice_and_nasty = fruit.copy() # creates a new dictionary by copying fruit
nice_and_nasty.update(veg) # adds the veg dictionary to thr new nice_and_nasty one with fruit in it already
print(nice_and_nasty)
|
d1009e780e0f321483c33555eb40499688daf173 | FreedomFrog/pdxcodeguild | /python/blackjack/deck.py | 805 | 3.71875 | 4 | import card
import random
ranks = ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"]
suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
class Deck:
def __init__(self, an_int=1):
self.contents = []
self.num_decks = an_int
self.make_cards_in_decks(self.num_decks)
self.shuffle_cards()
def __repr__(self):
return str(self.contents)
def make_cards_in_decks(self, an_int):
for i in range(an_int):
self.contents.extend([card.Card(rank, suit) for rank in ranks for suit in suits])
def shuffle_cards(self):
random.shuffle(self.contents)
def deal_card(self):
return self.contents.pop(0)
#
# d1 = Deck()
# print(d1)
# print(d1.shuffle_cards())
# print(d1) |
a06d5f6a3a21913617b5081ef8f373348e28f10e | akwls/PythonTest | /Part14. 리스트 더 알아보기/slice.py | 393 | 3.71875 | 4 | rainbow = ["빨", "주", "노", "초", "파", "남", "보"]
# red_colors가 ["빨", "주", "노"]의 값을 가지도록 rainbow를 slice하세요.
red_colors = rainbow[:3]
#blue_colors가 ["파", "남", "보"]의 값을 가지도록 rainbow를 slice하세요.
blue_colors = rainbow[4:]
print("red_colors의 값 : {}".format(red_colors))
print("blue_colors의 값 : {}".format(blue_colors)) |
31674848f49216608d5c06a4128b22ef84cb451f | andreinaoliveira/Exercicios-Python | /Exercicios/077 - Contando vogais em Tupla.py | 466 | 4.1875 | 4 | # Exercício Python 077 - Contando vogais em Tupla
# Crie um programa que tenha uma tupla com várias palavras (não usar acentos).
# Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais.
frutas = ('banana', 'abacate', 'pera', 'uva', 'abacaxi')
for palavra in frutas:
print(f'Palavra {palavra.upper()} \nVogais: ')
for letra in palavra:
if letra.lower() in 'aeiou':
print(letra, end=' ')
print('\n')
|
b66c2a156100c0cc5ca88e51197d90d7291a320f | hopensic/LearnPython | /src/leecode/tree_medium_1038(3).py | 943 | 3.5 | 4 | # Definition for a binary tree node.
from leecode.common.commons import buildTree, TreeNode
d = {}
lst = []
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
d.clear()
lst.clear()
self.traverse(root)
d[lst[0]] = lst[0]
for x in lst[1:]:
d[x] = d[x + 1] + x
self.update(root)
return root
def traverse(self, node):
if (not node):
return
self.traverse(node.right)
lst.append(node.val)
self.traverse(node.left)
def update(self, node):
if (not node):
return
self.update(node.right)
node.val = d[node.val]
self.update(node.left)
# treelist = [4, 1, 6, 0, 2, 5, 7, None, None, None, 3, None, None, None, 8]
treelist = [0, None, 1]
root_tree = buildTree(treelist)
print('-----')
solution = Solution()
solution.bstToGst(root_tree)
# solution.traverse(root_tree)
|
6989eff4ff464c91b353c416165c401d6d9bf3d5 | patchiu/math-programmmmm | /interpolation/Newton interpolation.py | 959 | 4.125 | 4 |
import numpy as np
def newtonsDividedDifference(x_data,y_data):
"""Calculates the coeffisients of the interpolatiol polynomial
from n data points using Newton's divided difference.
Parameters:
x_data: float arr. All the x-values of the data set.
y_data: float arr. All the y-values of the data set.
x_data and y_data has to be of the same length.
Returns:
c: float arr. The coeffisients of the interpolation polynomial.
P_n=c_0(x-x_1)+c_1(x-x_1)(x-x_2)+.......
"""
n = len(x_data) - 1
c = y_data.copy()
for i in range(1, n + 1):
for j in range(n, i - 1 , -1):
c[j] = (c[j] - c[j - 1])/(x_data[j] - x_data[j - i])
return c
x_data = [1.0, 4.0, 7.0, 10.0, 11.0, 2.0]
y_data = [1.2, 1.1,-9.1, 1.0, 1.0, 0.0]
c = newtonsDividedDifference(x_data, y_data)
print(‘newtonsDividedDifference’)
print(c)
|
1008b56a4936b2ce98682b1a91c3d6084f33c403 | souhaiebtar/CSV-Special-Character-Remover | /SCR.py | 988 | 4.34375 | 4 | #-------------------------------------------------------------------------------
# Name: Special Characters Remover
# Purpose: A stright forward way to remove special characters or any other character defined by the user for CSV
# files.
#
# Author: Haytham Amin
#
# Created: 16/05/2015
# Copyright: CC
# Licence: <000000000>
#-------------------------------------------------------------------------------
import csv
fname = raw_input("Enter file name, please include the file extension '.csv' : ")
with open( fname , "rU") as infile, open("repaired_file.csv", "wb") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
conversion = '"/(){}_[]'
for row in reader:
newrow = [''.join('' if c in conversion else c for c in entry) for entry in row]
writer.writerow(newrow)
print 'done'
print 'The output file is located in the same folder that contained the input file'
print 'File name = reparied_file.csv'
|
ee7d098406d8159261820eb13fcee55443affb4c | excaliburnan/SolutionsOnLeetcodeForZZW | /2_AddTwoNumbers/addTwoNumbers.py | 773 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
if not l2: return l1
curNode = ListNode(0)
p, q, dummy = l1, l2, curNode
carry = 0
while p or q:
x = p.val if p else 0
y = q.val if q else 0
ssum = x + y + carry
curNode.next = ListNode(ssum % 10)
carry = ssum // 10
curNode = curNode.next
p = p.next if p else None
q = q.next if q else None
curNode.next = ListNode(1) if carry > 0 else None
return dummy.next
|
707a5e324c1fe249b0891d976595340597fe8b1a | yang4978/LintCode | /0463. Sort Integers.py | 295 | 3.53125 | 4 | class Solution:
"""
@param A: an integer array
@return: nothing
"""
def sortIntegers(self, A):
n = len(A)
for i in range(n,0,-1):
for j in range(1,i):
if(A[j-1]>A[j]):
A[j-1],A[j] = A[j],A[j-1]
return A
|
b19a7152bdf4b501d0366bc9a53ec07485624515 | gaodelade/MachineLearning_at_FLT | /02_Supervised/01_Regression/03_Polynomial_Linear_Regression/source.py | 2,347 | 4.1875 | 4 | ''' Polynomial Linear Regression '''
# ***** Polynomial-Linear-Regression Intution *****
# Here, we have a simple formula: `y = b0 + b1.x1 + b2.x1^2 + ... + bn.x1^n`
# where, x = independent variable
# y = dependent variable
# b1, b2, ... = quantifier of how `y` will change with the unit change in `x`.
# b0 = the constant quantifier for the case where rest of the expression evaluates to zero but still we are left with
# some quantifier.
#
# This is used in the case where we have a curve-fitted graph.
#
# Why it is still called Linear?
# - Here, when we are talking about Linear, we are not denoting the x (since x is polynomial) but what we are denoting
# here is the class of regression that is the coefficients that are being used with the independent variables.
# So, we can replace the coefficients with other coefficients to turn the equation into a linear one.
#
# But the way it fits the data is Non-Linear in nature.
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing dataset
dataset = pd.read_csv('Position_Salaries.csv')
# Making feature matrix and target vector
features = dataset.iloc[:, [1]].values
target = dataset.iloc[:, -1].values
# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
linear_regressor = LinearRegression()
linear_regressor.fit(features, target)
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_regressor = PolynomialFeatures(degree=5) # By default also, the degree is 2.
poly_features = poly_regressor.fit_transform(features)
poly_lin_regressor = LinearRegression()
poly_lin_regressor.fit(poly_features, target)
# *****Visualise the dataset *****
plt.subplot(121)
feature_grid = np.arange(min(features), max(features), 0.1)
feature_grid = feature_grid.reshape((len(feature_grid), 1))
plt.scatter(features, target, color='red')
plt.plot(feature_grid, linear_regressor.predict(feature_grid), color='blue')
plt.title('Truth or Bluff (Linear Regression)')
plt.subplot(122)
plt.scatter(features, target, color='red')
plt.plot(feature_grid, poly_lin_regressor.predict(poly_regressor.fit_transform(feature_grid)), color='blue')
plt.title('Truth or Bluff (Polynomial Linear Regression)')
plt.show()
|
7ed24f70a0444c664456a4c6920e0a16270737c0 | axura/shadow_alice | /test08.py | 220 | 3.9375 | 4 | #!/usr/bin/python
#testing break and continue functions
x = 0
while x <= 10:
if x % 4 == 0:
print "divisible by 4"
x += 1
elif x % 3 == 0:
print "divisible by 3"
continue
elif x > 8:
break
else:
x += 1
|
46d82e91545dd648e8c40e14064adfce5a71e04a | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise5.py | 371 | 4 | 4 | '''
5. Write a Pandas program to convert a dictionary to a Pandas series.
'''
dict1 = {"First Name" : ["Kevin","Lebron","Kobe","Michael"],
"Last Name" : ["Durant","James","Bryant","Jordan"],
"Team" : ["Brooklyn Nets","Los Angeles Lakers","Los Angeles Lakers","Chicago Bulls"]
}
import pandas as pd
pd_series = pd.Series(dict1)
print(pd_series) |
816c04c7cc93fd96828e070ef6a904b9d7f83c5d | JonasAraujoP/Python | /modularização/desafio107/desafio107.py | 399 | 3.578125 | 4 | import moeda
print('-=-'*12)
valor = float(input('Digite o preço: R$ '))
taxa = float(input('Informe a taxa: '))
print('-=-'*12)
print(f'Aumento de {taxa}% sobre R${valor} = R${moeda.aumentar(valor, taxa)}')
print(f'Diminuição de {taxa}% sobre R${valor} = R${moeda.diminuir(valor, taxa)}')
print(f'Dobro de R${valor} = R${moeda.dobro(valor)}')
print(f'Metade R${valor} = R${moeda.metade(valor)}') |
ba8ac3e26048a31a3689bd5e1ff34fb92e632bd1 | stanislavkozlovski/data_structures_feb_2016 | /SoftUni/Advanced Tree Structures/binary_heap_tests.py | 903 | 3.6875 | 4 | import unittest
from binary_heap import BinaryHeap
class BinaryHeapTests(unittest.TestCase):
def test_build_heap_extract_all_elements_should_return_sorted_elements(self):
nums = [3, 4, -1, 15, 2, 77, -3, 4, 12]
heap = BinaryHeap(nums)
result = []
expected = [77, 15, 12, 4, 4, 3, 2, -1, -3]
while len(heap) > 0:
result.append(heap.extract_max())
self.assertEqual(result, expected)
def test_empty_heap_insert_extract_elements_should_return_sorted_elements(self):
nums = [3, 4, -1, 15, 2, 77, -3, 4, 12]
heap = BinaryHeap()
expected = [77, 15, 12, 4, 4, 3, 2, -1, -3]
result = []
for num in nums:
heap.insert(num)
while heap.count > 0:
result.append(heap.extract_max())
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main() |
2a2fcf84d93e05e0c72042dd3ee2ca978ed2dc28 | prajaktabhosale68121/learning_python | /variable.py | 1,021 | 4.0625 | 4 | # Question : How to create variable
name = 'prajakta'
print(name)
# Question : How to assign value to variable
a='20'
print(a)
# Question : How to print variable
a1='20'
print(a1)
# Question : How to contact a string variable and print
a2='prajakta'
b2='bhosale'
c2= a2+b2
print(c2)
# Question : How to add two number variable and print
e=10
f=20
g=e+f
print(g)
# Question : How to create array of string
arr=['orange','apple','banana']
print(arr)
# Question : How to create array of (object/json/dictionary).That contains information of two people
d=[
{
'age':26 ,
'name' : 'prajakta',
'address' : 'andheri' ,
'medals' : 7
},
{
'age':30 ,
'name' : 'vijay',
'address' : 'borivali' ,
'medals' : 2
}
]
print(d)
# Question : How to create array of (integer's/number)
h=[33,44,22]
print(h)
# Question : How to override variable and print
o1 = 100
print(o1)
o1 = 200
print(o1) #here o1 got overriden by new value
|
1d730868eddabe87a347af1cc7d1e5e8ac82da30 | Elsie0312/pycharm_code | /magic-8-ball.py | 514 | 3.734375 | 4 | import random, sys
ans = True
while ans:
question = input("Ask a question…if you dare")
answers = random.randint(1,6)
if question == "q":
sys.exit()
elif answers == 1:
print("NO")
elif answers == 2:
print("Yaaaasssss")
elif answers == 3:
print("ummmmm maybe?")
elif answers == 4:
print("idk tbqh")
elif answers == 5:
print("definitely")
elif answers == 6:
print("ask me tomorrow")
|
8a6a56bb857c5bd820a17e0d1c12c02c6d135bf3 | boluocat/core-python-programming | /最小数组合.py | 490 | 3.59375 | 4 | '''
输入:数组字用英文逗号隔开。
输出:
1、选取数组中的三个数字组合成最小数输出
2、如果数组中的数字个数小于3,则采用全部数字进行组合输出,输出最小值
例如:
#输入
32,435,6,543,654
#输出
324356
'''
a = list(input().split(','))
c = sorted(map(int,a))[0:3]
d = list(map(str,c))
b = ''
e = ''
if len(a) <=3:
for i in sorted(a):
b = b+i
print(b)
else:
for j in sorted(d):
e = e + j
print(e)
|
f606649153018af62f2521f526054c1a7c413dda | rohitrastogi/Interview-Prep | /solns/num_islands.py | 994 | 3.734375 | 4 | def num_islands(matrix):
num_rows = len(matrix)
num_cols = len(matrix[0])
queue = []
count = 0
def is_valid(row, col):
return not (row < 0 or row == num_rows or col < 0 or col == num_cols)
def bfs():
queue.append( (row, col) )
matrix[row][col] = 0
while queue:
row, col = queue.pop(0)
dirs = [(0, 1), (1, 0), (-1, 0), (0, -1)]
for d in dirs:
new_row, new_col = row + d[0], col + d[1]
if is_valid(new_row, new_col) and matrix[new_row][new_col] == 1:
queue.append( (new_row, new_col) )
matrix[new_row][new_col] = 0 #mark visited
for row in range(num_rows):
for col in range(num_cols):
if (matrix[row][col] == 1):
bfs()
count += 1
return count
test = [
[1, 1, 1],
[0, 0, 0],
[1, 1, 1],
[1, 1, 1]
]
print(num_islands(test)) |
557774540471ef26ad43910cb054987a20e0f939 | RajMadhok/python- | /credit and debit.py | 632 | 4.15625 | 4 | balance=20000
operation=int(input("Press 1 for Credit and 2 for Debit: "))
print("ur balance is:",balance)
trans_amount=int(input("Enter the Amount:"))
i=1
while i<=3:
if operation==1:
credit=balance+trans_amount
print("Your Current balance is: ",credit)
print("Amount Credited: ",trans_amount)
break;
elif operation==2:
if trans_amount>balance:
print("Not enough balance.")
break;
elif (trans_amount<=balance):
debit=balance-trans_amount
print("your current balance is: ",debit)
print("Amount Debited: ",trans_amount)
break;
i=i+1
|
9fc5ca14231325b2a0b0f8957f71e6d473afc1d8 | tberhanu/green_book | /ch1_Arrays&Strings/rotate_matrix.py | 723 | 3.984375 | 4 | from copy import deepcopy
def rotated_matrix(matrix):
'''matrix = [ [ , , ],
[ , , ],
[ , , ] ]
is list of lists'''
'''matrix = [ [(0,0) , (0,1) , (0,2)],
[(1,0) , (1,1) , (1,2)],
[(2,0) , (2,1) , (2,2)] ]'''
'''rotated_ matrix = [ [(2,0) , (1,0) , (0,0)],
[(2,1) , (1,1) , (0,1)],
[(2,2) , (1,2) , (0,2)] ]'''
rotated_matrix = deepcopy(matrix)
n = len(matrix)
row = len(matrix)
for lst in matrix:
for i in range(n):
rotated_matrix[i][row - 1] = lst[i]
row -= 1
return rotated_matrix
matrix = [ [1 , 2 , 3],
[4 , 5 , 6],
[7 , 8 , 9] ]
print(rotated_matrix(matrix))
|
8814169ecb7e155092f7876927911b2f268bc9df | aamir7shahab/FellowshipPrograms | /Logical Programs/StopWatch.py | 924 | 3.84375 | 4 | import time
from math import floor
class StopWatch:
@staticmethod
def startTime():
start = time.time()
return start
@staticmethod
def stopTime():
stop = time.time()
return stop
@staticmethod
def elapsedTime(start, end):
elapsedTime = (end - start)
return elapsedTime
@staticmethod
def formatTime(timeInSec):
mins = timeInSec // 60
sec = timeInSec % 60
hour = mins // 60
mins = mins % 60
millSec = (sec - floor(sec)) * 1000
print()
print(f'{int(hour):2} hrs: {int(mins):2} mins: {floor(sec):2} secs: {floor(millSec):3} msec')
print()
if __name__ == '__main__':
input('Press Enter to Start the Watch')
start = StopWatch.startTime()
input('Press Enter to Stop the Watch')
end = StopWatch.stopTime()
StopWatch.formatTime(StopWatch.elapsedTime(start, end))
|
ae611a2d541ca43641b3a943ab1d92888f833814 | HalfMoonFatty/Interview-Questions | /467. Unique Substrings in Wraparound String.py | 2,337 | 4.03125 | 4 | '''
Problem:
Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz",
so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s.
In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.
Note: p consists of only lowercase English letters and the size of p might be over 10000.
Example 1:
Input: "a"
Output: 1
Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:
Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in the string s.
Example 3:
Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
'''
'''
Solution:
The idea is, if we know the max number of unique substrings in p ends with 'a', 'b', ..., 'z', then the summary of them is the answer.
The max number of unique substring ends with a letter equals to the length of max contiguous substring ends with that letter.
Example "abcd", the max number of unique substring ends with 'd' is 4, apparently they are "abcd", "bcd", "cd" and "d".
If there are overlapping, we only need to consider the longest one because it covers all the possible substrings.
E.g.: "abcdbcd", the max number of unique substring ends with 'd' is 4 and all substrings formed by the 2nd "bcd" part are covered in the 4 substrings already.
No matter how long is a contiguous substring in p, it is in s since s has infinite length.
Now we know the max number of unique substrings in p ends with 'a', 'b', ..., 'z' and those substrings are all in s. Summary is the answer.
'''
class Solution(object):
def findSubstringInWraproundString(self, p):
"""
:type p: str
:rtype: int
"""
count = collections.defaultdict(int)
seqLen = 0
for i in range(len(p)):
if i > 0 and (ord(p[i]) - ord(p[i-1]) == 1 or ord(p[i-1]) - ord(p[i]) == 25):
seqLen += 1
else:
seqLen = 1
count[p[i]] = max(count[p[i]], seqLen)
return sum(count.values())
|
3a761e72e8d57b4ee149c0df9d473b4c7c8dac90 | vannt010391/vspro_final0905 | /media/New Text Document.py | 276 | 3.5 | 4 | def chan(a):
if a % 2 == 0:
return True
else:
return False
# a = input()
a = '127'
sc = 0
sl = 0
for i in a:
if chan(int(i)):
sc += int(i)
sl += int(i)
if sl % sc == 0:
print('YES')
else:
print('NO') |
22a82b6c590fed87cb677c0f1b958950af27b5e7 | typhoon93/python3learning | /TicTacToe_Project.py | 6,639 | 4.09375 | 4 | from IPython.display import (
clear_output,
) # this function can clear the output so we don't have clutter
import time # using time.sleep in the code so we don't have issues with input sequence display in jypiter
from random import randint # used to randomly assign first player
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
player_turn = "x" # using this to store player turn
entered_keys = (
[]
) # using this to check which keys are entered. we append the entered keys to the list
def clear_board():
global board # defining board as global, so we can change it inside the function
global entered_keys # same for keys
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
entered_keys = [] # clearing keys as well
def display_board(board):
clear_output() # from IPython.display import clear_output, clears screen before displaying the modified board
board_print = "{}|{}|{} \n-----\n{}|{}|{}\n-----\n{}|{}|{}".format(
board[0][0],
board[0][1],
board[0][2],
board[1][0],
board[1][1],
board[1][2],
board[2][0],
board[2][1],
board[2][2],
)
print(board_print)
def player_input():
while True:
try:
player_choice = int(
input(
f"Player {player_turn.upper()}, choose where to place {player_turn.upper()} (1-9): "
)
) # converting input to INT
if player_choice not in range(
1, 10
): # user entered a number thats not between 1-9
print("That's not a valid option, choose a NUMBER between 1 and 9.")
continue
elif (
player_choice in entered_keys
): # user entered a key that was already entered
print("That field is already taken, please choose an empty field.")
else:
break # no issues with input, breaking out of while loop
except: ##if there is an exception in converting the string to INT, In other words, user entered a letter
print("That's not a valid option, choose a NUMBER between 1 and 9.")
entered_keys.append(player_choice)
return player_choice
def winning_check(board): ### CHECK IF A PLAYER IS WINNING
entered_keys.sort() # sorting list so we can check if it is the end of the game
# check 1) horizontally 2) vertically 3) across (8 possible combinations), returing false will break out of the main loop and the game will end
if (
board[0][0] == board[0][1] == board[0][2] == "x"
or board[1][0] == board[1][1] == board[1][2] == "x"
or board[2][0] == board[2][1] == board[2][2] == "x"
):
print("X wins the game. Game over")
return False
elif (
board[0][0] == board[1][0] == board[2][0] == "x"
or board[0][1] == board[1][1] == board[2][1] == "x"
or board[0][2] == board[1][2] == board[2][2] == "x"
):
print("X wins the game. Game over")
return False
elif (
board[0][0] == board[1][1] == board[2][2] == "x"
or board[2][0] == board[1][1] == board[0][2] == "x"
):
print("X wins the game. Game over")
return False
elif (
board[0][0] == board[0][1] == board[0][2] == "o"
or board[1][0] == board[1][1] == board[1][2] == "o"
or board[2][0] == board[2][1] == board[2][2] == "o"
):
print("O wins the game. Game over")
return False
elif (
board[0][0] == board[1][0] == board[2][0] == "o"
or board[0][1] == board[1][1] == board[2][1] == "o"
or board[0][2] == board[1][2] == board[2][2] == "o"
):
print("O wins the game. Game over")
return False
elif (
board[0][0] == board[1][1] == board[2][2] == "o"
or board[2][0] == board[1][1] == board[0][2] == "o"
):
print("O wins the game. Game over")
return False
# check if all spots are filled
elif entered_keys == list(
range(1, 10)
): # entered keys list already sorted above. Alternatively can use >= 9 as well, instead of creating a new list
print("It's a DRAW. Nobody wins the game. Game over")
return False
return True ##returnign true to continue while loop
def change_player_turn(): #### CHANGE PLAYER TURN FUNCTION####, checks which player's turn is currently, and switches to the other one
global player_turn
if player_turn == "x":
player_turn = "o"
else:
player_turn = "x"
def board_update(
player_input,
): #### UPDATE BOARD FUCNTION#### Updates board with the date entered from the player input function
if player_input == 1:
board[2][0] = player_turn
elif player_input == 2:
board[2][1] = player_turn
elif player_input == 3:
board[2][2] = player_turn
elif player_input == 4:
board[1][0] = player_turn
elif player_input == 5:
board[1][1] = player_turn
elif player_input == 6:
board[1][2] = player_turn
elif player_input == 7:
board[0][0] = player_turn
elif player_input == 8:
board[0][1] = player_turn
elif player_input == 9:
board[0][2] = player_turn
def random_first_player(): ###randomly assigning first player
global player_turn
if randint(0, 1) == 0:
player_turn = "x"
else:
player_turn = "o"
def start_game(): # starts game
random_first_player() # randomly choose first player
clear_board() # clear board and output in case another game was played before
# clear_output()
display_board(board)
print(f"It's time to begin a new game. Player {player_turn.upper()} goes first")
while winning_check(
board
): ###IF no winner, func returns TRUE, if there;s a winner it will return False and we will leave the loop
board_update(player_input()) # take input and update board
display_board(board)
change_player_turn()
def yes_no_game():
multiple_games_text = ""
while True:
yes_no = input(
f"Would you like to play a{multiple_games_text} game of Tic Tac Toe? Choose Y or N: "
)
if yes_no.lower() == "y":
start_game()
multiple_games_text = "nother" ##little trick, if playing multiple texts, this will change the printed question
elif yes_no.lower() == "n":
clear_output()
print("Closing the game")
break
else:
print("Please write 'y' or 'n'. ")
|
e6cf429b6ce1b0052c48cbe72aebbee70670ed19 | nyck33/coding_practice | /Python/leetcode/dfs_bfs.py | 705 | 3.703125 | 4 | graph = {1:[2,4], 2:[1,3], 3:[3,4],4:[1,3]}
def dfs(g, s=1):
g[0] = [0]
stack = []
visited = [0 for x in range(len(g))]
stack.append(s)
while stack:
u = stack.pop(-1)
visited[u] = 1
edges = g[u]
for v in edges:
if not visited[v]:
stack.append(v)
return visited
def bfs(g, s=1):
g[0] = 0
visited = [0 for x in range(len(g))]
q = []
q.append(s)
while q:
u = q.pop(0)
visited[u] = 1
edges = g[u]
for v in edges:
if not visited[v]:
q.append(v)
return visited
if __name__=="__main__":
g = graph
print(dfs(g))
print(bfs(g))
|
0e2c73177a0bb32644bb881acdde09b084c2a52f | Jinsaeng/CS-Python | /al4995_hw6.py | 3,852 | 3.875 | 4 | ##def print_shifted_triangle(n,m,symbol):
## matrix = "";
## for i in range(2*n):
## if i % 2 == 0:
## j = 0
## else:
## j = i
## line = (" " * m) + ((2* n-i) * " ")+ (j * symbol) + "\n"
## matrix +=line
## return matrix
##def print_pine_tree(n, symbol):
## pine = "";
## for i in range(1, n+1):
## result = print_shifted_triangle(i+1, n-i, symbol) + "\n"
## pine += result
## return pine
##def main():
## print(print_pine_tree(n, symbol))
##
##
##def print_month_calendar(num_of_days, starting_day):
## print("Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun", sep = "\t")
## empty = starting_day - 1
## for i in range(empty):
## print(" ", end = "\t")
## for j in range (1,9-starting_day):
## print(j, end = "\t")
## change_of_week = 0;
## for k in range(9- starting_day, num_of_days +1 ):
## print(k, end = "\t")
## change_of_week += 1
## if change_of_week == 7:
## print()
## change_of_week = 0;
## last_day = (num_of_days - (8-starting_day) %7)
## return last_day
##
##def check_leap(year):
## if year % 400 == 0:
## return True
## elif year % 4 == 0 and year % 100 != 0:
## return True
## else:
## return False
##
##def print_year_calendar(year, starting_day):
leap = check_leap(year)
for month in range(1,13):
if month == 1:
print("January", year)
num_of_days = 31
elif month == 2:
print("February", year)
if leap:
num_of_days = 29
else:
num_of_days = 28
elif month == 3:
print("March", year)
num_of_days = 31
elif month == 4:
print("April", year)
num_of_days = 30
elif month == 5:
print("May", year)
num_of_days = 31
elif month == 6:
print("June", year)
num_of_days = 30
elif month == 7:
print("July", year)
num_of_days = 31
elif month == 8:
print("August", year)
num_of_days = 31
elif month == 9:
print("September", year)
num_of_days = 30
elif month == 10:
print("October", year)
num_of_days = 31
elif month == 11:
print("November", year)
num_of_days = 30
elif month == 12:
print("December", year)
num_of_days = 31
## last_day= print_month_calendar(num_of_days, starting_day)
## if l(ast_day + 1) <= 7:
## starting_day = last_day+1
## else:
## starting_day = 1
##
##def main():
## year = input("Enter a year: ");
## starting_day = int(input("Enter the starting day with numbers 1-7: "));
## print_year_calendar(year,starting_day)
##
##
##
def first_word(phrase):
first = phrase.find(" ");
word = phrase[0 : first]
return word
def rest_of_it(phrase):
first = phrase.find(" ");
rest = phrase[first + 1:]
return rest
##
##def main():
## phrase = "the quick brown fox"
##
phrase = input("String:")
first = 0
newstring2 = ""
word1 = first_word(phrase)
while phrase.find(" ") != -1:
first = phrase.find(" ");
word = phrase[0: first+1]
rest = rest_of_it(phrase)
phrase = rest
newstring = word
newstring3 = newstring + newstring2
newstring2 = newstring3
newstring2 = rest + " " + newstring3
print(newstring2)
|
1d955e5ee15e926c49bcc1cea4fb0ed48dfb9fd8 | rusalforever/python-course-alphabet | /relational_database/homework.py | 9,417 | 3.578125 | 4 | from typing import List
def task_1_add_new_record_to_db(con) -> None:
"""
Add a record for a new customer from Singapore
{
'customer_name': 'Thomas',
'contactname': 'David',
'address': 'Some Address',
'city': 'London',
'postalcode': '774',
'country': 'Singapore',
}
Args:
con: psycopg connection
Returns: 92 records
"""
<<<<<<< HEAD
j_values = {
'customername': 'Thomas',
'contactname': 'David',
'address': 'Some Address',
'city': 'London',
'postalcode': '774',
'country': 'Singapore',
}
vals_str2 = ", ".join(["%({0})s".format(x) for x in j_values.keys()])
with con.cursor() as cur:
cur.execute("INSERT INTO customers ({}) VALUES ({})".format(
', '.join(j_values.keys()),
vals_str2), j_values)
con.commit()
=======
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_2_list_all_customers(cur) -> list:
"""
<<<<<<< HEAD
Get
all
records
from table Customers
Args:
cur: psycopg
cursor
Returns: 91
records
"""
cur.execute("SELECT * FROM customers")
return cur.fetchall()
=======
Get all records from table Customers
Args:
cur: psycopg cursor
Returns: 91 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_3_list_customers_in_germany(cur) -> list:
"""
<<<<<<< HEAD
List
the
customers in Germany
Args:
cur: psycopg
cursor
Returns: 11
records
"""
cur.execute("SELECT * FROM customers WHERE country='Germany'")
return cur.fetchall()
=======
List the customers in Germany
Args:
cur: psycopg cursor
Returns: 11 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_4_update_customer(con):
"""
<<<<<<< HEAD
Update
first
customer
's name (Set customername equal to '
Johnny
Depp
')
Args:
cur: psycopg
cursor
Returns: 91
records
with updated customer
"""
with con.cursor() as cur:
cur.execute("""
UPDATE customers SET customername = '{}'
WHERE customerid = (SELECT customerid FROM customers ORDER BY customerid LIMIT 1)
""".format('Johnny Depp'))
con.commit()
=======
Update first customer's name (Set customername equal to 'Johnny Depp')
Args:
cur: psycopg cursor
Returns: 91 records with updated customer
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_5_delete_the_last_customer(con) -> None:
"""
Delete the last customer
Args:
<<<<<<< HEAD
con: psycopg
connection
"""
with con.cursor() as cursor:
cursor.execute("""DELETE FROM customers WHERE customerid =
(SELECT customerid FROM customers ORDER BY customerid DESC LIMIT 1)""")
con.commit()
=======
con: psycopg connection
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_6_list_all_supplier_countries(cur) -> list:
"""
<<<<<<< HEAD
List
all
supplier
countries
Args:
cur: psycopg
cursor
Returns: 29
records
"""
cur.execute("SELECT country FROM suppliers")
return cur.fetchall()
=======
List all supplier countries
Args:
cur: psycopg cursor
Returns: 29 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_7_list_supplier_countries_in_desc_order(cur) -> list:
"""
<<<<<<< HEAD
List
all
supplier
countries in descending
order
Args:
cur: psycopg
cursor
Returns: 29
records in descending
order
"""
cur.execute("SELECT country FROM suppliers ORDER BY country DESC")
return cur.fetchall()
=======
List all supplier countries in descending order
Args:
cur: psycopg cursor
Returns: 29 records in descending order
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_8_count_customers_by_city(cur):
"""
<<<<<<< HEAD
List
the
number
of
customers in each
city
Args:
cur: psycopg
cursor
Returns: 69
records in descending
order
"""
cur.execute("SELECT COUNT(city) as count, city FROM customers GROUP BY city ORDER BY count DESC")
return cur.fetchall()
=======
List the number of customers in each city
Args:
cur: psycopg cursor
Returns: 69 records in descending order
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_9_count_customers_by_country_with_than_10_customers(cur):
"""
<<<<<<< HEAD
List
the
number
of
customers in each
country.Only
include
countries
with more than 10 customers.
Args:
cur: psycopg
cursor
Returns: 3
records
"""
cur.execute("""
SELECT COUNT(country) as count, country
FROM customers GROUP BY country
HAVING COUNT(country) > 10 ORDER BY count DESC
""")
return cur.fetchall()
=======
List the number of customers in each country. Only include countries with more than 10 customers.
Args:
cur: psycopg cursor
Returns: 3 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_10_list_first_10_customers(cur):
"""
<<<<<<< HEAD
List
first
10
customers
from the table
Results: 10
records
"""
cur.execute("SELECT * FROM customers LIMIT 10")
return cur.fetchall()
=======
List first 10 customers from the table
Results: 10 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_11_list_customers_starting_from_11th(cur):
"""
<<<<<<< HEAD
List
all
customers
starting
from
11
th
record
Args:
cur: psycopg
cursor
Returns: 11
records
"""
cur.execute("SELECT * FROM customers OFFSET 11")
return cur.fetchall()
=======
List all customers starting from 11th record
Args:
cur: psycopg cursor
Returns: 11 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_12_list_suppliers_from_specified_countries(cur):
"""
<<<<<<< HEAD
List
all
suppliers
from the USA, UK, OR
Japan
Args:
cur: psycopg
cursor
Returns: 8
records
"""
cur.execute("""
SELECT SupplierId, SupplierName, ContactName, City, Country
FROM suppliers WHERE country IN ('USA', 'UK', 'Japan')""")
return cur.fetchall()
=======
List all suppliers from the USA, UK, OR Japan
Args:
cur: psycopg cursor
Returns: 8 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_13_list_products_from_sweden_suppliers(cur):
"""
<<<<<<< HEAD
List
products
with suppliers from Sweden.
Args:
cur: psycopg
cursor
Returns: 3
records
"""
cur.execute("""
SELECT productname FROM products AS p
INNER JOIN suppliers s ON p.supplierid = s.supplierid
WHERE s.country = 'Sweden'
""")
return cur.fetchall()
=======
List products with suppliers from Sweden.
Args:
cur: psycopg cursor
Returns: 3 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_14_list_products_with_supplier_information(cur):
"""
<<<<<<< HEAD
List
all
products
with supplier information
Args:
cur: psycopg
cursor
Returns: 77
records
"""
cur.execute("""
SELECT p.*, suppliername FROM products AS p
LEFT JOIN suppliers AS s ON s.supplierid = p.supplierid
""")
return cur.fetchall()
=======
List all products with supplier information
Args:
cur: psycopg cursor
Returns: 77 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_15_list_customers_with_any_order_or_not(cur):
"""
<<<<<<< HEAD
List
all
customers, whether
they
placed
any
order or not.
Args:
cur: psycopg
cursor
Returns: 213
records
"""
cur.execute("""
SELECT customername, contactname, country, orderid FROM customers
LEFT JOIN orders ON orders.customerid = customers.customerid
""")
return cur.fetchall()
=======
List all customers, whether they placed any order or not.
Args:
cur: psycopg cursor
Returns: 213 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
def task_16_match_all_customers_and_suppliers_by_country(cur):
"""
<<<<<<< HEAD
Match
all
customers and suppliers
by
country
Args:
cur: psycopg
cursor
Returns: 194
records
"""
cur.execute("""
SELECT customername,
c.address,
c.country as customercountry,
s.country as suppliercountry,
suppliername
FROM customers AS c FULL JOIN suppliers AS s ON s.country = c.country
ORDER BY customercountry, suppliercountry""")
return cur.fetchall()
=======
Match all customers and suppliers by country
Args:
cur: psycopg cursor
Returns: 194 records
"""
pass
>>>>>>> 9e6a5cf9ab589ac685b162a0775bf72ea64dd0ba
|
c285bbe04ed02ee521ca13794264915943e84554 | HsiangHung/Code-Challenges | /leetcode_solution/string/438.Find_All_Anagrams_in_a_String.py | 1,123 | 3.6875 | 4 | # 438. Find All Anagrams in a String
#
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
'''
looping s as s[:3], s[1:4], s[1:5], ......
when new letter comes in, add it in dict, and remove the oldest letter.
and check s_dict == p_dict
'''
p_dict = self.get_word_dict(p)
s_dict = self.get_word_dict(s[:len(p)])
print (p_dict, s_dict)
indices = []
for i in range(len(s)-len(p)+1):
if s_dict == p_dict:
indices.append(i)
if i < len(s)-len(p) and s[i] != s[i+len(p)]:
s_dict[s[i+len(p)]] = s_dict.get(s[i+len(p)], 0) + 1
if s[i] in s_dict and s_dict[s[i]] > 1:
s_dict[s[i]] -= 1
elif s[i] in s_dict and s_dict[s[i]] == 1:
del s_dict[s[i]]
return indices
def get_word_dict(self, s):
word_dict = {}
for i in range(len(s)):
word_dict[s[i]] = word_dict.get(s[i], 0) + 1
return word_dict |
78b012ce19e3b837eb3ec1983e483b20dec89404 | tjsaotome65/sec430-python | /module-06/chatclient.py | 3,937 | 3.765625 | 4 | """
File: chatclient.py
Project 10.10
This module defines the ChatClient class, which provides a window
for a chatroom conversation.
"""
from socket import *
from codecs import decode
from breezypythongui import EasyFrame
HOST = "localhost"
PORT = 5000
ADDRESS = (HOST, PORT)
BUFSIZE = 1024
CODE = "ascii"
class ChatClient(EasyFrame):
"""Represents an chat window for a client.
The window waits for users to connect, then
sends requests to the server."""
def __init__(self):
"""Initialize the window."""
EasyFrame.__init__(self, title = "Chat Room")
# Create and add the widgets to the window."""
self.outputLabel = self.addLabel(text = "Transcript of the chat:",
row = 0, column = 0,
columnspan = 2,
sticky = "NSEW")
self.outputArea = self.addTextArea("", row = 1, column = 0,
columnspan = 2,
width = 50, height = 4)
self.inputLabel = self.addLabel(text = "Want to connect?",
row = 2, column = 0,
columnspan = 2,
sticky = "NSEW")
self.inputArea = self.addTextArea("", row = 3, column = 0,
columnspan = 2,
width = 50, height = 4)
self.sendButton = self.addButton(text = "Send",
row = 4, column = 0,
command = self.send,
state = "disabled")
self.connectButton = self.addButton(text = "Connect",
row = 4, column = 1,
command = self.connect)
# Connect to server and confirm connection
def connect(self):
"""Attempts to connect to the server. If successful,
enables the send and disconnect buttons."""
name = self.prompterBox(title = "Input Dialog",
promptString = "Your name:")
if name == "": return
self.server = socket(AF_INET, SOCK_STREAM)
self.server.connect(ADDRESS)
self.server.send(bytes(name, CODE))
reply = decode(self.server.recv(BUFSIZE), CODE)
if reply:
self.outputArea.setText(reply)
self.inputLabel["text"] = "Enter your message below:"
self.sendButton["state"] = "normal"
self.connectButton["text"] = "Disconnect"
self.connectButton["command"] = self.disconnect
else:
self.outputArea.setText("Could not connect")
def disconnect(self):
"""Disconnects the client, clears the text areas,
disables the send button, and enables connect."""
self.server.send(bytes("DISCONNECT", CODE))
self.server.close()
self.inputArea.setText("")
self.outputArea.setText("")
self.inputLabel["text"] = "Want to connect?"
self.sendButton["state"] = "disabled"
self.connectButton["text"] = "Connect"
self.connectButton["command"] = self.connect
def send(self):
"""Sends a message to the server and waits for a
reply."""
message = self.inputArea.getText()
if message == "": return
self.server.send(bytes(message, CODE))
reply = decode(self.server.recv(BUFSIZE), CODE)
self.outputArea.setText(reply)
def main(fileName = None):
"""Creates the bank with the optional file name,
wraps the window around it, and opens the window.
Saves the bank when the window closes."""
ChatClient().mainloop()
if __name__ == "__main__":
main()
|
d260aceda5958d58d4d9ea13016d108a8d32e9ea | chanyoonzhu/leetcode-python | /1790-Check_if_One_String_Swap_Can_Make_Strings_Equal.py | 249 | 3.5625 | 4 | """
- Array
- O(n), O(1)
"""
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
diffs = [(c1, c2) for c1, c2 in zip(s1, s2) if c1 != c2]
return not diffs or len(diffs) == 2 and diffs[0][::-1] == diffs[1]
|
aed896860a6d872454269cee6e60b49e23e184c7 | boraseoksoon/DailyCommit | /CrackingCodingInterview/Python/20170301_crackingCodingInterview.py | 9,661 | 4.0625 | 4 | #!/usr/bin/python
# Q1. anagram : a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
# Write a method to decide if two strings are anagram or not. if a one string is a permutation of another string.
Qstring1 = "LIsTEn"
Qstring2 = "sLienT"
def anagram(str1, str2):
if ''.join(sorted(str1.lower())).strip() == ''.join(sorted(str2.lower())).strip():
return True
else:
return False
result = anagram(Qstring1, Qstring2)
print(result) # True
### Python Join API
list = "!".join(["a", "b", "c"])
print(list) # a!b!c
# Q2. duplicated linked list node : Write a method to remove duplicated node from the given unsorted linked list.
# from LinkedList import VerySimpleLinkedList, Node, prepareLinkedList
# verySimpleLinkedList = prepareLinkedList()
# verySimpleLinkedList.printAll()
class Node:
next = None
data = None
def __init__(self, data):
self.data = data
class VerySimpleLinkedList:
# ADT
# find
# getSize
# printAll
# add
# remove
headNode = None
totalSize = 0
def __init__(self, node):
self.headNode = node
self.totalSize = 1
def prepareToGo(self):
node = self.headNode
count = 0
return node, count
def find(self, data):
tuple = self.prepareToGo()
node = tuple[0]
count = tuple[1]
while node is not None:
if node.data == data:
print("found out at index {}".format(count))
return True
node = node.next
count+=1
print("Not found out through entire list!")
return False
def getSize(self):
tuple = self.prepareToGo()
node = tuple[0]
count = tuple[1]
while node is not None:
node = node.next
count+=1
return count
def printAll(self):
tuple = self.prepareToGo()
node = tuple[0]
count = tuple[1]
while node is not None:
print("list[{0}]:{1}".format(count, node.data))
node = node.next
count+=1
def add(self, node):
node.next = self.headNode
self.headNode = node
self.totalSize+=1
def deleted_duplicated(self):
cur = self.headNode
dict = {}
prev = None
while cur is not None:
if cur.data in dict:
prev.next = cur.next
else:
dict[cur.data] = True
prev = cur
cur = cur.next
def remove(self, index):
if (index > self.totalSize -1):
print("index overflow on list!!")
return False
else:
tuple = self.prepareToGo()
node = tuple[0] # self.headNode
count = tuple[1] # 0
prevNode = node
while node is not None:
if index == 0:
self.headNode = node.next
return True
elif node.next == None:
prevNode.next = None
return True
prevNode = node
node = node.next
count += 1
if index == count:
prevNode.next = node.next
node.next = None
return True
return False
def prepareLinkedList():
linkedList = VerySimpleLinkedList(Node(1))
size = linkedList.getSize()
# print("Linked list size : {}".format(size))
# result = linkedList.find(10)
# print(result)
linkedList.add(Node(2))
linkedList.add(Node(2))
linkedList.add(Node(2))
linkedList.add(Node(2))
linkedList.add(Node(2))
linkedList.add(Node(3))
linkedList.add(Node(4))
linkedList.add(Node(5))
linkedList.add(Node(6))
linkedList.add(Node(7))
linkedList.add(Node(7))
linkedList.add(Node(1))
linkedList.add(Node(1))
print("before removed duplicates!")
linkedList.printAll()
print("after removed duplicates!")
linkedList.deleted_duplicated()
linkedList.printAll()
print("DONE")
# print("total size of list : {}".format(linkedList.totalSize))
# result = linkedList.find(3)
# print(result)
# result = linkedList.find(7)
# print(result)
# result = linkedList.find(8)
# print(result)
# linkedList.printAll()
# print("")
# linkedList.remove(6)
# linkedList.printAll()
# print("")
return linkedList
verySimpleLinkedList = prepareLinkedList()
verySimpleLinkedList.printAll()
'''
list[0]:1
list[1]:1
list[2]:7
list[3]:7
list[4]:6
list[5]:5
list[6]:4
list[7]:3
list[8]:2
list[9]:1
list[10]:15
'''
print("")
# Plus, solve the problem for Python Native list Type.
print("Plus, solve the problem for Python Native list Type.")
list = [1,1,7,7,6,5,5,4,4,3,10,10,9,9,1,2,3,4,5,6,7,2,1,15]
list.append(100)
print("original list value : ")
print("["),
for i in list:
print("{},".format(i)),
print("]")
# using dictionary
def removeDuplicatedNode(list):
dict = {}; localList = []
for o in list:
dict[o] = o
for k, v in dict.iteritems():
localList.append(v)
return localList
print("")
print("remove duplicated version of Python list : ")
print("["),
notRepeatedList = removeDuplicatedNode(list)
for i in notRepeatedList:
print("{},".format(i)),
print("]")
print("")
# Q3. reverse String
orderedString = "ABCDEFG"
# the first way : using Python Native API.
def reverseString(str):
return str[::-1]
reverseString = reverseString(orderedString)
print(reverseString)
# the second way
# implement stack first to use stack.
class VerySimpleStack:
# ADT
# Push
# Pop
# Peek
# PopAll
# PrintAll
currentNode = None
totalStackIndexNumber = 0
def __init__(self, newNode):
self.currentNode = newNode
self.totalStackIndexNumber = 0
def push(self, newNode):
prevNode = self.currentNode
self.currentNode = newNode
self.currentNode.next = prevNode
self.totalStackIndexNumber += 1
def pop(self):
targetNode = self.currentNode
self.currentNode = self.currentNode.next
return targetNode
def peek(self):
return self.currentNode.data
def popAll(self):
while self.currentNode is not None:
self.pop()
def printAll(self):
driveNode = self.currentNode
while driveNode is not None:
print (driveNode.data)
driveNode = driveNode.next
s = VerySimpleStack(Node(0))
# s.push(Node(1))
# s.push(Node(2))
# s.push(Node(3))
# s.push(Node(4))
# print("peek : {}".format(s.peek()))
# print("print all stack : ")
# s.printAll()
# print("pop once!")
# s.pop()
# print("peek : {}".format(s.peek()))
# print("print all stack : ")
# s.printAll()
# print("pop once!")
# s.pop()
# print("peek : {}".format(s.peek()))
# print("print all stack : ")
# s.printAll()
# print("pop two times!")
# s.pop()
# s.pop()
# print("print all stack : ")
# s.printAll()
#
# s.push(Node(1))
# s.push(Node(2))
# s.push(Node(3))
# s.push(Node(4))
# s.push(Node(1))
# s.push(Node(2))
# s.push(Node(3))
# s.push(Node(4))
# print("print all stack after pushing a lot : ")
# s.printAll()
# print("print all stack after pop all : ")
# s.popAll()
# s.printAll()
# print("push three times!")
# s.push(Node(100))
# s.push(Node(1000))
# s.push(Node(10000))
# s.printAll()
# print("print all stack after pop all : ")
# s.popAll()
# s.printAll()
#
# orderedString = "ABCDEFG"
print("orderedString : {}".format(orderedString))
list = []
for i in orderedString:
list.append(i)
print("list : {}".format(list))
# for i in orderedString:
for i in list:
s.push(Node(i))
reverseString = []
while s.currentNode is not None:
node = s.pop()
reverseString.append(node.data)
print("reverseString : {}".format(reverseString))
# Q4. replace space with 20%
# Write a method to replace all whitespace in string with %20
# input "Mr John Smith "
# Output "Mr%20John%20Smith"
whitespaceString = "Mr John Smith "
answerString = whitespaceString.strip().replace(" ", "%20")
print(answerString)
# Q5. string compression
'''
Write a method to perform basic string compression using counts of repeated Characters.
If the compression string would not become smaller than the original string,
then return original string.
Input:aabccccaa
Output:a2b1c4a2
'''
# inputString = "aabccccaacccccddddddddddddddddddzzefffffaaasss"
inputString = "aabccccaa"
print("string before being compressed : {}".format(inputString))
# test
# repeat = 4
# c = "c"
# list = "ab"
# for _ in range(repeat):
# list += c
# print("List : {}".format(list))
def compressString(string):
finalOutput = ""
buffer = ""
repeatCount = 1
for character in string:
if finalOutput == "":
finalOutput += character
buffer += character
print("final : {}".format(finalOutput))
# it begins with 'a'
else:
# when continuous characters pattern is changed
if buffer != character:
finalOutput += str(repeatCount)
buffer = character
finalOutput += buffer
repeatCount = 1
# when characters pattern is keeping being continued
else:
repeatCount += 1
buffer = character
if repeatCount >= 1:
finalOutput += str(repeatCount)
return finalOutput
output = compressString(inputString)
print(output)
|
829b68a4cffd7f3addae14a9ca92130378312f9f | OhOverLord/loft-Python | /Алгоритмы_ теория и практика. Структуры данных/(1.2.3)Simulation_network_packet.py | 2,385 | 4.09375 | 4 | """
Симуляция обработки сетевых пакетов
Sample Input 1:
1 0
Sample Output 1:
Sample Input 2:
1 1
0 0
Sample Output 2:
0
Sample Input 3:
1 1
0 1
Sample Output 3:
0
"""
class Queue:
"""
Класс для создания очереди
"""
def __init__(self):
"""
Конструктор класса с созданием списка
"""
self.items = []
def isEmpty(self):
"""
Функция для проверки пустая ли очередь
:return: True или False
"""
return self.items == []
def push(self, item):
"""
Функция для вставки элемента в очередь
:param item: эелемент
"""
self.items.insert(0, item)
def pop(self):
"""
Функция для удаления и возвращения последнего элемента
очереди
:return: последний элемент очереди
"""
return self.items.pop()
def peek(self):
"""
Функция возвращает последний элемент очереди
:return: последний элемент очереди
"""
return self.items[-1]
def size(self):
"""
Функция возвращает размер очереди
:return: размер очереди
"""
return len(self.items)
def main():
"""
Функция реализующая обработку сетевых пакетов
"""
q = Queue() # Обьявление очереди
time = 0 # обьявление переменной времени
buf_size, count = map(int, input().split()) # считывание размера буфера и количества пакетов
for i in range(count):
arrival, duration = map(int, input().split())
while not q.isEmpty() and q.peek() <= arrival:
q.pop()
if time < arrival:
print(arrival)
time = arrival + duration
q.push(time)
elif q.size() < buf_size:
print(time)
time += duration
q.push(time)
else:
print(-1)
if __name__ == '__main__':
main()
|
a2a77dba795ba39cd596e1975bc97f2bbaf14f3f | howardl2/practice | /palindrome_num.py | 1,284 | 4.1875 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
# Example 1:
# Input: 121
# Output: true
# Example 2:
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
# Input: 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Follow up:
# Coud you solve it without converting the integer to a string?
import math
def palindrome_num(num):
if num < 0:
return False
elif num < 10:
return True
n = int(math.log(num, 10)) + 1 # number of digits
stack = []
for idx in range(n//2):
digit = num // 10**idx % 10
stack.append(digit)
startIdx = n//2
if n % 2 != 0:
startIdx = n//2 + 1
for idx in range(startIdx, n):
digit = num // 10**idx % 10
if stack.pop() != digit:
return False
return True
print(palindrome_num(120) == False)
print(palindrome_num(1) == True)
print(palindrome_num(9) == True)
print(palindrome_num(12) == False)
print(palindrome_num(245929542) == True)
print(palindrome_num(24592954) == False)
print(palindrome_num(2459229542) == True)
|
e015977ed62850ea64e24b39f93650012346d744 | ekohilas/comp2041_prac_soln | /version_1/q4.py | 614 | 3.96875 | 4 | import re
import sys
def round_match(match):
# group 0 is the entire match
return str(round(float(match.group(0))))
for line in sys.stdin:
# re.sub will do a regex replacement with specified string.
# to do additional expressions, we can pass in a function that will
# handle the match and return a replacement string
print(re.sub(r"\d+.\d+", round_match, line.strip()))
# you could replace the function with a lambda but why
# note: the round function behaves unexpectadly with
# floating point errors, you could do it andrews's way as
# return str(int(float(match.group(0) + 0.5)))
|
2f685ba54c27c7937688f77789260ea5dde709e7 | JoyC14/notes | /HW5/BFS_06170241.py | 903 | 3.640625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
state2 = []
queue = [s]
while queue:
s = queue.pop(0)
if s not in state2:
state2.append(s)
w = self.graph[s]
for v in w:
queue.append(v)
return state2
def DFS(self, s):
stack = [s]
stateb = []
while stack:
s = stack.pop(-1)
if s not in stateb:
stateb.append(s)
w = self.graph[s]
for v in w:
stack.append(v)
return stateb
# In[ ]:
# In[ ]:
|
d67f0c3e827060bd5b0bfda467cb4393f4b5f821 | BrodyCur/python_fundamentals1 | /exercise3.py | 590 | 3.8125 | 4 | print("What is your name?")
user_name = input()
print("Hello, {}".format(user_name))
secret_password = "please"
print("What's the password?")
password_attempt = input()
correct_or_not = (password_attempt == secret_password)
print("That's {}".format(correct_or_not))
print("How many cookies have been eaten?")
eaten = input()
remaining_cookies = 12 - int(eaten)
print("There are {} cookies left.".format(remaining_cookies))
print("How old are you (or will you be this year)?")
age = input()
birth_year = 2019 - int(age)
print("You were born in the year {}!".format(birth_year)) |
13a6fbb232f3029a889dad96800fbbc1dac20b99 | daniel-reich/turbo-robot | /2nciiXZN4HCuNEmAi_13.py | 1,419 | 3.90625 | 4 | """
The nesting of lists can be viewed indirectly as curves and barriers of the
real data embedded in lists, thus, defeats the very purpose of directly
accessing them thru indexes and slices. In this challenge, a function is
required to **flatten those curves** (i.e. level, iron, compress, raze,
topple) and expose those data as a **single list** and not as a _list of
lists_.
### Examples
flatten([[[[[["direction"], [372], ["one"], [[[[[["Era"]]]], "Sruth", 3337]]], "First"]]]])
➞ ["direction", 372, "one", "Era", "Sruth", 3337, "First"]
flatten([[4666], [5394], [466], [[["Saskia", [[[[["DXTD"]], "Lexi"]]]]]]])
➞ [4666, 5394, 466, "Saskia", "DXTD", "Lexi"]
flatten([[696], ["friend"], ["power"], [[[["Marcus"]]]], ["philus"]])
➞ [696, "friend", "power", "Marcus", "philus"]
flatten([[["deep"], [[["ocean"]]], [["Marge"]], ["rase", 876]]])
➞ ["deep", "ocean", "Marge", "rase", 876]
### Notes
* There are no empty lists to handle.
* You're expected to solve this challenge using a **recursive approach**.
* You can read on more topics about recursion (see **Resources** tab) if you aren't familiar with it yet or haven't fully understood the concept behind it before taking up this challenge.
"""
def flatten(r):
if r == []:
return r
if isinstance(r[0], list):
return flatten(r[0]) + flatten(r[1:])
return r[:1] + flatten(r[1:])
|
4fe651b79c2c04fe30bf0ebc49af0c256082de08 | Cherietabb/python_algorithms | /pet_test.py | 728 | 4.15625 | 4 | __author__ = 'Cherie Tabb'
import pet
def make_list():
pet_list = []
for count in range(1, 2):
name = input("Enter your pet's name: ")
animal_type = input("What pet_type of pet is it: ")
age = int(input('Enter the age of your pet: '))
new_pet = pet.Pet(name, animal_type, age)
pet_list.append(new_pet)
return pet_list
def display_list(pet_list):
for item in pet_list:
print('')
print(item.get_name())
print(item.get_animal_type())
print(item.get_age())
def main():
# Create an empty list.
pets = make_list()
print('')
print('Here are the pets you listed: ')
display_list(pets)
if __name__ == "__main__":
main()
|
bbdfddac759c36df02e3f41c7c4aad0688235bb2 | arijit1410/cs498 | /assignment2/models/neural_net.py | 10,977 | 4.03125 | 4 | """Neural network model."""
from typing import Sequence
import numpy as np
class NeuralNetwork:
"""A multi-layer fully-connected neural network. The net has an input
dimension of N, a hidden layer dimension of H, and performs classification
over C classes. We train the network with a cross-entropy loss function and
L2 regularization on the weight matrices.
The network uses a nonlinearity after each fully connected layer except for
the last. The outputs of the last fully-connected layer are passed through
a softmax, and become the scores for each class."""
def __init__(
self,
input_size: int,
hidden_sizes: Sequence[int],
output_size: int,
num_layers: int,
):
"""Initialize the model. Weights are initialized to small random values
and biases are initialized to zero. Weights and biases are stored in
the variable self.params, which is a dictionary with the following
keys:
W1: 1st layer weights; has shape (D, H_1)
b1: 1st layer biases; has shape (H_1,)
...
Wk: kth layer weights; has shape (H_{k-1}, C)
bk: kth layer biases; has shape (C,)
Parameters:
input_size: The dimension D of the input data
hidden_size: List [H1,..., Hk] with the number of neurons Hi in the
hidden layer i
output_size: The number of classes C
num_layers: Number of fully connected layers in the neural network
"""
self.input_size = input_size
self.hidden_sizes = hidden_sizes
self.output_size = output_size
self.num_layers = num_layers
self.t = 0; self.m = {}; self.v = {}
assert len(hidden_sizes) == (num_layers - 1)
sizes = [input_size] + hidden_sizes + [output_size]
self.params = {}
for i in range(1, num_layers + 1):
self.params["W" + str(i)] = np.random.randn(sizes[i - 1], sizes[i]) / np.sqrt(sizes[i - 1])
self.params["b" + str(i)] = np.zeros(sizes[i])
def linear(self, W: np.ndarray, X: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Fully connected (linear) layer.
Parameters:
W: the weight matrix
X: the input data
b: the bias
Returns:
the output
"""
return np.dot(X, W) + b
def linear_grad(self, prev_input, upstream_grad):
"""Gradient of Fully connected (linear) layer.
Parameters:
W: the weight matrix
X: the input data
b: the bias
Returns:
the output
"""
return np.matmul(prev_input.T, upstream_grad)
def relu(self, X: np.ndarray) -> np.ndarray:
"""Rectified Linear Unit (ReLU).
Parameters:
X: the input data
Returns:
the output
"""
return np.maximum(X, 0)
def relu_grad(self, X: np.ndarray) -> np.ndarray:
"""Gradient of Rectified Linear Unit (ReLU).
Parameters:
X: the input data
Returns:
the output data
"""
X[X <= 0] = 0
X[X > 0] = 1
return X
def softmax(self, X: np.ndarray) -> np.ndarray:
"""The softmax function.
Parameters:
X: the input data
Returns:
the output
"""
exps = np.exp(X - np.max(X, axis=1).reshape((-1,1)))
return exps / np.sum(exps, axis=1).reshape((-1,1))
def delta_cross_entropy(self, X: np.ndarray, y: np.ndarray) -> np.ndarray:
""" Gradient of softmax.
Parameters:
X: the input data
y: vector of training labels
Retuns:
the output data
"""
m = y.shape[0]
grad = self.softmax(X)
grad[range(m), y] -= 1
return grad / m
def cross_entorpy(self, X: np.ndarray, y: np.ndarray) -> np.ndarray:
""" Gradient of softmax.
Parameters:
X: the input data
y: vector of training labels
Retuns:
the output data
"""
m = y.shape[0]
p = self.softmax(X)
if np.all(p) == False:
print(np.all(p))
log_like = -np.log(p[range(m),y])
return np.sum(log_like) / m
def calc_total_loss(self, reg, loss, m):
cost = 0
for key in self.params.keys():
if key[0] == 'W':
cost += np.sum(np.square(self.params[key]))
cost *= reg / (2*m)
total_loss = loss + cost
total_loss = np.squeeze(total_loss)
return total_loss
def initialize_grads(self, layer):
self.gradients['W'+str(layer)] = np.zeros(self.params['W'+str(layer)].shape)
self.gradients['b'+str(layer)] = np.zeros(self.params['b'+str(layer)].shape)
def forward(self, X: np.ndarray) -> np.ndarray:
"""Compute the scores for each class for all of the data samples.
Hint: this function is also used for prediction.
Parameters:
X: Input data of shape (N, D). Each X[i] is a training or
testing sample
Returns:
Matrix of shape (N, C) where scores[i, c] is the score for class
c on input X[i] outputted from the last layer of your network
"""
self.outputs = {}
# implement me. You'll want to store the output of each layer in
# self.outputs as it will be used during back-propagation. You can use
# the same keys as self.params. You can use functions like
# self.linear, self.relu, and self.softmax in here.
score = np.zeros((X.shape[0], self.output_size))
for layer in range(1, self.num_layers + 1):
weight = self.params['W' + str(layer)]
bias = self.params['b' + str(layer)]
if layer == 1:
output = self.linear(weight, X, bias)
self.outputs['o' + str(layer)] = output
self.outputs['i' + str(layer)] = X
input_ = self.relu(output)
elif (layer > 1) and (layer < self.num_layers):
output = self.linear(weight, input_, bias)
self.outputs['o' + str(layer)] = output
self.outputs['i' + str(layer)] = input_
input_ = self.relu(output)
else:
output = self.linear(weight, input_, bias)
self.outputs['o' + str(layer)] = output
self.outputs['i' + str(layer)] = input_
score = self.softmax(output)
return score
def backward(self, y: np.ndarray, reg: float = 0.0) -> float:
"""Perform back-propagation and compute the gradients and losses.
Note: both gradients and loss should include regularization.
Parameters:
y: Vector of training labels. y[i] is the label for X[i], and each
y[i] is an integer in the range 0 <= y[i] < C
reg: Regularization strength
Returns:
Total loss for this batch of training samples
"""
self.gradients = {}
# TODO: implement me. You'll want to store the gradient of each
# parameter in self.gradients as it will be used when updating each
# parameter and during numerical gradient checks. You can use the same
# keys as self.params. You can add functions like self.linear_grad,
# self.relu_grad, and self.delta_cross_entropy if it helps organize your code.
upstream_grad = 0
for layer in reversed(range(1, self.num_layers+1)):
if 'W'+str(layer) not in self.gradients and 'b'+str(layer) not in self.gradients:
self.initialize_grads(layer)
output = self.outputs['o'+str(layer)]
weight = self.params['W'+str(layer)]
m = output.shape[0]
prev_input = self.outputs['i'+str(layer)]
if layer == self.num_layers:
loss = self.cross_entorpy(output, y)
upstream_grad = self.delta_cross_entropy(output, y)
linear_grad = self.linear_grad(prev_input, upstream_grad)
self.gradients['W'+str(layer)] = linear_grad + (reg/m)*weight
self.gradients['b'+str(layer)] = np.sum(upstream_grad, 0)
upstream_grad = np.dot(upstream_grad, weight.T)
else:
relu_grad = self.relu_grad(output)
upstream_grad = upstream_grad*relu_grad
linear_grad = self.linear_grad(prev_input, upstream_grad)
self.gradients['W'+str(layer)] = linear_grad + (reg/m)*weight
self.gradients['b'+str(layer)] = np.sum(upstream_grad, 0)
upstream_grad = np.dot(upstream_grad, weight.T)
total_loss = self.calc_total_loss(reg, loss, m)
return total_loss
def SGD(self, lr):
for key in self.params.keys():
self.params[key] -= lr * self.gradients[key]
def SGD_momentum(self, lr, b1):
for key in self.params.keys():
if key not in self.m and key not in self.v:
self.m[key] = np.zeros(self.params[key].shape)
self.m[key] = b1*self.m[key] - lr*self.gradients[key]
self.params[key] += self.m[key]
def Adam(self, lr, b1, b2, eps, epoch):
#TODO: Implement Adam
self.t = epoch
for key in self.params.keys():
if key not in self.m and key not in self.v:
self.m[key] = np.zeros(self.params[key].shape)
self.v[key] = np.zeros(self.params[key].shape)
gt = self.gradients[key]
# self.update_Adam(b1, b2, gt, key)
self.params[key] -= lr * np.divide(self.m[key], ((self.v[key]**(1/2)) + eps))
self.m[key] = b1*self.m[key] + (1 - b1) * gt
self.v[key] = b2*self.v[key] + (1 - b2) * np.square(gt)
lr = lr * (1 - b2**self.t)**(1/2) / (1-b1**self.t)
self.params[key] = self.params[key] - np.divide((lr * self.m[key]), (self.v[key]**(1/2)+eps))
def update(
self,
lr: float = 0.001,
b1: float = 0.9,
b2: float = 0.999,
eps: float = 1e-8,
opt: str = "SGD",
epoch: int = 0
):
"""Update the parameters of the model using the previously calculated
gradients.
Parameters:
lr: Learning rate
b1: beta 1 parameter (for Adam)
b2: beta 2 parameter (for Adam)
eps: epsilon to prevent division by zero (for Adam)
opt: optimizer, either 'SGD' or 'Adam'
"""
if opt == 'SGD':
self.SGD(lr)
elif opt == 'Adam':
self.Adam(lr, b1, b2, eps, epoch)
else:
self.SGD_momentum(lr, b1) |
c4ffe9f905667c5465d98cf4560b5c5c3bda9041 | sevgo/Programming101 | /week1/the_final_round/count_words.py | 477 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def count_words(arr):
"""Counts words in a list and returns a dictionary
of the type {"word":count} """
unique = set(arr)
words = {}
for element in unique:
words[element] = 0
for el in unique:
for e in arr:
if e == el:
words[el] += 1
return words
if __name__ == "__main__":
print (count_words(["ala", "bala", "ala", "store", "new", "key", "new"]))
|
21cf231232cf42e9e30f99db0f3645f4d790faf5 | xwzl/python | /python/src/com/python/learn/obj/ClassExtend.py | 4,361 | 4.125 | 4 | # 继承是面向对象的三大特征之一,也是实现代码复用的重要手段。继承经常用于创建和现有类功能类似的新类,又或是新类只需要在现有类基础上添加一些成员(属性和方法),但又不想直接将现有类代码
# 复制给新类。
#
# 例如,有一个 Shape 类,该类的 draw() 方法可以在屏幕上画出指定的形状,现在需要创建一个 Rectangle 类,要求此类不但可以在屏幕上画出指定的形状,还可以计算出所画形状的面积。要创建这
# 样的 Rectangle 类,除了将 draw() 方法直接复制到新类中,并添加计算面积的方法,其实还有更简单的方法,即让 Rectangle 类继承 Shape 类,这样当 Rectangle 类对象调用 draw() 方法时,
# Python 解释器会自动去 Shape 类中调用该方法,如此,我们只需在 Rectangle 类中添加计算面积的方法即可。
#
# Python 中,实现继承的类称为子类,被继承的类称为父类(也可称为基类、超类)。子类继承父类的语法是:在定义子类时,将多个父类放在子类之后的圆括号里。语法格式如下:
#
# class 类名(父类1, 父类2, ...):
# #类定义部分
#
# 注意,Python 的继承是多继承机制,即一个子类可以同时拥有多个直接父类。
#
# 从上面的语法格式来看,定义子类的语法非常简单,只需在原来的类定义后增加圆括号,并在圆括号中添加多个父类,即可表明该子类继承了这些父类。如果在定义一个 Python 类时,并未显式指定这个类
# 的直接父类,则这个类默认继承 object 类。
#
# object 类是所有类的父类,要么是直接父类,要么是间接父类。
#
# 父类和子类的关系,就好像水果和苹果的关系,苹果是一种特殊的水果,苹果是水果的子类,水果是苹果的父类,因此可以说,苹果继承了水果。不仅如此,由于子类是一种特殊的父类,因此父类包含的范围
# 总比子类包含的范围要大,所以可以认为父类是大类,而子类是小类。
#
# 从实际意义上看,子类是对父类的扩展,子类是一种特殊的父类。从这个意义上看,使用继承来描述子类和父类的关系是错误的,用扩展更恰当。因此,这样的说法更加准确:苹果扩展了水果这个类。
#
# 从子类的角度来看,子类扩展(extend)了父类;但从父类的角度来看,父类派生(derive)出子类。也就是说,扩展和派生所描述的是同一个动作,只是观察角度不同而已。
class Fruit:
def info(self):
print("我是一个水果!重%g克" % self.weight)
class Food:
def taste(self):
print("不同食物的口感不同")
# 定义Apple类,继承了Fruit和Food类
class Apple(Fruit, Food):
pass
# 创建Apple对象
a = Apple()
a.weight = 5.6
# 调用Apple对象的info()方法
a.info()
# 调用Apple对象的taste()方法
a.taste()
# 关于Python的多继承
#
# 大部分面向对象的编程语言(除了 C++)都只支持单继承,而不支持多继承,这是由于多继承不仅增加了编程的复杂度,而且很容易导致一些莫名的错误。
#
# Python 虽然在语法上明确支持多继承,但通常推荐如果不是很有必要,则尽量不要使用多继承,而是使用单继承,这样可以保证编程思路更清晰,而且可以避免很多麻烦。
#
# 当一个子类有多个直接父类时,该子类会继承得到所有父类的方法,这一点在前面示例中己经做了示范。现在的问题是,如果多个父类中包含了同名的方法,此时会发生什么呢?此时排在前面的父类中的方法会“遮蔽”
# 排在后面的父类中的同名方法。例如如下代码:
class Item:
def info(self):
print("Item中方法:", '这是一个商品')
class Product:
def info(self):
print("Product中方法:", '这是一个工业产品')
# Mouse 继承了 Item 类和 Product 类,由于 Item 排在前面,因此 Item 中定义的方法优先级更好,Python 会优先到 Item 父类中搜寻方法,一旦在 Item 父类中搜寻到目标方法,Python 就不会
# 继续向下搜寻了。
class Mouse(Item, Product):
pass
m = Mouse()
m.info()
|
addf439650324b961f83d0ad44298431761cd0d1 | vansoares/challenges_solutions | /educative.io/algorithms-in-python/sorting/bubble-sort.py | 560 | 4.125 | 4 | def bubble_sort(lst):
is_not_sorted = False
array_size = len(lst)
index = 0
while not is_not_sorted:
changed = False
for i in range(array_size-1):
if i+1 >= array_size:
continue
current = lst[i]
next = lst[i+1]
if next < current:
lst[i], lst[i+1] = lst[i+1], lst[i]
changed = True
print(lst)
if not changed:
is_not_sorted = True
return lst
print(bubble_sort([5,3,8,6,9,2,1,4,7,10])) |
0e8cdf2c90821eb42e1a593d38c5b50b72d9f9c5 | zanariah8/Starting_Out_with_Python | /chapter_05/rectangle.py | 427 | 3.828125 | 4 | # the rectangle module has functions that performs
# calculations related to rectangle
# the area function accepts a rectangle's width and
# length as arguments and returns the rectangle's area
def area(width, length):
return width * length
# the perimeter function accepts a rectangle's width
# and length as arguments and returns the rectangle's perimeter
def perimeter(width, length):
return 2 * (width+length) |
01677a7c933fa163221e27a8bea963a35b8888be | oddsorevans/eveCalc | /main.py | 2,991 | 4.34375 | 4 | # get current day and find distance from give holiday (christmas) in this case
from datetime import date
import json
#made a global to be used in functions
holidayList = []
#finds the distance between 2 dates. Prints distance for testing
def dateDistance(date, holiday):
distance = abs(date - holiday).days
print(distance)
return distance
#The holiday has a dummy year, since that could change depending on the current date.
#To get around that, the program finds the year of the next time the holiday will occur
#dependent on the date given
def findYear(date, holiday):
if date.month < holiday.month:
holiday = holiday.replace(date.year)
elif date.month > holiday.month:
holiday = holiday.replace(date.year + 1)
else:
if date.day > holiday.day:
holiday = holiday.replace(date.year + 1)
else:
holiday = holiday.replace(date.year)
return holiday
#check if a given variable is in the list, and return true or false
def findInList(list, variable):
present = False
for i in list:
if i == variable:
present = True
return present
#get user input
def userInput():
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
#keep window open until they get the correct answer
correctInput = False
while correctInput == False:
if desired == "options":
print(holidayList)
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
else:
if findInList(holidayList, desired) == True:
correctInput = True
else:
print("That is not a valid holiday")
desired = input("What holiday would you like to calculate the eve for? Type options for available holidays\n")
return desired
def main():
#take contents of json and load into dictionary
holidayDict = {}
scratch = open("holidays.json", 'r')
temp = scratch.read()
holidayDict = (json.loads(temp))
#create list with all the titles so that the user knows input options
#as well as something to check their input on
for i in holidayDict["holidayList"]:
holidayList.append(i)
desired = userInput()
print(holidayDict["holidayList"][desired])
#d1 can be altered to custom date to test year finding function
d1 = date.today()
#1 is a dummy year. Will be used to check if it is a user created year
holiday = date(holidayDict["holidayList"][desired]["year"],holidayDict["holidayList"][desired]["month"],holidayDict["holidayList"][desired]["day"])
holiday = findYear(d1, holiday)
eve = "Merry " + desired
#print out eve for distance. If date distance is 0, it is that day
#and never concatenates eve
for i in range(0, dateDistance(d1, holiday)):
eve = eve + " eve"
eve = eve + "!"
print(eve)
main() |
38911ac68c8478b8dfe07ea708b8f5df11a59f57 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_203/547.py | 1,583 | 3.796875 | 4 | def contain(matriz, char):
for r in matriz:
if char in r:
return True
return False
def print_mat(matriz):
for r in matriz:
print(''.join(r))
def change_direita(matriz, char, r, c):
lim = len(matriz[0]) - 1
while c<lim and matriz[r][c+1] == '?':
c += 1
matriz[r][c] = char
def change_esquerda(matriz, char, r, c):
lim = 0
while(c > lim and matriz[r][c-1] == '?'):
c -= 1
matriz[r][c] = char
def change_cima(matriz, char, r, c):
lim = 0
while (r > lim and matriz[r-1][c] == '?'):
r -= 1
matriz[r][c] = char
def change_baixo(matriz, char, r, c):
lim = len(matriz) -1
while(r<lim and matriz[r+1][c] == '?'):
r+=1
matriz[r][c] = char
def change_matriz(matriz, vlr):
for r in range(len(matriz)):
for c in range(len(matriz[0])):
if matriz[r][c] != '?':
if vlr % 2 == 0:
change_direita(matriz, matriz[r][c], r, c)
change_esquerda(matriz, matriz[r][c], r, c)
else:
change_cima(matriz, matriz[r][c], r, c)
change_baixo(matriz, matriz[r][c], r, c)
def answer():
r,c = [int (s) for s in input().split(' ')]
mat = []
for i in range(r):
mat.append(list(input()))
vlr = 1
while contain(mat,'?'):
change_matriz(mat, vlr)
vlr+= 1
print_mat(mat)
times = int(input())
for t in range(1,times + 1):
print('Case #{}:'.format(str(t)))
answer()
|
967be1f8566036398185c1586cab28c510b60759 | dustinsnoap/code-challenges | /python/missing_number.py | 1,214 | 3.8125 | 4 | # Given an array nums containing n distinct numbers taken from 0, 1, 2, ..., n, return the one that is missing from the array.
# Follow up: Could you implement a solution using only constant extra space complexity and linear runtime complexity?
# Example 1:
# Input: nums = [3,0,1]
# Output: 2
# Example 2:
# Input: nums = [0,1]
# Output: 2
# Example 3:
# Input: nums = [9,6,4,2,3,5,7,0,1]
# Output: 8
# Example 4:
# Input: nums = [0]
# Output: 1
# Constraints:
# n == nums.length
# 1 <= n <= 104
# 0 <= nums[i] <= n
# All the numbers of nums are unique.
def missingNumber(nums):
expected = [None] * (len(nums)+1)
for n in nums: expected[n] = n
for i in range(len(expected)):
if expected[i] == None: return i
return False
def missingNumber2(nums):
return set([n for n in range(len(nums)+1)]).difference(set(nums)).pop()
def missingNumber3(nums):
max_n = len(nums)
total = 0
for n in nums: total += n
return int((max_n*(max_n+1))/2 - total)
from tools import test
inputs = [[3,0,1],[0,1],[9,6,4,2,3,5,7,0,1],[0]]
outputs = [2,2,8,1]
funcs = [missingNumber,missingNumber2,missingNumber3]
test(inputs, outputs, funcs) |
9246f2d852f477afcaadb6d9ea1f538cc02d87cc | jeanggabriel/jean-scripts | /curso em video/array.py | 182 | 3.671875 | 4 | while True:
a = str(input('nome:'))
b = str(input('telefone: '))
c = str(input('cpf: '))
d= [a ,b ,c]
for i in (a,b,c,d):
print(i)
break |
e439ece96da236dd2c4f50d67a3831624844bb7e | JuDaGoRo/grup05 | /ejesuma.py | 211 | 3.828125 | 4 | print ("Escriba el limite superior de la suma")
n = int (input())
suma = 0 # desde que numero comienza el ciclo
for i in range (1, n +1):
suma = suma + i # Esto es igual a decir "suma = suma + 1
print (suma) |
4b3187694d3f43ef8b7ee834c64e18fad6e4b5d3 | DSXiangLi/Leetcode_python | /script/[662]二叉树最大宽度.py | 2,352 | 4 | 4 | # 给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节
# 点为空。
#
# 每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
#
# 示例 1:
#
#
# 输入:
#
# 1
# / \
# 3 2
# / \ \
# 5 3 9
#
# 输出: 4
# 解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
#
#
# 示例 2:
#
#
# 输入:
#
# 1
# /
# 3
# / \
# 5 3
#
# 输出: 2
# 解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
#
#
# 示例 3:
#
#
# 输入:
#
# 1
# / \
# 3 2
# /
# 5
#
# 输出: 2
# 解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
#
#
# 示例 4:
#
#
# 输入:
#
# 1
# / \
# 3 2
# / \
# 5 9
# / \
# 6 7
# 输出: 8
# 解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
#
#
# 注意: 答案在32位有符号整数的表示范围内。
# Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 384 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
maxw = 0
stack = [(root,0)]
while stack:
l = len(stack)
left = 0
for i in range(l):
node, pos = stack.pop(0)
if i==0:
left= pos
if node.left:
stack.append((node.left, pos*2))
if node.right:
stack.append((node.right, pos*2+1))
if i==l-1:
maxw = max(maxw, pos-left+1)
return maxw
# leetcode submit region end(Prohibit modification and deletion)
|
092bd9ab615cf0970301c7df2e126f91b3511140 | Vampir007one/Python | /Kalmykov_Practical_5/quest17.py | 359 | 3.984375 | 4 | from math import sqrt
partialSum = 0
partialSumSquares = 0
n = 0
number = int(input("Введите число: "))
while number != 0:
n += 1
partialSum += number
partialSumSquares += number ** 2
number = int(input("Введите число: "))
answer = sqrt((partialSumSquares - partialSum ** 2 / n) / (n - 1))
print("Ответ:", answer)
|
66a81b6ebccfaae8022462d95bf9ae5ddde7ef0a | OnsJannet/holbertonschool-web_back_end | /0x00-python_variable_annotations/5-sum_list.py | 368 | 4.03125 | 4 | #!/usr/bin/env python3
'''
takes a list input_list of floats
as argument and returns their sum as a float.
'''
from typing import List
def sum_list(input_list: List[float]) -> float:
'''returns the sum of a list of floats
Args:
input_list (float): [list of floats]
Returns:
float: [sum of list items]
'''
return sum(input_list)
|
d85fa9097f2df522bdb488cdf50255ca48e53dd0 | YifanC86/hrinf-development | /2020-2021/DEV2/Chapter 1B/BA04.py | 231 | 3.546875 | 4 | def breakUp4DigitNumber(num):
digit4 = num % 10
num = num // 10
digit3 = num % 10
num = num // 10
digit2 = num % 10
num = num // 10
digit1 = num % 10
num = num // 10
print()
input = 123
breakUp4DigitNumber(input) |
b302806221377a29e3d973cc8613fb97a669e610 | wxl789/python | /Day06/1-代码/基础内容/17-作业.py | 1,668 | 3.703125 | 4 | # 1、
# 1.1、从控制台输入两个数,输出较大的那个数
# 1.2、从控制台输入三个数,输出较大的那个数
# 不准使用max min
'''
a = input()
b = input()
numA = int(a)
numB = int(b)
if a > b:
print(a)
else:
print(b)
'''
'''
a = int(input())
b = int(input())
c = int(input())
if a >= b and a >= c:
print(a)
if b >= a and b >= c:
print(b)
if c >= b and c >= a:
print(c)
'''
print("**************")
# 2、判断平闰年
'''
闰年的条件:1、能被4整除,不能被100整除
2、能被400整除
满足以上两个条件的任意一个就是闰年。
'''
'''
year = int(input())
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("yes")
else:
print("no")
'''
# 3、中奖:从控制台输入一个数字,判断是否与随机的哪个数字一致,一致则
# 中奖;不一致,提示很遗憾
'''
import random
res = random.randrange(10, 20)
print(res)
a = int(input())
if a == res:
print("中奖")
else:
print("!!!!!!!!!!!!!!!!")
'''
# 4、从控制台输入一个五位数,是回文数打印yes,不是打印no
# 12321 11111 11211 32523
'''
a = int(input()) # 12321
ge = a % 10
shi = (a // 10) % 10
qian = (a // 1000) % 10
wan = a // 10000
if ge==wan and qian==shi:
print("yes")
else:
print("no")
'''
# 5、从控制台输入一个三位数,判断当前数字是否为水仙花数,是打印yes,
# 否打印no
# 153 1^3+5^3+3^3 = 153
# 222
'''
a = int(input()) # 153
ge = a % 10
shi = (a // 10) % 10
bai = a // 100
if ge**3+shi**3+bai**3 == a:
print("yes")
else:
print("no")
'''
# String
# 循环语句
# List
|
61813e43dbfb6c4be84104f9e042207ef3beeb2e | sohitmiglani/Applications-in-Python | /Max Heaps.py | 931 | 4.125 | 4 | # This is the algorithm for building and working with heaps, which is a tree-based data structure.
# It allows us to build a heap from a given list, extract certain element, add and remove them.
def max_heapify(A, i):
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < len(A) and A[left] > A[largest]:
largest = left
if right < len(A) and A[right] > A[largest]:
largest = right
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest)
def build_max_heap(A):
for i in range(len(A) // 2, -1, -1):
max_heapify(A, i)
def heap_extract_max(list):
build_max_heap(list)
max = list[0]
list = list[1:]
build_max_heap(list)
return max, list
def max_heap_push(list,x):
list.append(x)
build_max_heap(list)
return list
def max_heap_pop(list):
list.remove(min(list))
build_max_heap(list)
return list
|
e95f8037552d517853d4170ce68fedd3aae93fab | nyxssmith/damageReport | /main.py | 3,375 | 3.734375 | 4 | import requests
from lxml import html
import time
address = "https://www.reddit.com/r/all/"
def checkValidLink(link):#checks if the link will work or not, so we can use this to remove bad links from lists and make sure the program wont error
try:
page = requests.get(link).text#we get the webpage
#print(link,"is valid")
return True
except:
#print(link,"is not valid")
return False
def openPage(address):
if(not checkValidLink):
return 0,0,[],null,null
page = requests.get(address).text#we get the webpage
doc = html.fromstring(page)#doc convets the page to strings
pageLines = page.split("\n")#my method of making a list of lines in the html
linesWithLinks = []
numberOfLines = 0
linkCount=1
toFind = "a href"#this makes a list of all lines of html that contain links
for line in pageLines:
if(line.find(toFind)!=-1):
#print("contains a link")
linesWithLinks.append(line)
linkCount+=1
numberOfLines+=1
return linkCount,numberOfLines,linesWithLinks,doc,page
def findLinkTo(to,linksList,doc):#takes linesWithLinks and doc at end
i=0
for linkline in linksList:
link = doc.cssselect("a")[i]
i+=1
if(link.text_content()==to):
return linkline,link
def listLinksTo(to,linksList,doc):#takes linesWithLinks and doc at end
listOfFinishedLinks = []
for line in linksList:
#print(line)
if to in line:
listOfFinishedLinks.append(getUrlFromLink(line))
return listOfFinishedLinks#returns a list that has links to the 'to' search term
def getUrlFromLink(rawLinkLine):#gets the hmtl file from the line with the link in html
string = rawLinkLine#make my typing easyer
i=0
j=0
try:
for char in string:
if(string[i]=='<' and string[i+1]=='a'):
string = string[i+9:]#cuts off the firts part upto the name of the hml
#now to cut off the end part
i+=1
except:
pass#this makes it not throw out of bounds exepction, and ignores it because we are hunting for something in the middle
#now to remove the rest past .html
try:
for char in string:
if(string[j]=='.' and string[j+1]=='h' and string[j+2]=='t' and string[j+3]=='m' and string[j+4]=='l'):
string = string[:j+5]#cuts off the rest past hmtl
#print(string)
j+=1
except:
pass#this makes it not throw out of bounds exepction, and ignores it because we are hunting for something in the middle
return string
def toFullLink(inputList):
outputList = []
for item in inputList:
item=addressBase+item
outputList.append(item)
return outputList
def removeInvalidLinks(inputList):
outputList = []
for item in inputList:
if(checkValidLink(item)):
outputList.append(item)
return outputList
def addToSet(inputSet,inputList):
for item in inputList:
inputSet.add(item)
def elementsMustHave(inputSet,mustHave,outputSet):
for item in inputSet:
if(item.find(mustHave)!=-1):
outputSet.add(item)
def outputToText(inputSet,name):
with open(name,"w") as N:
for item in inputSet:
N.write(item+"\n")
def outputToWeb(inputSet,name):
with open(name,"w") as N:
N.write("<html> \n <body> \n")
for item in inputSet:
N.write("<a href="+item+">"+item+"</a> <br>\n")
#program starts here
startTime = time.time()
linkCountM, numberOfLinesM, linesWithLinksM, docM, pageM = openPage(address)
pageM =pageM.lower()
print(numberOfLinesM)
print(type(pageM))
print(time.time()-startTime,"seconds to run")
|
a77ee4118dc3985d5b09a1a3257e9f276310d8e9 | AadityaDeshpande/PythonAssignments | /Intermediate/IntermediatePython/Assignments/Day2/Q5.py | 158 | 3.921875 | 4 | sentence = 'It is raining cats and dogs'
token = sentence.split(" ")
print(token)
targetList = [ len(word) for word in token ]
print(targetList)
|
3c947d233c597b7b2d57c8b20ca4855f19d9b125 | botamochi0x12/Yet-Another-SCP-Wiki-Bot-For-Slack | /wait.py | 3,255 | 3.59375 | 4 | """
Util functions to wait for time to post notifications.
"""
import time
from datetime import datetime, timedelta, timezone
from typing import Optional
TimeSeconds = float
Datetime = datetime
# offset from UTC to JST
TIMEZONE_OFFSET = (timedelta(hours=9) - timedelta(hours=0)).seconds
def wait_until(
then: Optional[Datetime] = None,
*,
day=None, hour=0, minute=0, second=0,
_how_to_know_now=None,
_sleep=time.sleep,
_debug=print,
) -> None:
"""Wait until a specific time point. Default to 0:00 on the next day.
Args:
then (Optional[Datetime], optional): Defaults to None.
day (Optional[int], optional): Defaults to today.
hour (int, optional): Defaults to 0.
minute (int, optional): Defaults to 0.
second (int, optional): Defaults to 0.
_how_to_know_now (optional): Defaults to None.
_sleep (optional): Defaults to time.sleep.
_debug (optional): Defaults to print.
>>> now = Datetime.now(tz=timezone(timedelta(hours=+9)))
>>> wait_until(
... hour=now.hour, minute=now.minute, second=now.second,
... _sleep=(lambda _: None),
... _how_to_know_now=(lambda: Datetime.now(tz=timezone(timedelta(hours=0)))),
... )
Wait for 0.0 sec(s).
"""
duration = compute_duration_to_tomorrow(
then=then,
day=day,
hour=hour,
minute=minute,
second=second,
# for debugging
how_to_know_now=_how_to_know_now if _how_to_know_now else Datetime.now,
)
duration = duration - TIMEZONE_OFFSET
if duration < 0.0:
duration += 24 * 60 * 60.0
_debug(f"Wait for {duration} sec(s).")
_sleep(duration)
def compute_duration_to_tomorrow(
then: Optional[Datetime] = None,
*,
how_to_know_now=Datetime.now,
**kwargs
) -> TimeSeconds:
"""
>>> now = Datetime(year=2020, month=6, day=15, hour=0)
>>> duration_to_tomorrow = compute_duration_to_tomorrow(
... how_to_know_now=(lambda: now),
... day=now.day, hour=1,
... )
>>> duration_to_yesterday = compute_duration_to_tomorrow(
... how_to_know_now=(lambda: now),
... day=(now.day-1), hour=1,
... )
>>> int(duration_to_yesterday) == int(duration_to_tomorrow)
True
"""
if then is None and len(kwargs) == 0:
raise ValueError("Any of `datetime` properties should be specified.")
now = how_to_know_now()
if then is None:
if kwargs["day"] is None:
kwargs["day"] = now.day
then: Datetime = now.replace(**kwargs)
duration = differ_from(now=now, then=then)
if duration < 0.0:
duration += 24 * 60 * 60.0
return duration
def differ_from(*, now: Datetime, then: Datetime) -> TimeSeconds:
"""
>>> now = Datetime.now()
>>> duration = differ_from(now=now, then=now)
>>> int(duration)
0
>>> tomorrow = now.replace(day=(now.day + 1))
>>> duration = differ_from(now=now, then=tomorrow)
>>> int(duration)
86400
>>> yesterday = now.replace(day=(now.day - 1))
>>> duration = differ_from(now=now, then=yesterday)
>>> int(duration)
-86400
"""
duration = (then - now).total_seconds()
return duration
|
7dd9ba628edb65afeaa8e83edb3a2d849bc8c768 | ragavan98/Numpy-study | /Lec2-Arrays.py | 7,961 | 4.03125 | 4 | import numpy as np
# Creating a 0-Dimensional array
print("#### Creating a 0-Dimensional array ####")
arr0Dimensional = np.array(42)
print(arr0Dimensional)
# print(type(arr0Dimensional)) it is object type
#################################################################################################################################
# Creating a 1-Dimensional array
print("#### Creating a 1-Dimensional array ####")
arr1Dimensional = np.array([1,2,3,4,5])
print(arr1Dimensional)
#print(type(arr1Dimensional)) it is object type
#################################################################################################################################
# Creating a 2-Dimentional array
print("#### Creating a 2-Dimensional array ####")
arr2Dimensional = np.array([[1,2,3],[4,5,6]])
print(arr2Dimensional)
#print(type(arr2Dimensional)) it is object type
#################################################################################################################################
# Creating a 3-Dimentional array
print("#### Creating a 3-Dimensional array ####")
arr3Dimensional = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(arr3Dimensional)
#print(type(arr3Dimensional)) it is object type
#################################################################################################################################
# Checking Number of dimensions
print("#### Checking Number of dimensions ####")
a = np.array(42)
b = np.array([1,2,3,4,5])
c = np.array([[1,2,3],[4,5,6]])
d = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
#################################################################################################################################
# Higher Dimensional Arrays
# An Array can have any number of dimensions.
# When the array is created, you can define the number of dimensions by using the "ndmin" argument.
#Creating an array with 5 dimensions and verify that it has 5 dimensions:
print("#### Creating an array with 5 dimensions and verify that it has 5 dimensions ####")
dimCheckArr = np.array([1,2,3,4,5],ndmin=5)
print(dimCheckArr)
print('Number of dimensions :',dimCheckArr.ndim)
#################################################################################################################################
###################### Numpy Array Indexing #################################
# Access Array Elements
# Array indexing is the same as accessing an array element.
# You can access an array element by referring to its index number.
# The indexes in Numpy arraysstarts with o, meaning that the first element has index 0, and the second has index 1 etc.
# Get the first element form the following array
print("#### Get the first element form the following array ####")
indArray = np.array([1,2,3,4,5])
print(indArray[0])
# Get the third and fourth elements from the following array and add them.
print("#### Get the third and fourth elements from the following array ####")
addArray = np.array([1,2,3,4,5])
print(addArray[2]+addArray[3])
##################### Access 2-D Arrays ##################
# Access the 2nd element on 1st dimensional
print("#### Accessing the 2nd element on 1st dimensional ####")
print('2nd element of the first dimension is',arr2Dimensional[0,1])
##################### Access 3-D Arrays ##################
# Access the third element of the second array of the first array:
print("#### Access the third element of the second array of the first array ####")
print('3rd element of the second array of the first array is',arr3Dimensional[0,1,2])
# Example Explained
# arr[0, 1, 2] prints the value 6.
# And this is why:
# The first number represents the first dimension, which contains two arrays:
# [[1, 2, 3], [4, 5, 6]]
# and:
# [[7, 8, 9], [10, 11, 12]]
# Since we selected 0, we are left with the first array:
# [[1, 2, 3], [4, 5, 6]]
# The second number represents the second dimension, which also contains two arrays:
# [1, 2, 3]
# and:
# [4, 5, 6]
# Since we selected 1, we are left with the second array:
# [4, 5, 6]
# The third number represents the third dimension, which contains three values:
# 4
# 5
# 6
# Since we selected 2, we end up with the third value:
# 6
#################################################################################################################################
###################### Negative Indexing #################################
# Negative inexing is used to access an array from the end
# Print the last element form the 2nd dimension:
print("#### Printing the last element form the 2nd dimension ####")
arr2Dimensional = np.array([[1,2,3],[4,5,6]])
print('using Positive indexing ',arr2Dimensional[1,2])
print('using Negative indexing ',arr2Dimensional[1,-1])
#################################################################################################################################
###################### NumPy Array Slicing #################################
# Slicing arrays
# Slicing in python means taking elements from one given index to another given index.
# We pass slice instead of index like this: [start:end].
# We can also define the step, like this: [start:end:step].
# If we don't pass start its considered 0
# If we don't pass end its considered length of array in that dimension
# If we don't pass step its considered 1
# Slice elements from index 1 to index 5 from the following array:
print("#### Slicing elements from index 1 to index 5 from the following array ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[1:5]) # Note: The result includes the start index, but excludes the end index.
# Slice elements from index 4 to the end of the array
print("#### Slicing elements from index 4 to the end of the array ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[4:])
# Slice elements from the beginning to index 4 (not included)
print("#### Slicing elements from the beginning to index 4 (not included) ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[:4])
###################### Negative Slicing #################################
# Slice from the index 3 from the end to index 1 from the end
print("#### Slicing from the index 3 from the end to index 1 from the end ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[-3:-1])
###################### Step #################################
# Use the step value to determine the step of the slicing:
# Return every other element from index 1 to index 5:
print("#### Returning every other element from index 1 to index 5 ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[1:5:2])
# Return every other element from the entire array
print("#### Returning every other element from the entire array ####")
arr1Dimensional = np.array([1,2,3,4,5,6,7])
print(arr1Dimensional[::2])
###################### Slicing 2-D Array #################################
# From the second element, slice elements from index 1 to index 4 (not included)
print("#### From the second element, slicing elements from index 1 to index 4 (not included) ####")
arr2Dimensional = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(arr2Dimensional[1,1:4])
# From both elements, return index 2
print("#### From both elements, returning index 2 ####")
arr2Dimensional = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(arr2Dimensional[0:2,2])
# From both elements, slice index 1 to index 4 (not included), this will return a 2-D array
print("#### From both elements, slicing index 1 to index 4 (not included), this will return a 2-D array ####")
arr2Dimensional = np.array([[1,2,3,4,5],[6,7,8,9,10]])
print(arr2Dimensional[0:2,1:4]) |
a607a903d29bf628fe0b7bef4f5ad077233efe5b | waiteb15/py3forsci3day | /date_delta.py | 570 | 3.953125 | 4 | #!/usr/bin/env python
import sys
from datetime import date, datetime, timedelta, time
#date = sys.argv[1]
#date = input("Enter date (YYYY-MM-DD):")
d1 = '1991-07-02'
#d1 = datetime.strptime(date, "%Y-%m-%d")
d2 = datetime.now().strftime("%Y-%m-%d")
def _days_between(d1, d2):
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
return abs((d2 - d1).days)
years = _days_between(d1,d2)//365.25
days = (_days_between(d1,d2) / 365.25 - years) * 365.25
print(f'{years:.0f} years and {days:.0f} days')
|
861694caeb29e5f89907a2950b7b67175cc2ec6a | alvxyz/PythonClass | /Belajar bersama Kelas Terbuka/Bilangan Prima dan belajar codesaya.py | 1,577 | 3.578125 | 4 |
# tentukan batas bilangan prima yang akan dicari
Angka = 100
#
# # perulangan untuk mengecek bilangan prima
# for num in range(2, Angka):
# prima = True
# for i in range(2, num):
# if (num % i == 0):
# prima = False
# if prima:
# print(num)
def hitung_tagihan(uang_muka):
harga_laptop = 7000
sisa_cicilan = harga_laptop - uang_muka
suku_bunga = 10 # dalam persen
jumlah_bunga = sisa_cicilan * suku_bunga / 100
total_tagihan = sisa_cicilan + jumlah_bunga
tagihan_bulanan = total_tagihan / 12
return tagihan_bulanan
print (hitung_tagihan(1000))
angka_minus = -3.14
angka_positif = abs(-3.14)
print (angka_minus)
print (angka_positif)
from random import randint
hitung_kepala = 0
hitung_total = 0
while True:
# angka integer acak: 0 atau 1
putar = randint(0, 1)
if putar:
hitung_kepala = hitung_kepala + 1
print
str(hitung_total) + " kepala " + str(hitung_kepala)
else:
hitung_kepala = 0
print
str(hitung_total) + " buntut"
hitung_total = hitung_total + 1
if not (hitung_kepala < 3 and hitung_total < 100):
break
print
"Muncul kepala " + str(hitung_kepala) + " kali berturut-turut."
# anda sudah bisa menggunakan for dengan range()
for i in range(1000, 1, -200):
print i
# sudah bisa juga untuk mencetak sebuah list
for p in [ 2, 3, 5, 7 ]:
print p
# termasuk mencetak string
for s in "string":
print s
# dictionary juga
dict = { 'nama' : 'saya', 'umur': 17 }
for d in dict:
print d + ": " + str(dict[d]) |
9972f8d198fe60acae7f422c47bae51aaf91ba22 | onetoofree/IT_Masters | /StuffFromLectures/SolutionsFromLabs/Lab3/PrefSuff.py | 843 | 4.3125 | 4 | #prefix/suffix testing
LongStr=input("Please enter a long string ")
ShortStr=input("Please enter a short string ")
longlen=len(LongStr)
shortlen=len(ShortStr)
if(shortlen>longlen):
print("String ",ShortStr," is neither a prefix nor a suffix of string ",LongStr)
else:
ispref=1
for i in range (0,shortlen):
if(ShortStr[i]!=LongStr[i]):
ispref=0
break
if (ispref==1):
print("String ",ShortStr," is a prefix of a string ",LongStr)
else:
print("String ",ShortStr," is not a prefix of a string ",LongStr)
issuff=1
for i in range (0,shortlen):
if(ShortStr[shortlen-1-i]!=LongStr[longlen-1-i]):
issuff=0
break
if (issuff==1):
print("String ",ShortStr," is a suffix of a string ",LongStr)
else:
print("String ",ShortStr," is not a suffix of a string ",LongStr)
|
eac0789333b9034bfd0f1990abcbc4264c8c434c | peltierchip/the_python_workbook_exercises | /chapter_2/exercise_57.py | 1,031 | 4 | 4 | ##
#Calculate the total cost of a cell phone plan
b_cost=15.00
c_mess_add=0.15
c_minu_add=0.25
c_911=0.44
tax=0.05
#Read the number of minutes and text messages used in this month
minutes=int(input("Enter the number of minutes used:\n"))
messages=int(input("Enter the number of messages used:\n"))
#Compute the total bill amount
t_bill_amount=b_cost+c_911
charge_minu_add=0.0
charge_mess_add=0.0
if minutes>50:
charge_minu_add=(minutes-50)*c_minu_add
t_bill_amount=t_bill_amount+charge_minu_add
if messages>50:
charge_mess_add=(messages-50)*c_mess_add
t_bill_amount=t_bill_amount+charge_mess_add
t_bill_amount_tax=t_bill_amount*tax
t_bill_amount=t_bill_amount+t_bill_amount_tax
#Display the result
print("The base charge is $%.2f .\nThe additional minutes charge is $%.2f.\
\nThe additional message charge is $%.2f.\nThe 911 fee is $%.2f .\
\nThe tax is $%.2f .\nThe total bill amount is $%.2f ."%(b_cost,charge_minu_add,
charge_mess_add,c_911,t_bill_amount_tax,t_bill_amount))
|
f22ede9fe55778c6e598641b5a153e1589afd399 | kanak8278/LeetCode-Practice | /Stacks and Queues/floodFill.py | 1,057 | 3.734375 | 4 | from collections import deque
from typing import List
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
q = deque()
visited = set()
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
q.append((sr, sc))
color = image[sr][sc]
image[sr][sc] = newColor
visited.add((sr, sc))
while q:
l = len(q)
for _ in range(l):
x, y = q.pop()
for dx, dy in dirs:
if x + dx in range(len(image)) and y + dy in range(len(image[0])) \
and image[x + dx][y + dy] == color and (x+dx, y+dy) not in visited:
q.append((x + dx, y + dy))
image[x + dx][y + dy] = newColor
visited.add((x+dx, y+dy))
return image
if __name__ == "__main__":
image = [[0, 0, 0], [0, 1, 1]]
sr, sc = 1, 1
newColor = 1
sol = Solution()
print(sol.floodFill(image, sr, sc, newColor))
|
358169c174ee0c23f4f1c4eaa3c26095d963a83a | WilliamRo/greedy_snake | /Section I/step_1.py | 703 | 4 | 4 | """
If you want to create a game based on whatever programming language, you must
decide where to show your user interface. It can be on terminal (sometimes
people call it 'command line window' or 'command shell') of course, yet a
window on which we can draw whatever shape with whatever color is definitely
more preferable. Here we go with a build-in package named 'tkinter' to create
such a window.
"""
import tkinter as tk
# This line create a tk root which is ready to be showed
root = tk.Tk()
# This line let the root show itself
root.mainloop()
"""
Now that you have created and showed a window using tk, it's time to change its
styles such as its size, start position and background color.
""" |
520055c5d6c0bc95fc1f91cb441e82b34d225d9e | GT-IEEE-Robotics/Simulator2020 | /simulator/legos.py | 3,651 | 3.84375 | 4 | """
File: legos.py
Author: Ammar Ratnani
Last Modified: Ammar on 11/26
"""
import pybullet as p
from typing import List, Tuple
import re
from simulator.utilities import Utilities
class Legos:
"""
A class to provide for the importing of legos.
Provides functions to import a list of legos and put them at desired
positions. Also allows specifying the colors. Will eventually provide
functionality to calculate the score based off the legos so we don't have
to do it manually.
"""
"""The height to spawn the blocks at"""
SPAWN_HEIGHT = .3
def __init__(self):
"""Creates an array of all the block ids to be populated.
Right now there isn't much of a need for internal state, but when we
start keeping track of score this may expand.
"""
self.block_ids : List[int] = []
def __str__(self) -> str:
"""Prints out instance variables."""
return "(" + str(self.block_ids) + ")"
def __repr__(self) -> str:
"""Returns `__str__` for easy debugging."""
return str(self)
def load_lego_urdfs(self, blocks: List[Tuple[float, float, str]]) -> None:
"""Loads the blocks specified in the list.
Takes in a list of x and y positions, as well as the rgb color to
make the blocks, and loads them upright into the play field. Also
does validation to make sure the blocks are in range, and throws an
exception if they are not.
:param blocks: a list of tuples of x, y, and rgb hex
:raises ValueError: if the x or y is out of range or hex is invalid
"""
for b in blocks:
# For readability
b_x = b[0]
b_y = b[1]
b_z = b[2]
# Check that the color is valid with regex
if re.match(r"#[0-9a-f]{6}", b[3]) == None:
raise ValueError("Must have valid rgb hex color")
# Compute its color
# We hard code the alpha as it must be exactly 0 or 1
# From stackoverflow.com/questions/29643352/converting-hex-to-rgb-value-in-python
b_color = [int(b[3].lstrip('#')[i:i+2], 16) / 256 for i in (0,2,4)] + [1]
# Check that it is valid
# Basic sanity check that it is in bin area for now
# if abs(b_x) >= .682625 \
# or abs(b_y) >= .5715 \
# or abs(b_y) <= .2667:
# raise ValueError("Center of lego block not in bin area")
# Load the block
b_id = p.loadURDF(
fileName = Utilities.gen_urdf_path("lego/lego.urdf"),
basePosition = [b_x, b_y, b_z],
globalScaling=0.9)
# Change its color with white specular
p.changeVisualShape(
objectUniqueId = b_id,
linkIndex = -1,
rgbaColor = b_color,
specularColor = [1,1,1])
# Change the collision properties so they stick
# Requires further testing
# p.changeDynamics(
# bodyUniqueId = b_id,
# linkIndex = -1,
# contactStiffness = 1e6, # Unknown units
# contactDamping = 1e5) # Unknown units
# Append the block id to the list we are maintaining
self.block_ids.append(b_id)
def step(self, robot_id, robot_link_id):
for lego_id in self.block_ids:
if len(p.getClosestPoints(robot_id, lego_id, 0.004, linkIndexA=robot_link_id)) > 0:
self.block_ids.remove(lego_id)
p.removeBody(lego_id)
|
56bad7dc91c35dd8c1ff0b2bb2b986f3b6534a9c | childe/leetcode | /merge-intervals/solution.py | 1,412 | 4 | 4 | # -*- coding: utf-8 -*-
'''
https://leetcode-cn.com/problems/merge-intervals/
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
'''
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
rst = [intervals[0]]
for (x,y) in intervals[1:]:
if x <= rst[-1][1]:
rst[-1] = [rst[-1][0], max(y,rst[-1][1])]
else:
rst.append([x,y])
return rst
def main():
s = Solution()
r = s.merge([[1, 3], [2, 6], [8, 10], [15, 18]])
a = [[1, 6], [8, 10], [15, 18]]
assert r == a
r = s.merge([[1, 4], [4, 5]])
a = [[1, 5]]
assert r == a
r = s.merge([[1, 4], [0, 4]])
a = [[0, 4]]
assert r == a
r = s.merge([[1, 4], [2, 3]])
a = [[1, 4]]
assert r == a
if __name__ == '__main__':
main()
|
3b550a112176c96da14e1642ec414d25b43c75e1 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/756.py | 1,443 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
# drop first line of stdin
sys.stdin.readline()
for test, line in enumerate(sys.stdin):
seq_raw = line.split()[1:]
seq = []
orange_queue = []
blue_queue = []
for i in range(0, len(seq_raw), 2):
color = seq_raw[i]
button = int(seq_raw[i+1])
seq.append((color, button))
if color == 'B':
blue_queue.append(button)
elif color == 'O':
orange_queue.append(button)
time = 0
next_button = None
next_blue = None
next_orange = None
pos_blue = 1
pos_orange = 1
while True:
if next_button is None:
try:
next_button = seq.pop(0)
except IndexError:
# no more buttons
break
if next_blue is None:
try:
next_blue = blue_queue.pop(0)
except IndexError:
pass
if next_orange is None:
try:
next_orange = orange_queue.pop(0)
except IndexError:
pass
# increment time
time += 1
# blue bot
if next_blue is not None:
if next_blue > pos_blue:
pos_blue += 1
elif next_blue < pos_blue:
pos_blue -= 1
else:
if next_button is not None and next_button[0] == 'B':
next_button = None
next_blue = None
# orange bot
if next_orange is not None:
if next_orange > pos_orange:
pos_orange += 1
elif next_orange < pos_orange:
pos_orange -= 1
else:
if next_button is not None and next_button[0] == 'O':
next_button = None
next_orange = None
print('Case #{}: {}'.format(test+1, time))
|
f7a0b345f3690cbbf2c63df111609331d20b7955 | jsqihui/lintcode | /Binary_Tree_Maximum_Path_Sum.py | 903 | 3.78125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxPathSum(self, root):
# write your code here
maxPath, _ = self.helper(root)
return maxPath
def helper(self, root):
if not root:
return -sys.maxint, 0
# divide
leftMax, leftSingle = self.helper(root.left)
rightMax, rightSingle = self.helper(root.right)
# conqure
# get a single max path from leaf to root
rootSingle = max(leftSingle, rightSingle) + root.val
rootSingle = max(rootSingle, 0)
rootMax = max(leftSingle + rightSingle + root.val, leftMax, rightMax)
return rootMax, rootSingle
|
659a8f43baa848318b6f8bd0a36ac35ddfbdf773 | rohitgupta29/Python_projects | /Data_Structures/5.Pig_latin.py | 246 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 16:54:36 2020
@author: infom
"""
def pig_latin(word):
if word[0] in 'aeiou':
return f'{word}way'
return f'{word[1:]}{word[0]}ay'
print(pig_latin('python'))
|
3e1d85091c17f642047403be6a6b7d5eb4e478ea | MehtapIsik/algebra | /tmp.py | 196 | 3.703125 | 4 | # Run example: python tmp.py 4 5
import sys
import algebra
print(sys.argv)
name = sys.argv[0]
num1 = float(sys.argv[1])
num2 = float(sys.argv[2])
print(algebra.operations.product(num1, num2))
|
dda71af28bf3c2406758f0eeea7bb8254f7d0546 | ohadsham/AI_HW_3 | /q1.py | 5,465 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from numpy import log2,inf
#general:
#each element represent as line of the file.
#all features have binary values (true or false)
# convert feature name to index in line
def featureToIndex(feature):
return attributes.index(feature)
def makeTree(examples,features,default):
if not examples :
return ([],[],default)
c = majorityClass(examples)
#features == ['classification'] means features list is empty
if c[1] or features == ['classification']:
return ([],[],c[0])
c = c[0]
f = selectFeature(features,examples) #f <- SelectFeature(Features, E)
F = features.copy()
F.remove(f) #F <- Features-{f}
f_index = featureToIndex(f)
# feature value can be 1 or 0. we create two sub trees. one with all the element with
#0 value second with all the element with 1 value
subtrees = ('0',makeTree([x for x in examples if x[f_index] =='0'],F,c)),('1',makeTree([x for x in examples if x[f_index] =='1'],F,c))
return (f,subtrees,c)
def selectFeature(features,examples):
if features[0] == 'classification':
return []
return minEntropyOfFeature(features,examples)
def classify(element,tree):
(feature,childrens,value) = tree
if childrens == []:
return value
v = element[featureToIndex(feature)]
if v == '0':
subtree = ((childrens[0])[1])
else:
subtree = ((childrens[1])[1])
return classify(element,subtree)
#return true if most of the elements are in the "true" class
#otherwise return false
# return value tuple: (majority class,isAllAgree)
#if all elements are in the same class then "isAllAgree" is true
def majorityClass(examples):
total_false = 0
total_true = 0
isAllAgree = False
classIndex = len(examples[0]) - 1
for element in examples:
if element[classIndex] == 'True':
total_true+=1
else:
total_false+=1
if total_true==0 or total_false==0:
isAllAgree=True
return (total_true>total_false,isAllAgree)
def entropy(examples):
total_false = 0
total_true = 0
if(not examples):
return 0
classIndex = len(examples[0])-1
for element in examples:
if element[classIndex] == 'True':
total_true+=1
else:
total_false+=1
total = total_false + total_true
true_entropy =total_true/total
false_entropy =total_false/total
if total_true==0:
return -1*(false_entropy)*log2((false_entropy))
if total_false==0:
return -1*(true_entropy)*log2((true_entropy))
return -1*(false_entropy)*log2((false_entropy))+ -1*(true_entropy)*log2((true_entropy))
#for a group of features and examples we iterate over the features and caculate for
#each feature the entropy of the two divide group. we return the feature with
#the minimum entropy. (=means the information gain is the largest)
def minEntropyOfFeature(features,examples):
f_min =-1
minEnt = inf
lLen = len(examples)
for f in features:
#end of features
if f == 'classification':
return f_min
f_index = featureToIndex(f)
f0_divide = [x for x in examples if x[f_index] =='0']
f1_divide = [x for x in examples if x[f_index] =='1']
current_entropy =(len(f0_divide)/lLen) *entropy(f0_divide)+(len(f1_divide)/lLen) *entropy(f1_divide)
if current_entropy < minEnt:
minEnt = current_entropy
f_min = f
return f_min
#returns successeful qualifications number
def hitRatio(tree,examples):
hitCounter = 0
for example in examples:
if str(classify(example,tree)) == example[len(example)-1]:
hitCounter+=1
return hitCounter
#calc average accuracy of 4fold examples
def calcAcc(examples):
total_acc = 0
fold_size = len(examples)/4
for x in range(4):
fold3 = examples[0:round(x*fold_size)]+examples[round((x+1)*fold_size):]
fold1 = examples[round(x*fold_size):round((x+1)*fold_size)]
tree = makeTree(fold3,attributes,True)
total_acc += hitRatio(tree,fold1)
return total_acc/len(examples)
#calc confuison matrix 4fold examples
def calcConfusionMatrix(examples):
fold_size = len(examples)/4
true_pos = 0
false_pos = 0
false_neg = 0
true_neg = 0
for x in range(4):
fold3 = examples[0:round(x*fold_size)]+examples[round((x+1)*fold_size):]
fold1 = examples[round(x*fold_size):round((x+1)*fold_size)]
tree = makeTree(fold3,attributes,True)
for example in fold1:
if str(classify(example,tree)) == example[len(example)-1]:
if example[len(example)-1] == 'True':
true_pos+=1
else:
true_neg+=1
else:
if example[len(example)-1] == 'False':
false_pos+=1
else:
false_neg+=1
print("[["+str(true_pos)+" "+str(false_pos)+"]")
print("[ "+str(false_neg)+" "+str(true_neg)+"]]")
def main():
file = open ('flare.csv')
examples = [[]]
for line in file:
line = line.strip("\r\n")
examples.append(line.split(','))
examples.remove([])
global attributes
attributes = examples[0]
examples.remove(attributes)
print(calcAcc(examples))
calcConfusionMatrix(examples)
file.close()
if __name__ == '__main__':
main() |
a087215bcd32db3a39af230e06bc74d088ca86d5 | Parizval/CodeWars | /Mexican Wave/Solution.py | 169 | 3.71875 | 4 | def wave(str):
ans = []
for i in range(len(str)):
if str[i] == " ": continue
ans.append(str[:i] + str[i].upper() + str[i+1:])
return ans |
2d4a1b0e038a4b915f3e223be468f46df390fc74 | mohit2494/gfg | /languages/python/Input_Output(done)/3. Taking multiple inputs from user in Python.py | 1,861 | 4.40625 | 4 | '''
Developer often wants a user to enter multiple values or inputs in one line.
In C++/C user can take multiple inputs in one line using scanf but in Python
user can take multiple values or inputs in one line by two methods.
- using the split() method
- using List Comprehension
'''
# using split method
'''
This function helps in getting a multiple inputs from
user . It breaks the given input by the specified separator.
If separator is not provided then any white space is a separator.
Generally, user use a split() method to split a Python string but
one can used it in taking multiple input.
'''
# syntax :
input().split(seperator, maxsplit)
# python program showing how to
# multiple input using split
# taking two inputs at a time
x, y = input("Enter 2 values").split()
# taking three inputs at a time
x, y, z = input("Enter 3 values").split()
# how to print the input value using
'''
str.format() is an improvement on %-formatting. It uses normal
function call syntax and is extensible through the __format__()
method on the object being converted to a string.
'''
# taking two inputs at a time and printing them
a, b = input('Enter 2 values : ').split()
print("First number is {} and second number is {}".format(a,b))
# taking multiple inputs at a time
# and typecasting using list function
# we are converting the input to string
# to help us manage input effectively
x = list(map(int,input('Enter multiple values : ').split()))
print('List of values',x)
# second way is using list comprehensions
# taking two inputs at a time
x,y = [int(x) for x in input('Enter your values').split()]
# similarly taking 3 inputs at a time
x, y, z = [int(x) for x in input('Enter your values').split()]
# taking multiple values at a time
x = [int(x) for x in input('Enter multiple values').split()]
print('values in list are :',x)
|
ea4b3432bb1e15b6b65a6114d62392be2830cf35 | Mehr2008/summer-of-qode | /Python/2021/Class 1/Student Code/Avie Lal/main.py | 192 | 3.765625 | 4 | Tea1 = input('Tea from shop one =\n')
Tea1 = int(Tea1)
Tea1 = Tea1*15
T2 = input('Tea from shop 2 =\n')
T2 = int(T2)
T2 = T2*30
Tea_total = Tea1 + T2;
print("Total bill =",Tea_total," Rupees") |
8ebb57ff4fa439ed1ad44b9617f6458ca8ecf64c | libinlovexin/web_project | /test/orderDict.py | 741 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
class lastUpdateOrderedDict(OrderedDict):
def __init__(self,max):
super(lastUpdateOrderedDict,self).__init__()
self._max = max
def __setitem__(self,key,value):
containsKey = 1 if key in self else 0
#假如超过长度,删除第一个进入的元素
if len(self) - containsKey >= self._max:
last = self.popitem(last =False)
print "remove:" , last
if containsKey:
del self[key]
print "set :" , (key , value)
else:
print "add : ", (key, value)
#调用夫类set方法
OrderedDict.__setitem__(self,key,value)
if __name__ == '__main__':
a = lastUpdateOrderedDict(2)
a["x"] = 1
a["z"] = 12
a["aa"] = 14
print a |
50eb449a51438b6154a6ae47b82990ac28023dfa | luizfernandosantoss/Curso-alura | /Python/Primeiro curso Python/forca.py | 4,525 | 3.671875 | 4 | import random
def jogar():
imprime_abertura();
palavra_secreta = escolher_palavra();
letras_acertadas = quantidade_letras(palavra_secreta);
enforcou = False
acertou = False
erros = 0;
chutes=[];
while (not enforcou and not acertou):
chute = pede_chute();
if (chute in palavra_secreta):
marca_chute_correto(chute,palavra_secreta,letras_acertadas);
else:
erros += 1
desenha_forca(erros);
guardar_chutes(chute,chutes);
enforcou = erros == 7;
acertou = not '_' in letras_acertadas;
print(letras_acertadas)
if(acertou):
imprime_mensagem_vencedor();
else:
imprime_mensagem_perdedor(palavra_secreta);
continuar_jogo();
def imprime_abertura():
print("*********************************")
print("***Bem vindo ao jogo da Forca!***")
print("*********************************")
def escolher_palavra():
arquivo = open("palavra.txt", "r");
palavra = [];
for linha in arquivo:
palavra.append(linha.strip())
numero = random.randrange(0, len(palavra));
arquivo.close();
return palavra[numero].upper();
def quantidade_letras(palavra):
return ['_' for letra in palavra]
def pede_chute():
chute = input("Qual letra? ")
return chute.strip().upper();
def marca_chute_correto(chute,palavra_secreta,letras_acertadas):
index = 0
for letra in palavra_secreta:
if (chute == letra):
letras_acertadas[index] = letra
index += 1
def guardar_chutes(chute,chutes):
if(chute in chutes):
print("Voce ja tentou essa letra {}".format(chutes))
else:
chutes.append(chute);
print("chutes efetuados {}".format(chutes))
def continuar_jogo():
print("Deseja continuar Jogandor ?");
decisao = int(input("1:Sim ou 2:N:"));
deseja_continuar = decisao == 1;
if(deseja_continuar):
jogar();
else:
print("Fim do jogo");
def desenha_forca(erros):
print(" _______ ")
print(" |/ | ")
if(erros == 1):
print(" | (_) ")
print(" | ")
print(" | ")
print(" | ")
if(erros == 2):
print(" | (_) ")
print(" | \ ")
print(" | ")
print(" | ")
if(erros == 3):
print(" | (_) ")
print(" | \| ")
print(" | ")
print(" | ")
if(erros == 4):
print(" | (_) ")
print(" | \|/ ")
print(" | ")
print(" | ")
if(erros == 5):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | ")
if(erros == 6):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if (erros == 7):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
def imprime_mensagem_vencedor():
print("Parabéns, você ganhou!")
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
def imprime_mensagem_perdedor(palavra_secreta):
print("Puxa, você foi enforcado!")
print("A palavra era {}".format(palavra_secreta))
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
if (__name__ == "__main__"):
jogar()
|
dc2f2ff8952f60e860e0fef387b25d42296cd2bd | SatoKeiju/AtCoder-Python3 | /ABC152/e.py | 370 | 3.671875 | 4 | # ACできてない!!
def main():
from fractions import gcd
n = int(input())
num_list = tuple(map(int, input().split()))
l = 1
for num in num_list:
l *= num // gcd(l, num)
answer = 0
for num in num_list:
answer += l // num
answer %= 10 ** 9 + 7
print(int(answer))
if __name__ == '__main__':
main()
|
b259aa8602eebb68764568615a94abe834c99ae3 | hminah0215/Baekjoon_step | /step1/2588.py | 308 | 3.546875 | 4 | # 세자리 수 곱하기 세자리 수 일때 단계별 계산값
a = int(input()) # 기본값
b = list(input()) # 곱할값을 list로 저장
c1 = a * int(b[2]) # a * 곱셈할 값의 일의자리 수
c2 = a * int(b[1])
c3 = a * int(b[0])
answer = (c1 + (c2*10) + (c3*100))
print(c1, c2, c3, answer)
|
4c3f222af60d3be0a3c20d3b62367063e796eab2 | HeydarO/Python-Crash-Course- | /Chapter4_Working with Lists/square.py | 609 | 4.1875 | 4 | #finding square of the each number between 1 and 10 using list() and range() functions
squares = []
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
#improving code and get the same result as above:
squares = []
for value in range(1,11):
squares.append(value ** 2)
print(squares)
#improving code even more using list comprehensions and getting the same results:
squares = [value ** 2 for value in range(1,11)]
print(squares)
#simple math operations with Python:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
|
185ced4c8e270f5f1d39909e04103c215dcf35c0 | AkylbekMelisov/classes | /week4/day3/classes_task1.py | 3,164 | 3.859375 | 4 | class Car:
wheels = 4
def __init__(self, name, year, color, model, is_crashed):
self.name = name
self.year = year
self.color = color
self.model = model
self.is_crashed = is_crashed
self.fuel = 100
self.run = 0
self.speed = 0
self.V = 20
self.position = 0
# print(f"{self.name} created!")
def drive_to(self, city, km):
result = self.V / 100
result = result * km
if result < self.fuel:
self.fuel -= result
if self.fuel >= 0:
print(f"{self.name} drive to {city}")
else:
print('Road so far...')
def charge(self):
if self.fuel < 20:
self.fuel = 100
def crash(self, another_car):
if self.position == another_car.position:
self.is_crashed = True
another_car.is_crashed = True
print(f"{self.name} and {another_car.name} were crash!!!")
class Human:
def __init__(self, ful_name, age, heigth, weigth, nation):
self.ful_name = ful_name
self.age = age
self.heigth = heigth
self.weigth = weigth
self.nation = nation
self.position = 0
self.health = 100
self.is_live = True
def move(self):
self.position += 1
def accident(self, car, trafficligt):
if car.position == self.position and trafficligt.green:
if self.health > 40:
car.is_crashed = True
if 5 < car.speed < 20:
self.health -= 20
elif car.speed > 20:
self.health -= 40
else:
self.health = 0
self.is_live = False
print(f"{self.ful_name} попал в аварию, его сбила {car.name}, осталось здоровья {self.health}")
class Trafficlight:
def __init__(self):
self.red = False
self.yellow = False
self.green = False
def set_color(self, color: int):
if color % 2 == 1:
self.red = True
self.yellow = False
self.green = False
elif color == 'yellow':
self.yellow = True
self.red = False
self.green = False
elif color % 2 == 0:
self.green = True
self.red = False
self.yellow = False
audi = Car(name='AUDI', year=2021, color='grey', model='RX 8', is_crashed=False)
bmv = Car(name='BMV', year=2020, color='red', model='X 5', is_crashed=False)
honda = Car(name='HONDA', year=2020, color='red', model='X 5', is_crashed=False)
bmv.speed = 50
human1 = Human(ful_name='Bob', age=25, heigth=185, weigth=85, nation='france')
traffic_light = Trafficlight()
# print(traffic_light.red,traffic_light.yellow,traffic_light.green)
for i in range(1, 10):
if human1.health > 0:
traffic_light.set_color(i)
human1.accident(bmv, traffic_light)
# audi.drive_to('Los-Angeles',1000)
print(bmv.is_crashed)
print('Здоровье человека: ', human1.health, '\n', 'Жив ли человек: ', human1.is_live)
|
239e404666f128301d0634fa5b8e238b7ef58fb4 | zhengxiaochen/cognitivetwins | /transDomin.py | 540 | 3.71875 | 4 | # 转换数据维度
import pandas
table = pandas.DataFrame()
for i in range(max(input_table['Iteration'])+1):
#input_table_1.loc[input_table_1['Iteration']==i]
#input_table_2.loc[input_table_2['Iteration']==i]
print(i)
if i == 0:
table = pandas.DataFrame(columns = [str(i)], data = input_table.loc[input_table['Iteration']==i]['value'].values)
#print(table)
else:
table[str(i)] = pandas.DataFrame(columns = [str(i)], data = input_table.loc[input_table['Iteration']==i]['value'].values)
output_table = table
|
e1afa698123d5c7ca1b804bb347baa7108342de7 | syurskyi/Python_Topics | /045_functions/005_decorators/_exercises/_templates/2/019_A Few Real World Examples_Timing Functions.py | 1,022 | 3.65625 | 4 | # _____ fun___
# _____ ti__
#
# ___ timer func
# """Print the runtime of the decorated function"""
# ??.? ?
# ___ wrapper_timer $ $$
# start_time _ ti__.p00_cou00 # 1
# value _ ? $ $$
# end_time _ ti__.p00_cou00__ # 2
# run_time _ e... - s... # 3
# print _*Finished |?. -n!r| in |r00_t00:.4f| secs # look formating
# r_ ?
# r_ ??
#
# ??
# ___ waste_some_time num_times
# ___ _ i_ ra.. ? # the first _ is original
# su_||i**2 ___ i __ ra.. 10000
#
# # This decorator works by storing the time just before the function starts running (at the line marked # 1)
# # and just after the function finishes (at # 2). The time the function takes is then the difference between the two
# # (at # 3). We use the time.perf_counter() function, which does a good job of measuring time intervals.
# # Here are some examples of timings:
#
# ? 1
# # Finished 'waste_some_time' in 0.0010 secs
#
# ? 999
# # Finished 'waste_some_time' in 0.3260 secs |
ac87736b1e98b46d9f20ee7925c0416f1bcaebd8 | David970804/CSCI2040Python | /LAB2code/test_scripts/p1.py | 966 | 3.75 | 4 | units=['I','V']
tens=['X','L']
hundreds=['C','D']
thousands=['M']
digit=[units,tens,hundreds,thousands]
def roman_number(n):
num_of_digits=0
n_digits = []
roman_num=""
if n<=0 or n>9999:
return 'Number is out of range'
while n>0:
n_digits.append(n%10)
n = n//10
#for each digit of a number, the conversion logic is the same
#split four different cases: <4 =4 <9 =9
#and create the list "digit" to store sequentially the corresponding
#roman number digit representation so that it is easier to refer to in this for loop
for i in range(len(n_digits)):
if i < 3:
if n_digits[i]<4:
roman_num = n_digits[i]*digit[i][0] + roman_num
elif n_digits[i]==4:
roman_num = digit[i][0]+digit[i][1]+roman_num
elif n_digits[i]<9:
roman_num = digit[i][1]+(n_digits[i]-5)*digit[i][0]+roman_num
elif n_digits[i]==9:
roman_num = digit[i][0]+digit[i+1][0]+roman_num
else:
roman_num = digit[i][0]*n_digits[i] + roman_num
return roman_num
|
0cfe54474368433890f7a5edcbb0ee2d1356e037 | shaswat-99/tathastu_week_of_code | /Day1/Program4.py | 288 | 3.953125 | 4 | #Program 4 of Tathastu-Week of Code by shaswat-99
cp=float(input("Enter Cost Price of the Product "))
sp=float(input("Enter Selling Price of the Product "))
profit=sp-cp
print(f"Profit= {profit}")
new_sp=1.05*profit+cp
print(f" Selling Price after 5% extra profit on product = {new_sp}")
|
957e19fd197b2c184cc8d42b211d25c79dc0115b | zl1fly/note-taker | /notetaker.py | 940 | 3.71875 | 4 | #!/usr/bin/python
import time
import os
## Declared vars.
## This is the file it writes the notes to.
filename = "logfile.txt"
## This a the loop var which will keep the loop going
loop = 1
## Enter the loop and continue until loop != 1
while (loop == 1):
## Clear the Screen and prompt to enter there text
os.system('clear')
str = raw_input("Enter your note QUIT to quit: ")
## If the input was QUIT then set the loop var to 0
if (str == "QUIT"):
loop = 0
else:
## Otherwise pull the current date and build the log string to be written
## to the file
datestamp = time.asctime( time.localtime( time.time( ) ) )
logstring = datestamp + "\n===\n" + str+ "\n\n"
## Open and write string to the file and close the file this will ensure that
## any writes are not lost should the script be killed unnaturally
logfile = open(filename, "a+")
logfile.write(logstring )
logfile.close()
|
3286cbc3754d3c1c3705e0282ffa3032dde4a8e7 | webturing/PythonProgramming_20DS123 | /lec08-function/Primer.py | 356 | 3.875 | 4 | def is_prime(n):
if n < 2: return False # patch
for i in range(2, n):
if n % i == 0:
return False
return True
print(True == is_prime(13))
print(False == is_prime(25))
print(False == is_prime(9))
print(True == is_prime(2))
print(False == is_prime(1))
for n in range(1, 100):
if is_prime(n):
print(n, end=' ')
|
9802967b3b939d8d9c5aca5271f7952c900db206 | bl0rch1d/cs50_hw | /python/bleep/bleep.py | 740 | 3.703125 | 4 | import sys
def parse_dictionary(filename):
result = []
with open(filename, mode='r') as f:
for word in f:
result.append(word.strip())
return result
def main():
if len(sys.argv) != 2:
print('Usage: python bleep.py dictionary')
exit(1)
dictionary = parse_dictionary(sys.argv[1])
text = str(input('What message would you like to censor?\n'))
for word in dictionary:
replace_with = len(word) * '*'
if word in text:
text = text.replace(word, replace_with)
elif word.upper() in text:
text = text.replace(word.upper(), replace_with)
print(text)
if __name__ == "__main__":
main()
|
d309ca15942fcb464c186b67789fce3b4f4854cf | Dmitry314/lingustic | /untitled1.py | 843 | 3.609375 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 20:51:05 2018
@author: dmitriy
"""
import numpy as np
def get_one_text(my_file):
with open(my_file) as f:
read_data = f.read()
return read_data
def get_dict():
data = get_one_text('ozgegov/oz/ozgegov.txt')
res = data.split(" ")
words = []
for i in range(0, len(res)):
if(res[i].decode('utf-8').isupper() and len(res[i]) > 2):
words.append(i)
my_dict = {}
for i in range(len(words) - 1):
key_word = []
for j in res[words[i]]:
if(j != '' and j != '\n' and j != ','):
key_word.append(j)
key_word = "".join(key_word)
my_dict[key_word] = " ".join(res[words[i] + 1 : words[i + 1]] )
|
83803d1105fc15b8e81d525c8541b272b2c01d21 | manunapo/blackjack-game | /classes/deck.py | 553 | 3.875 | 4 | import random
from classes.card import Card
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
self.all_cards.append(Card(suit,rank))
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
if len(self.all_cards) > 0:
return self.all_cards.pop()
else:
print("There is no more Cards to deal. Game ended")
|
9d9600fedff52553c50535d3c9769d71055ddfb0 | pradoz/leetcode_pset | /py/remove_outer_parenthesis.py | 1,254 | 3.765625 | 4 | '''
ex1:
Input: "(()())(())"
Output: "()()()"
ex2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
ex3:
Input: "()()"
Output: ""
'''
# Time/Space: O(n), where n is the number of parenthesis is the string 'parens'
class Solution:
def removeOuterParentheses(self, parens: str) -> str:
res = ''
prev = 0
count = 0
for i, s in enumerate(parens):
if s == '(': # we have an open bracket
count += 1 # increment count by one
else:
count -= 1 # if we have another closing bracket, subtract one
# print(res)
if count == 0: # if we opened and closed: i.e. '(' then ')'
res += parens[prev + 1: i] # append the valid sequence to res
# print(f'(i:{i}, s:\'{s}\') ==> res:{res}')
prev = i + 1 # track next place for input in res
return res
s1 = Solution()
# print(s1.removeOuterParentheses("(()())(())"))
print(s1.removeOuterParentheses("(()())(())(()(()))"))
# print(s1.removeOuterParentheses("()()"))
# assert s1.removeOuterParentheses("(()())(())") == "()()()"
# assert s1.removeOuterParentheses("(()())(())(()(()))") == "()()()()(())"
# assert s1.removeOuterParentheses("()()") == ""
|
affa0aa8edb7f2cd5f122766c1549e397d2d3967 | jbrownxf/mycode | /mycal/mycal.py | 259 | 4.25 | 4 | #!/usr/bin/python
import calendar
yr = input('What year is it? ')
lilcal = calendar.calendar(yr)
print("Here is a tiny calendar:")
print(lilcal)
if calendar.isleap(yr) == False:
print('This is not a leap year')
else:
print('This year is a leap year')
|
6b96d16f00b428ec0fb2c44155d7b84141995c1f | monikatrznadel/nauka_pythona | /zadanie13.py | 189 | 3.671875 | 4 | Print('Zadanie 13')
ranking = {'name': 'Player1', 'pkt': '10', 'kat': 'junior'}
print(ranking['name'])
print(ranking['kat'])
for i in ranking:
print("{0}:{1}".format(i, ranking[i]))
|
368d0a5f6b6f5f984b3b3ad4b2bfa0acb8846c54 | tuxedocat/nlp100 | /src/p06.py | 627 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""nlp100 in python3"""
__author__ = "Yu Sawai (tuxedocat@github.com)"
__copyright__ = "Copyright 2015, tuxedocat"
__credits__ = ["Naoaki Okazaki", "Inui-Okazaki Lab. at Tohoku University"]
__license__ = "MIT"
from common.ngram import ngram
if __name__ == '__main__':
s1 = "paraparaparadise"
s2 = "paragraph"
X = set(ngram([c for c in s1], 2))
Y = set(ngram([c for c in s2], 2))
print("Union", X.union(Y))
print("Intersection", X.intersection(Y))
print("Difference", X.difference(Y))
se = ('s', 'e')
if se in X:
print("s e is in X")
if se in Y:
print("s e is in Y")
|
209f9f540de3b07951bea2c3ff03a1de710da192 | adamburford/COP4533 | /COP4533/Assignment 3/quick_string_list.py | 1,139 | 3.6875 | 4 | #Adam Burford
#COP4533
#Section 3594
class QuickStringList():
"""Quick String List"""
def __init__(self):
self.__list = []
def __iter__(self):
return iter(self.__list)
def __getitem__(self, key):
return self.__list[key]
def __setitem__(self, key, value):
self.__list[key] = value
def __str__(self):
return str(self.__list)
def __len__(self):
return len(self.__list)
def add(self, value):
self.__list.append(value)
def sort(self):
__quick_sort__(self.__list, 0 , len(self.__list) - 1)
def __quick_sort__(list, low, high):
if low < high:
pivot = __partition__(list, low, high)
__quick_sort__(list, low, pivot - 1)
__quick_sort__(list, pivot + 1, high)
def __partition__(list, low, high):
i = low
pivot = list[high]
for x in range(low , high):
if list[x] < pivot:
t = list[x]
list[x] = list[i]
list[i] = t
i += 1
t = list[high]
list[high] = list[i]
list[i] = t
return i
|
317826bf0f6e8fff46a982e8f6c9b0510197cc01 | shaoda06/python_work | /Part_I_Basics/exercises/exercise_3_9_dinner_guests.py | 436 | 4.0625 | 4 | # 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4
# through 3-7 (page 46), use len() to print a message indicating the number
# of people you are inviting to dinner.
names = ['MrrNonsense', 'Tony', 'Tom']
msg = " Would u like to have dinner with me?"
print("Hello, " + names[0] + msg)
print("Hello, " + names[1] + msg)
print("Hello, " + names[2] + msg)
print("I have " + str(len(names)) + " guests in total")
|
0f21e9badc5dd561641125bf4f16d0fc30aba9c0 | junyeong-dev/python3-class_arguments | /class-method.py | 1,340 | 3.53125 | 4 | class Car():
def __init__(self, **kwargs):
self.wheels = 4
self.doors = 4
self.windows = 4
self.seats = 4
# get("k", "d") : k는 key, d는 default를 가리킴
self.color = kwargs.get("color", "black")
self.price = kwargs.get("price", "2000")
# method는 class안에 있는 function을 말함
# method의 첫번째 argument는 method를 호출하는 instance 자기 자신 - 정해져있는 규칙
def carMethod(self):
print("method")
# __str__ : 호출될 때마다 class의 instance를 출력
# 기본적은 내장 method인 __str__을 override
def __str__(self):
return "__str__ override"
# inherit(상속)
class Convertible(Car):
def __init__(self, **kwargs):
# super() : 부모 class를 호출함
# 부모의 init을 호출함으로써 부모의 init과 자식만의 init을 둘다 가지게 됨
super().__init__(**kwargs)
self.time = kwargs.get("time", 10)
def take_off(self):
return "take off"
porche = Car(color = "blue", price = "5000")
porche.carMethod()
# dir : class안에 있는 모든 properties를 보여줌
print(dir(Car))
print(porche.__str__())
print(porche.color, porche.price)
benz = Car()
print(benz.color, benz.price)
bmw = Convertible()
print(bmw.take_off()) |
9f1c4e750b33b2b0b39fc799c68fb642630992de | ZainebPenwala/leetcode-solutions | /replace_ip.py | 725 | 3.796875 | 4 | '''Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" '''
# Solution 1: without using .replace()
class Defang:
def defang(self, ip):
ans = ''
for x in ip:
if x == '.':
x = '[' + '.' +']'
ans +=x
return ans
obj = Defang()
obj.defang('1.1.1.1')
# Solution 2:using .replace()
class Replace:
def replace(self, ip):
r = ip.replace('.', '[.]')
return r
obj = Replace()
obj.replace('1.1.1.1')
|
547d5c35d834f744caf887cd9cc7e3b0f983f905 | Algorant/HackerRank | /Python/zeros_and_ones/zeros.py | 353 | 4.09375 | 4 | '''
Given the shape of an array in the form of space separated integers, use numpy
functions zeros and ones to print an array of the given shape
'''
import numpy as np
dimensions = tuple(map(int, (input().strip().split()))
zeros = np.zeros(dimensions, dtype=np.int)
ones = np.ones(dimensions, dtype=np.int)
print(zeroes)
print(ones)
|
196f303f8502966785cf4a48b7279b01b4e80862 | YJISCOOL/if_condition | /if_condition-temperature.py | 316 | 4.03125 | 4 | temp_unit = input("what is the unit(\'C/\'F): ")
temp = int(input("what is the temperature now? "))
if temp_unit == "\'C":
temp_F = str(temp * 1.8 + 32)
print (temp, temp_unit + ' is equal to ' + temp_F + '\'F')
else:
temp_C = str((temp - 32) * (5/9))
print (temp, temp_unit + ' is equal to ' + temp_C + '\'C') |
6411ebe2b56fa80f00b95effc637d3443d0fd1bd | jyotsanashyama/python-basics | /diwali_discount.py | 593 | 4.125 | 4 | purchase_amt=int(input("Enter the purchase amount(in Rs.):"))
if purchase_amt<=400:
discount=0
elif purchase_amt<=5000 and purchase_amt>400:
discount=400
elif purchase_amt>5000 and purchase_amt<=10000:
discount=800
elif purchase_amt>10000 and purchase_amt<=20000:
discount=1000
else:
discount=2000
amt_after_discount=(purchase_amt-discount)
additional_discount=(3/100)*amt_after_discount
discount=discount+additional_discount
net_amt=purchase_amt-discount
print("The discount is Rs.",discount,"and the net amount after discount is Rs.",net_amt) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.