blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
aea7836f08d592b045334c13180b01d41acd9d90 | Randle9000/pythonCheatSheet | /pythonCourseEu/1Basics/24OOPrograming/Ex1.py | 249 | 3.65625 | 4 | #In fact, everything is a class in Python.
x = 42
print(type(x))
#---------------------------------
class Robot:
pass
if __name__ == "__main__":
x = Robot()
y = Robot()
y2 = y
print(y == y2)
print(y == x) |
f8137076318aa192f55f0334f29d325505cdba17 | wegesdal/udacity-ml | /Supervised_Learning/linear_regression3.py | 957 | 3.96875 | 4 | # Add import statements
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import numpy as np
import pandas
# Assign the data to predictor and outcome variables
# Load the data
train_data = pandas.read_csv('data2.csv')
X = np.reshape([train_data['Var_X']], (20, 1))
y = train_data['Var_Y']
print(X)
print(X.shape)
# Create polynomial features
# Create a PolynomialFeatures object, then fit and transform the
# predictor feature
poly_feat = PolynomialFeatures(degree = 3)
X_poly = poly_feat.fit_transform(X)
# Make and fit the polynomial regression model
# Create a LinearRegression object and fit it to the polynomial predictor
# features
poly_model = LinearRegression()
poly_model.fit(X_poly, y)
# Once you've completed all of the steps, select Test Run to see your model
# predictions against the data, or select Submit Answer to check if the degree
# of the polynomial features is the same as ours! |
705c5c0bc4e22b1b334bf6891dad00b8bf60c3fb | DidiMilikina/DataCamp | /Data Scientist with Python - Career Track /25. Introduction to Deep Learning in Python/03. Building deep learning models with keras/03. Fitting the model.py | 958 | 4.21875 | 4 | '''
Fitting the model
You're at the most fun part. You'll now fit the model. Recall that the data to be used as predictive features is loaded in a NumPy matrix called predictors and the data to be predicted is stored in a NumPy matrix called target. Your model is pre-written and it has been compiled with the code from the previous exercise.
Instructions
100 XP
Fit the model. Remember that the first argument is the predictive features (predictors), and the data to be predicted (target) is the second argument.
'''
SOLUTION
# Import necessary modules
import keras
from keras.layers import Dense
from keras.models import Sequential
# Specify the model
n_cols = predictors.shape[1]
model = Sequential()
model.add(Dense(50, activation='relu', input_shape = (n_cols,)))
model.add(Dense(32, activation='relu'))
model.add(Dense(1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Fit the model
model.fit(predictors, target)
|
af4d6fb2b148eb3c94a1e83d6de949dd27e54d03 | Ethan-Hill/Ember-Dragon | /Map.py | 7,129 | 3.65625 | 4 | import inquirer
import os
import SamTheSmith
import Village
import Cave
import End
from termcolor import colored
xLimit = 10
yLimit = 10
xPos = 1
yPos = 1
SamVisited = False
PeterVisited = False
CaveVisited = False
EndVisited = False
VillagePeopleX = 1
VillagePeopleY = 3
SamTheSmithX = 1
SamTheSmithY = 6
CaveX = 7
CaveY = 3
EndX = 1
EndY = 3
def clear():
# Clears the terminal at the start
os.system("c")
# user input function for taking commands from the user
def userInput():
global yPos
global xPos
global yLimit
global xLimit
# takes input from the user and forwards it on through a parameter
command = input("What would you like to do? ")
if "walk" in command:
getDirection(command)
elif "help" in command:
help()
elif "hint" in command:
hint()
else:
print("Unknown command, Please Try Again.")
userInput()
# finds out which direction the user wants to travel
def getDirection(command):
if "north" in command:
walkNorth()
elif "east" in command:
walkEast()
elif "south" in command:
walkSouth()
elif "west" in command:
walkWest()
else:
print("Unknown Direction, Please Try Again. ")
userInput()
def help():
print(colored('HELP', 'yellow'))
print(colored('CONTROLS', 'green'))
print(colored('Movement -', 'yellow'))
print(colored('Walk north: "walk north"', 'yellow'))
print(colored('Walk east: "walk east"', 'yellow'))
print(colored('Walk south: "walk south"', 'yellow'))
print(colored('Walk west: "walk west"', 'yellow'))
print(colored('HINTS', 'green'))
print(colored('Hint: "hint"', 'yellow'))
userInput()
def hint():
print(colored('HINT', 'yellow'))
if PeterVisited == False:
print(colored('Find Peter at 1, 3', 'yellow'))
elif PeterVisited == True and SamTheSmith == False and CaveVisited == False and EndVisited == False:
print(colored('Find Sam at 1, 6', 'yellow'))
elif PeterVisited == True and SamTheSmith == True and CaveVisited == False and EndVisited == False:
print(colored('Find the cave at 7, 3', 'yellow'))
elif PeterVisited == True and SamTheSmith == True and CaveVisited == True and EndVisited == False:
print(colored('Find the end at 1, 3', 'yellow'))
userInput()
# Walks in a direction
def walkNorth():
global yPos
global xPos
global PeterVisited
global SamVisited
global CaveVisited
global EndVisited
if yPos < 10:
print("You Walk North...")
yPos += 1
if xPos == VillagePeopleX and yPos == VillagePeopleY and SamVisited == False and CaveVisited == False and EndVisited == False:
Village.Start()
PeterVisited = True
if xPos == SamTheSmithX and yPos == SamTheSmithY and PeterVisited == True and CaveVisited == False and SamVisited == False and EndVisited == False:
SamTheSmith.Start()
SamVisited = True
if xPos == CaveX and yPos == CaveY and PeterVisited == True and CaveVisited == False and SamVisited == True and EndVisited == False:
Cave.Start()
CaveVisited = True
if xPos == EndX and yPos == EndY and PeterVisited == True and CaveVisited == True and SamVisited == True and EndVisited == False:
End.Start()
EndVisited = True
printCoords()
userInput()
else:
print("You Feel You Have Strayed Too Far, And Turn Back.")
userInput()
def walkEast():
global xPos
global xPos
global PeterVisited
global SamVisited
global CaveVisited
global EndVisited
if xPos < 10:
print("You Walk East...")
xPos += 1
if xPos == VillagePeopleX and yPos == VillagePeopleY and SamVisited == False and CaveVisited == False and EndVisited == False:
Village.Start()
PeterVisited = True
if xPos == SamTheSmithX and yPos == SamTheSmithY and PeterVisited == True and CaveVisited == False and SamVisited == False and EndVisited == False:
SamTheSmith.Start()
SamVisited = True
if xPos == CaveX and yPos == CaveY and PeterVisited == True and CaveVisited == False and SamVisited == True and EndVisited == False:
Cave.Start()
CaveVisited = True
if xPos == EndX and yPos == EndY and PeterVisited == True and CaveVisited == True and SamVisited == True and EndVisited == False:
End.Start()
EndVisited = True
printCoords()
userInput()
else:
print("You Feel You Have Strayed Too Far, And Turn Back.")
userInput()
def walkSouth():
global yPos
global xPos
global PeterVisited
global SamVisited
global CaveVisited
global EndVisited
if yPos > 1:
print("You Walk South...")
yPos -= 1
if xPos == VillagePeopleX and yPos == VillagePeopleY and SamVisited == False and CaveVisited == False and EndVisited == False:
Village.Start()
PeterVisited = True
if xPos == SamTheSmithX and yPos == SamTheSmithY and PeterVisited == True and CaveVisited == False and SamVisited == False and EndVisited == False:
SamTheSmith.Start()
SamVisited = True
if xPos == CaveX and yPos == CaveY and PeterVisited == True and CaveVisited == False and SamVisited == True and EndVisited == False:
Cave.Start()
CaveVisited = True
if xPos == EndX and yPos == EndY and PeterVisited == True and CaveVisited == True and SamVisited == True and EndVisited == False:
End.Start()
EndVisited = True
printCoords()
userInput()
else:
print("You Feel You Have Strayed Too Far, And Turn Back.")
userInput()
def walkWest():
global xPos
global xPos
global PeterVisited
global SamVisited
global CaveVisited
global EndVisited
if xPos > 1:
print("You Walk West...")
xPos -= 1
if xPos == VillagePeopleX and yPos == VillagePeopleY and SamVisited == False and CaveVisited == False and EndVisited == False:
Village.Start()
PeterVisited = True
if xPos == SamTheSmithX and yPos == SamTheSmithY and PeterVisited == True and CaveVisited == False and SamVisited == False and EndVisited == False:
SamTheSmith.Start()
SamVisited = True
if xPos == CaveX and yPos == CaveY and PeterVisited == True and CaveVisited == False and SamVisited == True and EndVisited == False:
Cave.Start()
CaveVisited = True
if xPos == EndX and yPos == EndY and PeterVisited == True and CaveVisited == True and SamVisited == True and EndVisited == False:
End.Start()
EndVisited = True
printCoords()
userInput()
else:
print("You Feel You Have Strayed Too Far, And Turn Back.")
userInput()
def printCoords():
print("Current Position: X=" + str(xPos) + ", Y=" + str(yPos))
if __name__ == "__main__":
userInput()
|
a6a465ef4de0e0663590011fa6ab507ca502429d | shagunattri/PythonScripts | /python/solves/D6/1_0.py | 697 | 3.765625 | 4 | # Check password
def is_low(x):
for i in x:
if 'a'<=i and i<='z':
return True
return False
def is_up(x):
for i in x:
if 'A'<=i and i<='Z':
return True
return False
def is_num(x):
for i in x:
if '0'<=i and i<='9':
return True
return False
def is_other(x):
for i in x:
if i=='$' or i=='#' or i=='@':
return True
return False
s = input().split(',')
lst = []
for i in s:
length = len(i)
if 6<= length and length <=12 and is_low(i) and is_up(i) and is_num(i) and is_other(i):
lst.append(i)
print(','.join(lst))
|
7e517a0e0dc0b9995dbc988be0d2d539c3f3a33e | ekarlekar/MyPythonHW | /0fibbonaccirecursion.py | 244 | 3.9375 | 4 | def fib(n):
if (n==1):
return (1)
elif (n==0):
return (0)
else:
return (fib (n-1)+ fib(n-2))
n=int(raw_input("Type in a number:"))
y=0
x=0
while x<=n:
x= fib(y)
if (x<=n):
print(x)
y=y+1
|
5b9e965e0424f80b13d54f4cf0523204fb5fa8bc | ricardoBpinheiro/PythonExercises | /Projetos/projeto1.py | 652 | 3.671875 | 4 | # Seu script deve gerar um valor aleatório entre 1 e 6(ou uma faixa que você definir)
# e permitir que o usuário rode o script quantas vezes quiser.
import random
import time
resposta = str(input('Você gosta de jogar dados? '))
c = 'SIM'
while c == 'SIM':
if resposta in 'simsSimSIM':
print('Rodando o dado!')
time.sleep(1)
print(random.randint(1, 6))
c = str(input('Quer continuar jogando?[sim/não] ')).upper()
if c == 'NÃO':
print('Blz, vaza daqui então ;-;')
exit()
else:
print('Blz, vaza daqui então ;-;')
exit()
print('Blz, vaza daqui então ;-;')
|
cb641f455c8ed32c5894dbe0f7227ed5ce9c6f46 | b1ueskydragon/PythonGround | /dailyOne/P276/trie.py | 868 | 3.59375 | 4 | class Node:
def __init__(self, char='*'):
self.char = char
self.children = {} # {char : Node}
self.index = 0
self.word_end = False
def cons(root: Node, word: str):
curr = root
for char in word:
for node in curr.children.values():
if node.char == char:
node.index += 1
curr = node
break
else:
new_node = Node(char)
curr.children[char] = new_node
curr = new_node
curr.word_end = True
def retrieval(word, patt):
"""
less than O(N * k) worst time.
:param word: string
:param patt: pattern
:return: Start index if pattern found, else False.
"""
return False
some_trie = Node()
cons(some_trie, "retrieval")
retrieval("retrieval", "trie") # 2
retrieval("retrieval", "e") # 1
|
559572af9370c5801278858835de5e7d5c02efc2 | cwallaceh/Python-Exercises | /flatten_tree_to_linked_list.py | 2,121 | 4.15625 | 4 | # Flatten a binary tree into linked list
# Given a binary tree, flatten it into a linked list.
# After flattening, the left of each node should point to
# NULL and right should contain next node in level order.
class BinaryTree():
def __init__(self):
self.left = None
self.right = None
self.data = None
def __repr__(self):
return "BinaryNode(%s)" % str(self.data)
class Stack():
def __init__(self):
self.stack = []
self.idx = 0
def push(self, val):
self.stack.append(val)
self.idx += 1
def pop(self):
val = self.stack[self.idx - 1]
del self.stack[self.idx - 1]
self.idx -= 1
return val
def __repr__(self):
return "Stack(%s)" % str(self.stack)
class Link:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return "%s→%s" % (self.value, self.next)
class LinkedList():
def __init__(self, value):
self.first = Link(value)
self.current = self.first
def __repr__(self):
return 'LinkedList(%s)' % self.first
def insert(self, value):
self.current.next = Link(value)
self.current = self.current.next
def flatten_tree_to_linked_list(root):
"""Traverse tree in depth frist fasion
and add every node to the linked list"""
stack = Stack()
stack.push(root)
while stack.stack:
node = stack.pop()
if 'linked' in locals():
linked.insert(node.data)
else:
linked = LinkedList(node.data)
if node.right:
stack.push(node.right)
if node.left:
stack.push(node.left)
return linked
root = BinaryTree()
root.data = 1
root.left = BinaryTree()
root.left.data = 2
root.right = BinaryTree()
root.right.data = 5
root.left.left = BinaryTree()
root.left.left.data = 3
root.left.right = BinaryTree()
root.left.right.data = 4
root.right.right = BinaryTree()
root.right.right.data = 6
ls = flatten_tree_to_linked_list(root)
print(ls)
# LinkedList(1→2→3→4→5→6→None)
|
fa06ce33ea1d16c151c6c8ec0123be29a392a462 | caiosuzuki/exercicios-python | /ex039.py | 403 | 4.0625 | 4 | from datetime import date
ano = int(input('Informe seu ano de nascimento: '))
idade = date.today().year - ano
if idade < 18:
print('Você ainda vai se alistar ao serviço militar! Falta(m) {} ano(s)!'.format(18-idade))
elif idade == 18:
print('Você deve se alistar esse ano ao serviço militar!')
else:
print('Seu tempo já passou, tá safe! Você tá safe há {} ano(s)'.format(idade-18))
|
de8f1b975afad9ae373293f8db3086b5521e7393 | smithajanardan/janardan_python | /Books.py | 3,821 | 3.765625 | 4 | # File: Books.py
# Description: Compares the vocabulary in two books.
# Student Name: Smitha Janardan
# Student UT EID: ssj398
# Course Name: CS 303E
# Unique Number: 52220
# Date Created: 11/19/10
# Date Last Modified: 11/29/10
import string
# Create word dictionary from the comprehensive word list
word_dict = {}
def create_word_dict ():
words = open("words.txt", "r")
for line in words:
word_dict[line] = 1
words.close()
return
# Removes punctuation marks from a string
def parseString (st):
st = st.replace("\n"," ")
#creating a new string and only adding letters and spaces to it
str = ""
for ch in st:
if ch == "-":
str += " "
if ch.isalpha() or ch.isspace():
str += ch
else:
str += " "
return str
# Returns a dictionary of words and their frequencies
def getWordFreq (file):
input = open (file, "r")
book = {}
#removing all necessary characters in book
for line in input:
line = line.rstrip("\n")
line = parseString(line)
#moving string into a dictionary
line = line.split()
#getting word frequencies in the dictionary.
for elt in line:
if elt in book:
book[elt] += 1
else:
book[elt] = 1
input.close()
#opening the list of dictionary words
dele = []
thing = book.keys()
#check for proper nouns
for key in thing:
if key[0].isupper():
if key.lower() in book:
book[key.lower()] += book[key]
elif key.lower() in word_dict:
book[key.lower()] = book[key]
dele.append(key)
#deleting proper nouns
for item in dele:
del book[item]
return book
# Compares the distinct words in two dictionaries
def wordComparison (author1, freq1, author2, freq2):
print author1
print "Total distinct words = ", len(freq1)
#finding the total words used by author one
sum = 0
for key in freq1.values():
sum += key
sum = float(sum)
#printing everything for author one
print "Total words (including duplicates) = ", int(sum)
print "Ratio(% of total distinct words to total words) = ", (len(freq1)/sum)*100
print
print author2
print "Total distinct words = ", len(freq2)
#finding the total words used by author two
sum2 = 0
for key in freq2.values():
sum2 += key
sum2 = float(sum2)
#printing everything for author two
print "Total words (including duplicates) =", int(sum2)
print "Ratio(% of total distinct words to total words) = ", (len(freq2)/sum2)*100
print
book1 = set(freq1.keys())
book2 = set(freq2.keys())
#printing cross comparisons
print "%s used %d words that %s did not use." % (author1, len(book1-book2), author2)
print "Relative frequency of words used by %s not in common with %s = %f" % (author1, author2, (len(book1-book2)/sum)*100)
print
print "%s used %d words that %s did not use." % (author2, len(book2-book1), author1)
print "Relative frequency of words used by %s not in common with %s = %f" % (author2, author1, (len(book2-book1)/sum2)*100)
return
def main():
# Create word dictionary from comprehensive word list
create_word_dict()
# Enter names of the two books in electronic form
book1 = raw_input ("Enter name of first book: ")
book2 = raw_input ("Enter name of second book: ")
print
# Enter names of the two authors
author1 = raw_input ("Enter last name of first author: ")
author2 = raw_input ("Enter last name of second author: ")
print
# Get the frequency of words used by the two authors
wordFreq1 = getWordFreq (book1)
wordFreq2 = getWordFreq (book2)
# Compare the relative frequency of uncommon words used
# by the two authors
wordComparison (author1, wordFreq1, author2, wordFreq2)
main()
|
9cafbcb47eacf896d26bb3e858a4dfc23c6ede90 | DainaGariboldi/Daina | /Numero triandulado.py | 95 | 3.625 | 4 | N = int(input())
for R in range (1, N + 1):
print(' '.join(str(e) for e in range(1, R +1))) |
6646a8b7a4f4ad312921284239906b3e2553eb3a | Kshitiz1403/GeekWeek-Local | /Kshitiz1403/Array3.py | 429 | 4.15625 | 4 | import array
arr = array.array('i', [1, 2, 3])
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")
arr.append(4)
print("The appended array is : ", end="")
for i in range (0, 4):
print (arr[i], end=" ")
arr.insert(2, 5)
print("\r")
print ("The array after insertion is : ", end="")
for i in range (0, 5):
print (arr[i], end=" ") |
966a31113e51f7f55dafc60a58cae0df749c0a1c | moshlwx/leetcode | /CODE/剑指 Offer 28. 对称的二叉树.py | 1,888 | 4.125 | 4 | r'''
剑指 Offer 28. 对称的二叉树
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
限制:
0 <= 节点个数 <= 1000
注意:本题与主站 101 题相同:https://leetcode-cn.com/problems/symmetric-tree/
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
'''
树的遍历,类似DFS问题,
递归解决时,先确认退出条件,然后递归调用函数
'''
def travel_tree(left_root, right_root):
'''返回两棵子树是否对称
'''
# 结束状态1:叶子节点,则返回真
if not left_root and not right_root:
return True
# 结束状态2:非同时到叶子节点 或值不相等,则返回假
if not left_root or not right_root or left_root.val != right_root.val:
return False
return travel_tree(left_root.left, right_root.right) and travel_tree(left_root.right, right_root.left)
return travel_tree(root.left, root.right) if root else True
# [1,2,2,3,4,4,3]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)
print(Solution().isSymmetric(root))
|
982955e713495bbf8e34d5561d1712bde4d25910 | Pxshuo163/GitDoc | /Python/ValidPhoneNumber.py | 1,528 | 3.765625 | 4 | # 手机号码校验
# 校验准则 移动,联通,电信
CN_mobile = [134, 135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 147, 178, 1705]
CN_union = [130, 131, 132, 155, 156, 185, 186, 145, 176, 1709]
CN_telecom = [133, 153, 180, 181, 189, 177, 1700]
# 校验长度是否符合
def valid_length(num):
if len(num) == 11:
return True
else:
return False
# 验证num个字符
def valid_num_n(tell_num, valid_num):
num = int(tell_num[0: valid_num])
if num in CN_mobile:
return "中国移动"
elif num in CN_union:
return "中国联通"
elif num in CN_telecom:
return "中国电信"
else:
return False
# 校验是否符合规范,辨别号码类型
def valid_type(num):
num_3 = valid_num_n(num, 3)
num_4 = valid_num_n(num, 4)
if (not num_3) & (not num_4):# 3,4个字符串都没有找到
return "手机号错误"
elif num_3:
return num_3
else:
return num_4
# 主函数
def valid_main():
phone_number = str(input("请输入你的手机号码:"))
if valid_length(phone_number):
result = valid_type(phone_number)
if result == "手机号错误":
print (result)
valid_main()
else:
print ("号段:" + result + "\n我们将将验证码发送到" + phone_number + ",请查收~")
return
else:
print ("您输入的手机号不是11位!")
valid_main()
valid_main()
|
6df091e896cc18b28e24237f17a0c8ab682459e2 | Wangyandong-master/MedicalNer | /Vocab.py | 3,715 | 3.578125 | 4 | PAD = "<<PAD>>"
UNK = "<<UNK>>"
NUM = "<<NUM>>"
OUTSIDE = "O"
class Vocab:
def __init__(self, filename=None, encode_char=False, encode_tag=False):
self.max_idx = 0
self.encoding_map = {}
self.decoding_map = {}
self.encode_char = encode_char
self.encode_tag = encode_tag
self._insert = True
if filename:
self.load(filename)
self._insert = False
else:
if not self.encode_tag:
self._encode(PAD, add=True)
self._encode(UNK, add=True)
if not self.encode_char:
self._encode(NUM, add=True)
else:
self._encode(OUTSIDE, add=True)
def __len__(self):
return len(self.encoding_map)
def encodes(self, seq, char_level=False):
'''
encode a sequence
'''
return [self.encode(word, char_level) for word in seq]
def encode(self, word, char_level=False):
'''
encode a word or a char
'''
if char_level:
if self.encode_char:
return self._encode(word, add=self._insert)
else:
return self._encode(word, add=self._insert)
else:
if self.encode_char:
return [self._encode(char, add=self._insert) for char in word]
else:
return self._encode(word, add=self._insert)
def encode_datasets(self, datasets, char_level=False):
for dataset in datasets:
for (xws, xcs), ys in dataset:
if char_level:
if self.encode_tag:
self.encodes(ys)
elif self.encode_char:
self.encodes(xcs, char_level)
else:
self.encodes(xws)
else:
if self.encode_tag:
# print(ys)
self.encodes(ys)
elif self.encode_char:
self.encodes(xcs, char_level)
else:
self.encodes(xws)
def decodes(self, idxs):
return map(self.decode, idxs)
def decode(self, idx):
return self.decoding_map.get(idx, UNK)
def _encode(self, word, lower=False, add=False):
if lower:
word = word.lower()
if add:
idx = self.encoding_map.get(word, self.max_idx)
if idx == self.max_idx:
self.max_idx += 1
self.encoding_map[word] = idx
self.decoding_map[idx] = word
else:
if self.encode_tag:
idx = self.encoding_map.get(word, self.encoding_map[OUTSIDE])
else:
idx = self.encoding_map.get(word, self.encoding_map[UNK])
return idx
def save(self, filename):
import operator
with open(filename, "w", encoding='utf-8') as f:
for word, idx in sorted(self.encoding_map.items(), key=operator.itemgetter(1)):
f.write("%s\t%s\n" % (word, idx))
def load(self, filename):
with open(filename, "r", encoding='utf-8') as f:
for line in f:
line = line.strip()
word, idx = line.split("\t")
idx = int(idx)
self.encoding_map[word] = idx
self.decoding_map[idx] = word
self.max_idx = max(idx, self.max_idx)
def update(self, vocab):
for word in vocab:
self._encode(word, add=True) |
0318e00a37bb0a332fb8034c38083e6d900f0570 | BoyaChiu/Python_Basic_note | /08_面向对象.py | 5,537 | 4.75 | 5 | # 面向对象
# 类的定义
'''
基本形式:
class ClassName(object):
Statement
1.class定义类的关键字
2.ClassName类名,类名的每个单词的首字母大写。
3.object是父类名,object是一切类的基类。在python3中如果继承类是基类可以省略不写。
'''
class Fruits:
fruit = 'xxxxxxx'
list1 = []
def __init__(self,name,color='red',weight=90):
self.name = name
self._color= color
self.__weight = weight
self.list2 = []
def eat(self):
print('我是%s,啊,被吃掉了。。。' % self.name)
def show(self):
print('我的重量是:%s' % self.__weight)
class Apple(Fruits):
def __init__(self,shape):
Fruits.__init__(self,'MMMM',weight=1000)
self.shape = shape
def eat(self,xxxx):
Fruits.eat (self)
print('被吃掉了',xxxx)
def show(self):
super().show()
print('哈哈哈哈哈')
self.eat()
ap = Apple('圆的')
banana = Fruits('banana','yellow')
apple2 = Fruits('apple','green')
# 类的初始化
# __init__
'''
定义类时,这种方法可以使类对象实例按某种特定的模式生产出来。
后面的参数中第一个参数我们约定俗成的为self参数名,
self代表的是在类实例化后这个实例对象本身。
初始化函数除了有self这个参数表示实例对象本身之外,
其他的参数的定义也遵循函数的必备参数和默认参数一样的原则,
必备参数就是在实例化是一定要传入的参数,
默认参数就是在定义时可以给这个参数一个初始值。
'''
# 类的实例化
'''
基本形式:实例对象名 = 类名(参数)
在实例化的过程中,self代表的就是这个实例对象自己。
实例化时会把类名后面接的参数传进去赋值给实例,
这样传进去的参数就成为了这个实例对象的属性。
实例化的过程遵循函数调用的原则。
在实例化时也必须个数和顺序与定义时相同(使用关键字参数可以改变传参的顺序)。
当初始化函数定义时使用了默认参数时,在实例化时默认参数可以不传参这时
这个实例对象就会使用默认的属性,如果传了参数进去则会改变这参数值,
使实例化对象的属性就为你传进来的这个参数。
isinstance(实例名,类名)
判断一个实例是不是这个类的实例。
'''
# 类和实例属性
'''
类属性
.类属性是可以直接通过“类名.属性名”来访问和修改。
.类属性是这个类的所有实例对象所共有的属性,
任意一个实例对象都可以访问并修改这个属性(私有隐藏除外)。
.对类属性的修改,遵循基本数据类型的特性:列表可以直接修改,字符串不可以,
所以当类属性是一个列表时,通过任意一个实例对象对其进行修改。
但字符串类型的类属性不能通过实例对象对其进行修改。
实例属性
.在属性前面加了self标识的属性为实例的属性。
.在定义的时候用的self加属性名字的形式,在查看实例的属性时
就是通过实例的名称+‘.’+属性名来访问实例属性。
方法属性
.定义属性方法的内容是函数,函数的第一个参数是self,代表实例本身。
一些说明:
.数据属性会覆盖同名的方法属性。减少冲突,可以方法使用动词,数据属性使用名词。
.数据属性可以被方法引用。
.一般,方法第一个参数被命名为self,,这仅仅是一个约定,
self没有特殊含义,程序员遵循这个约定。
.查看类中的属性和实例属性可以调用__dict__方法返回属性组成的字典。
'''
# 私有变量和类本地变量。
'''
以一个下划线开头的命名(无论是函数,方法或数据成员),
都会被隐藏起来。但直接将命名完整的写下还是一样可以访问到。
单下划线只是隐藏了属性,但还是可以从外部访问和修改。
以两个下划线开头的命名,一样会被隐藏,只能在内部访问和修改,
不能在外部访问,因为它变成了“_类名__属性”的形式。
在外部只能通过这种形式才能访问和修改。
双下划线开头的属性就变成了私有变量,即使能改也不要在外部外部修改了。
私有变量的作用就是确保外部代码不能随意修改对象内部的状态。
'''
# 数据封装:
'''
.在类里面数据属性和行为用函数的形式封装起来,
访问时直接调用,不需知道类里面具体的实现方法。
'''
# 继承:
'''
.在定义类时,可以从已有的类继承,
被继承的类称为基类,新定义的类称为派生类。
.在类中找不到调用的属性时就搜索基类,
如果基类是从别的类派生而来,这个规则会递归的应用上去。
反过来不行。
.如果派生类中的属性与基类属性重名,那么派生类的属性会覆盖掉基类的属性。
包括初始化函数。
.派生类在初始化函数中需要继承和修改初始化过程,
使用’类名+__init__(arg)’来实现继承和私有特性,也可以使用super()函数。
issubclass(类名1,类名2)
判断类1是否继承了类2
'''
# 多态:
'''
.多态是基于继承的一个好处。
.当派生类重写了基类的方法时就实现了多态性。
''' |
ec81e45353cb20332d5b864941a93a3f3292a47e | Fayozxon/python-quests | /Birinchi qism/48.4-musbatlar.py | 250 | 3.65625 | 4 | # a, b va c
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
# Tekshirish:
if a > 0:
print(a, 'ning kvadrati -', a**2)
if b > 0:
print(b, 'ning kvadrati -', b**2)
if c > 0:
print(c, 'ning kvadrati -', c**2) |
cfc243618aff89547e241d5f37d3f68755b4c7c9 | drybell/coding-problems | /may/may102020/attempt1problem2.py | 751 | 3.984375 | 4 | # This problem was asked by Jane Street.
# cons(a, b) constructs a pair, and car(pair) and cdr(pair)
# returns the first and last element of that pair.
# For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
# Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
# Implement car and cdr.
# algebraic laws: (car x xs) = x
# (cdr x xs) = xs
# (checked runtime error with car of empty list)
# (cdr []) == []
# (cdr x []) == []
def car(f):
return f(lambda x,y: x)
def cdr(f):
return f(lambda x,y: y)
# print(cons(3,4)(lambda x,y: x))
# print(car(cons(3,4)))
assert car(cons(3,4)) == 3
assert cdr(cons(3,4)) == 4 |
a80df3ebd58df8e023373649ec070fed16836595 | Wajahat-Ahmed-NED/WajahatAhmed | /waji.py | 538 | 3.515625 | 4 | class Myemployee:
def __init__(self,fnaem,lname,cnic,email,address,salary,post):
self.firstname=fnaem
self.lname=lname
self.cnic=cnic
self.email=email
self.address=address
self.salary=salary
self.post=post
ali=Myemployee("Ali","Khan","42102156578687","[email protected]","karachi","4500000","officer")
umar=Myemployee("umar","ahmed","42105604504763","[email protected]","Lahore","500000","Manager")
print(ali.salary)
# if ali is leaving
del ali
umar.email="[email protected]"
print(umar.email) |
9c910a6823d935cbc7604531d1c22a272ff4b096 | alading241/metaapi-python-sdk | /lib/clients/methodAccessException.py | 1,013 | 3.5 | 4 | class MethodAccessException(Exception):
"""Exception which indicates that user doesn't have access to a method.
"""
def __init__(self, method_name: str, access_type: str = 'api'):
"""Inits the method access exception.
Args:
method_name: Name of method.
access_type: Type of method access.
"""
if access_type == 'api':
error_message = f'You can not invoke {method_name} method, because you have connected with API ' + \
'access token. Please use account access token to invoke this method.'
elif access_type == 'account':
error_message = f'You can not invoke {method_name} method, because you have connected with account ' + \
'access token. Please use API access token from https://app.metaapi.cloud/token page ' + \
'to invoke this method.'
else:
error_message = ''
super().__init__(error_message)
|
095a2bc06e271807f87cd0f37e56634778dcc11d | gayathrimaganti/maganti_gayathridevi_spring2017 | /Python Assignment-3/Q1_Part_2.py | 1,968 | 3.75 | 4 |
# coding: utf-8
# NYC Vehicle Collision Analysis
#1.For each borough, find out distribution of each collision scale. (One car involved? Two? Three? or more?) (From 2015 to present)
#2.Display a few rows of the output use df.head().
#3.Generate a csv output with five columns ('borough', 'one-vehicle', 'two-vehicles', 'three-vehicles', 'more-vehicles')
# In[1]:
#importing libraries
import os
import pandas as pd
# In[2]:
#creating relative path from current directory to access the input csv file
current_location=os.path.dirname('__file__')
input_data_location=os.path.join(current_location,'Data')
csv_file='vehicle_collisions.csv'
#accessing csv input data file through relative path
path=os.path.join(input_data_location,csv_file)
# In[3]:
df=pd.read_csv(path,sep=',')
df
# In[4]:
select_col_df=df.ix[:,('BOROUGH','VEHICLE 1 TYPE','VEHICLE 2 TYPE','VEHICLE 3 TYPE','VEHICLE 4 TYPE', 'VEHICLE 5 TYPE')]
# In[5]:
select_col_df['VEHICLES']=select_col_df.loc[:,('VEHICLE 1 TYPE','VEHICLE 2 TYPE','VEHICLE 3 TYPE','VEHICLE 4 TYPE',
'VEHICLE 5 TYPE')].count(axis=1)
# In[6]:
select_col_df
# In[7]:
num_of_vehi=select_col_df.groupby(['BOROUGH','VEHICLES']).VEHICLES.count()
# In[8]:
num_of_vehi
# In[9]:
df1=pd.DataFrame({'Sum':num_of_vehi})
# In[10]:
df1.reset_index(inplace=True)
# In[11]:
df1
# In[12]:
df2=df1.pivot(index='BOROUGH', columns='VEHICLES', values='Sum')
# In[13]:
df2.columns=['ZERO_VEHICLE_INVOLVED','ONE_VEHICLE_INVOLVED','TWO_VEHICLES_INVOLVED','THREE_VEHICLES_INVOLVED','FOUR_VEHICLES_INVOLVED','FIVE_VEHICLES_INVOLVED']
# In[14]:
df2['MORE_VEHICLES_INVOLVED'] = df2['FOUR_VEHICLES_INVOLVED'] + df2['FIVE_VEHICLES_INVOLVED']
df2= df2.loc[:,('ONE_VEHICLE_INVOLVED','TWO_VEHICLES_INVOLVED','THREE_VEHICLES_INVOLVED','MORE_VEHICLES_INVOLVED')]
df2.reset_index(inplace=True)
# In[15]:
df2.head()
# In[16]:
df2.to_csv('Q1_Part_2.csv',index=False)
# In[ ]:
|
6d75e370ab4bc70c1a2c6e36e77e93e3559acb46 | akashshegde11/python-practice | /Introduction/intro_2.py | 142 | 4.03125 | 4 | # Demo of conditional statement
num = int(input("Enter a number: "))
if(num > 15):
print("Good number!")
else:
print("Bad number!")
|
f69afd92deeb7037b73240ad72e81a271823018a | miltonleal/MAC0110_Introduction_Computer_Science_IME_USP | /Ex. do Paca/Aula 17/P_17.14.py | 369 | 3.625 | 4 | # Função elimina_repetidos(x) que devolve uma lista contendo os elementos da lista x sem repetição.
a = [1,1,1,1,1,2,3,4,5]
def elimina_repetidos(a):
i = 0
result = []
for i in range (len(a)):
#while i < len(a):
if not (a[i] in a[i+1:]):
result.append(a[i])
i += 1
return result
print (elimina_repetidos(a))
|
fc0f10d875dca362b0e0bdde56994edc9bc4d155 | matthew-samyn/challenge-sentiment-analysis | /app/app.py | 2,456 | 3.609375 | 4 | from PIL import Image
from utils.streamlit_functions import *
import streamlit as st
st.set_page_config(layout="wide")
header = st.container()
plots = st.container()
scrape_section = st.container()
# Handles the sidebar option
st.sidebar.title("Sentiment analysis")
brooklyn_99_button = st.sidebar.selectbox("What show would you like to analyze?",
options=["Brooklyn 99","Analyze your own favorite show"])
# Handles the first option from the sidebar.
# Loads a csv, prescraped from Twitter.
# Shows a piechart with useful info on sentiment analysis.
if brooklyn_99_button == "Brooklyn 99":
with header:
st.title(" My favourite show ")
image = Image.open('visuals/Brooklyn-Nine-Nine.jpg')
st.image(image)
st.write('---')
with plots:
df = pd.read_csv("files/brooklyn99.csv")
with st.spinner(f"""
Processing {len(df)} tweets
"""):
st.success(f"Processed {len(df)} tweets")
fig = show_sentiment_distribution(df["sentiment"], plot_title="Brooklyn99 sentiment analysis")
st.plotly_chart(fig, use_container_width=True)
# Handles the second option from the sidebar.
# Scrapes a searchterm given by the user.
# Shows a piechart with useful info on sentiment analysis.
elif brooklyn_99_button == "Analyze your own favorite show":
with header:
image = Image.open('visuals/your_turn.jpg')
st.image(image)
st.write('---')
with plots:
inputted_text = st.text_input("Enter the hashtag you want to search for on Twitter:", value="#")
if inputted_text not in ["","#"]:
with st.spinner(f"Searching Twitter for {inputted_text}"):
df = scrape_twitter([inputted_text])
st.success(f"Found {len(df)} relevant tweets")
# Safety if no tweets were found.
if len(df) == 0:
st.write("Please try a different search message.")
else:
with st.spinner(f"""
Processing all tweets
"""):
df["sentiment"], df["cleaned_tweet"] = \
return_sentiments(df["text"])
st.success(f"Processed {len(df)} tweets")
fig = show_sentiment_distribution(df["sentiment"], plot_title=f"{inputted_text} sentiment analysis")
st.plotly_chart(fig, use_container_width=True)
|
72274d59f3a3a93c4f7225348918bd3c5a4411d4 | jlucasldm/ufbaBCC | /2021.2/linguagens_formais_e_automatos/listas/semana_3/encaixa_ou_nao_II.py | 739 | 3.84375 | 4 | #funcao principal Encaixa ou Nao
def solucao(a, b):
#procurar na string a, a partir do índice (len(a) - len(b))
#ate o fim de a, pela string b
#string.fin(substring) retorna -1 caso nao encontre a substring em
#questao. caso contrario, retorna o index de onde a substring comeca
#retorna 'encaixa' caso b for encontrado nos ultimos caracteres
#de a. caso contrario, retorna 'nao encaixa'
return 'encaixa' if not a.find(b, (len(a) - len(b)), len(a)) == -1 else 'nao encaixa'
#entrada da quantidade de linhas a serem lidas
n = int(input())
for i in range(n):
#entrada da string e substring
a, b = input().split()
#printando o retorno da funcao
print(solucao(a, b)) |
667218b768f34f7e1344554c108322e92751deac | jhiltonsantos/ADS-Algoritmos-IFPI | /Atividade_Fabio_01/fabio01_17_area-retangulo.py | 267 | 3.78125 | 4 | # entrada
base = float(input('Qual a medida da base do retangulo? '))
altura = float(input('Qual a medida da altura do retangulo? '))
# processamento
area_retangulo = base * altura
# saida
print ('A area do retangulo é de: {}'.format(area_retangulo))
|
746f2e2a89edcb56369a94eb59a888781e3fc234 | dcwales/leevs_space | /Complex.py | 898 | 3.53125 | 4 | """
CMod Ex2: methods for complex numbers
represented as Numpy 1*2 arrays
"""
import math
import numpy as np
# Complex conjugate
def conj(c):
return np.array([c[0], -c[1]])
# Square modulus
def normSq(c):
return c[0]**2 + c[1]**2
# Modulus
def norm(c):
return math.sqrt(normSq(c))
# Multiplication of complex with scalar
def scale(c, scalar):
return c*scalar
# Complex addition
def add(a, b):
realPart = a[0] + b[0]
imagPart = a[1] + b[1]
return np.array([realPart, imagPart ])
# Complex subtraction
def sub(a, b):
realPart = a[0] - b[0]
imagPart = a[1] - b[1]
return np.array([realPart, imagPart])
# Complex multiplication
def mul(a, b):
realPart = a[0]*b[0] - a[1]*b[1]
imagPart = a[0]*b[1] + a[1]*b[0]
return np.array([realPart, imagPart])
# Complex division
def div(a, b):
z = mul(a, conj(b))
return scale(z, 1.0/normSq(b))
|
873ca708b169bb7b0417bedbe1776665a08dc0f2 | DanAmador/RMP | /TZMap.py | 6,796 | 3.65625 | 4 | """
This program defines a class that stores the trapezoidal map.
It also provides related helper functions.
Author: Ajinkya Dhaigude ([email protected])
"""
class TZMap:
def __init__(self, root):
self.root = root
self.adjMatrix = None
self.allPNames = []
self.allQNames = []
self.totSegments = 0
self.totTrapezoids = 0
def update_root(self, root):
self.root = root
def assign_trapezoid_names(self, id_num=0, node=None):
"""
Recursive function that assigns a unique name to
each trapezoid. This function should be called
after the whole map is built as the trapezoids are
constantly modified and deleted during the building
process.
:param id_num: sequential number part of the name
:param node: current node under consideration
:return: last assigned number
"""
if node is None:
node = self.root
if node.is_leaf and node.name is None:
id_num += 1
node.name = 'T' + str(id_num)
elif node.type == 'xnode':
id_num = self.assign_trapezoid_names(id_num, node.left)
id_num = self.assign_trapezoid_names(id_num, node.right)
elif node.type == 'ynode':
id_num = self.assign_trapezoid_names(id_num, node.above)
id_num = self.assign_trapezoid_names(id_num, node.below)
return id_num
def find_tz_node(self,user_point, node= None):
if node is None:
node = self.root
if node == node.type == 'tnode':
return node.name
if node.type == 'xnode':
if user_point.x >= node.end_point.x:
self.print_traversal_path(user_point, node.right)
else:
self.print_traversal_path(user_point, node.left)
elif node.type == 'ynode':
if node.line_segment.isPointAbove(user_point):
self.print_traversal_path(user_point, node.above)
else:
self.print_traversal_path(user_point, node.below)
def print_traversal_path(self, user_point, node=None, path = []):
"""
Print to console the traversal path of the given
point in the map.
:param user_point: destination point
:param node: current node on the path to destination
:return: None
"""
if node is None:
node = self.root
path.append(node.get_name())
if node.type == 'xnode':
if user_point.x >= node.end_point.x:
self.print_traversal_path(user_point, node.right, path)
else:
self.print_traversal_path(user_point, node.left,path)
elif node.type == 'ynode':
if node.line_segment.isPointAbove(user_point):
self.print_traversal_path(user_point, node.above,path)
else:
self.print_traversal_path(user_point, node.below,path)
def create_adj_matrix(self, unique_points, num_segments, num_trapezoids):
"""
Convert trapezoidal map to an adjacency matrix and write the
output to a file.
:param unique_points: list of unique points in the map
:param num_segments: total number of segments in the map
:param num_trapezoids: total number of trapezoids in the map
:return: None
"""
for point in unique_points:
if point.name[0] == 'P':
self.allPNames.append(int(point.name[1:]))
else:
self.allQNames.append(int(point.name[1:]))
self.totSegments = num_segments
self.totTrapezoids = num_trapezoids
n = len(unique_points) + num_segments + num_trapezoids + 2
self.adjMatrix = [[0] * n for i in range(n)]
self.header_for_adj_matrix(0, ' ')
self.header_for_adj_matrix(len(self.adjMatrix) - 1, 'Sum')
self.fill_adj_matrix()
adjFileName = "adjMatrixOutput.txt"
with open(adjFileName, 'w') as outFile:
for arr in self.adjMatrix:
for col, elem in enumerate(arr):
elem = str(elem)
if len(elem) == 1:
elem = ' ' + elem + ' '
if len(elem) == 2:
elem = ' ' + elem
outFile.write(elem + ' ')
outFile.write('\n')
def fill_adj_matrix(self, node=None):
"""
Recursive function that traverses the map to fill in
appropriate vales in the adjacency matrix.
:param node: current node under consideration
:return: None
"""
if node is None:
node = self.root
col = self.get_idx(node)
if node.type == 'xnode':
self.add_to_adj_matrix(self.get_idx(node.left), col)
self.fill_adj_matrix(node.left)
self.add_to_adj_matrix(self.get_idx(node.right), col)
self.fill_adj_matrix(node.right)
if node.type == 'ynode':
self.add_to_adj_matrix(self.get_idx(node.above), col)
self.fill_adj_matrix(node.above)
self.add_to_adj_matrix(self.get_idx(node.below), col)
self.fill_adj_matrix(node.below)
def get_idx(self, node):
"""
Get corresponding index in the matrix of a node
from its name.
:param node: node to be indexed
:return: index of node
"""
name = node.get_name()
if len(name) == 2:
name += ' '
idx = int(name[1:])
if name[0] == 'P':
idx = self.allPNames.index(idx) + 1
self.header_for_adj_matrix(idx, name)
return idx
if name[0] == 'Q':
idx = self.allQNames.index(idx) + 1
idx += len(self.allPNames)
self.header_for_adj_matrix(idx, name)
return idx
if name[0] == 'S':
idx += len(self.allPNames) + len(self.allQNames)
self.header_for_adj_matrix(idx, name)
return idx
if name[0] == 'T':
idx += len(self.allPNames) + len(self.allQNames) + self.totSegments
self.header_for_adj_matrix(idx, name)
return idx
def add_to_adj_matrix(self, row, col):
if self.adjMatrix[row][col] == 0:
self.adjMatrix[row][col] = 1
self.adjMatrix[row][-1] += 1
self.adjMatrix[-1][col] += 1
def header_for_adj_matrix(self, idx, name):
self.adjMatrix[0][idx] = name
self.adjMatrix[idx][0] = name
|
c33d51d98f3363cbd92b99940b4d1a51bbd5e7f1 | akaProgramer/python_tkinter | /tk_button_pracice.py | 927 | 3.5625 | 4 | from tkinter import *
root = Tk()
def button1_message():
print("hello from button 1")
def button2_message():
print("hello from button 2")
def button3_message():
print("hello from button 3")
def button4_message():
print("hello from button 4")
def button1_message():
print("hello from button 1")
root.geometry("445x423")
f1= Frame(root,bg="skyblue", borderwidth= 4, relief=RAISED)
f1.pack(side=TOP)
Button1 = Button(f1,text="button 1" , bg="orange" , fg="green", command=button1_message)
Button1.pack(padx= 5, side=LEFT)
Button2 = Button(f1,text="button 2" , bg="orange" , fg="green", command=button2_message)
Button2.pack(padx= 5, side=LEFT)
Button3 = Button(f1,text="button 3" , bg="orange" , fg="green", command=button3_message)
Button3.pack(padx= 5, side=LEFT)
Button4 = Button(f1,text="button 4" , bg="orange" , fg="green", command=button4_message)
Button4.pack(pady= 5, side=LEFT)
root.mainloop() |
90daa8bad236485b1dc4edc69520fc82e757b8ff | lakshmiPrasanna-chebrolu/PythonProjects | /audioSeg&Recog/sr.py | 414 | 3.546875 | 4 | import speech_recognition as sr
AUDIO_FILE=("audio-extract.wav")
# use audio file as source
r=sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
try:
print("audio file contains:"+r.recognize_google(audio))
except sr.UnknownValueError:
print("Google cannot understand")
except sr.RequestError:
print("couldnt get the results from google speech Recognition")
|
8321da83525bb6e85ce9aee62448682b13bd3c9f | CrispthoAlex/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 409 | 4.09375 | 4 | #!/usr/bin/python3
"""
class MyList from list:
def print_sorted(self): that prints the list, but sorted (ascending sort)
"""
class MyList(list):
"""
Args: list from main
"""
def print_sorted(self):
"""
Public instance method that prints the list, but
sorted (ascending sort)
Args: @self: inherits the input from self
"""
print(sorted(self))
|
7f94d60cee39cc8d66f64fb1ab2457be7fa574be | SmischenkoB/campus_2018_python | /Dmytro_Shalimov/1/7.py | 1,698 | 4.28125 | 4 | <<<<<<< HEAD
print("Bob is a lackadaisical teenager. In conversation, his responses are very limited.")
print("Bob answers \"Sure.\" if you ask him a question.")
print("He answers \"Whoa, chill out!\" if you yell at him.")
print("He answers \"Calm down, I know what I'm doing!\" if you yell a question at him.")
print("He says \"Fine. Be that way!\" if you address him without actually saying anything.")
print("He answers \"Whatever.\" to anything else.")
user_input = input("Say something to Bob: ")
if len(user_input) == 0:
print("Fine. Be that way!")
elif user_input[-1] == '?':
if user_input[-2].isupper():
print("Calm down, I know what I'm doing!")
else:
print("Sure")
else:
if user_input[-1].isupper():
print("Whoa, chill out!")
else:
print("Whatever.")
=======
print("Bob is a lackadaisical teenager. In conversation, his responses are very limited.")
print("Bob answers \"Sure.\" if you ask him a question.")
print("He answers \"Whoa, chill out!\" if you yell at him.")
print("He answers \"Calm down, I know what I'm doing!\" if you yell a question at him.")
print("He says \"Fine. Be that way!\" if you address him without actually saying anything.")
print("He answers \"Whatever.\" to anything else.")
user_input = input("Say something to Bob: ")
if len(user_input) == 0:
print("Fine. Be that way!")
elif user_input[-1] == '?':
if user_input[-2].isupper():
print("Calm down, I know what I'm doing!")
else:
print("Sure")
else:
if user_input[-1].isupper():
print("Whoa, chill out!")
else:
print("Whatever.")
>>>>>>> 715fd0763b415a13fb28a483f258a5eadc1ec931
|
8b06a072633043fa28466d4830059d5144253750 | Malvtrics/ML | /LeeCode/LIS问题.py | 1,600 | 3.6875 | 4 | #LIS longest increasing sequence 最长上升子序列问题
#300 题目 https://leetcode-cn.com/problems/longest-increasing-subsequence/
#思路:用一个dp数组来保存历史最长子序列长度,这个是有了思路之后自己写出的代码,没有直接参考答案,复杂度O(N*N)
#需要进一步优化为nlogn, 先按照思路解决面试17.08题 https://leetcode-cn.com/problems/circus-tower-lcci/
class Solution(object):
def lengthOfLIS(self, nums):
dp = []
ans = 0
for i in range(len(nums)):
dp.append(1)
maxdp = 0
for j in range(i):
if nums[j] < nums[i] and dp[j] > maxdp:
maxdp = dp[j]
dp[i] += maxdp
if dp[i] > ans:
ans = dp[i]
return ans
#面试17.08题 https://leetcode-cn.com/problems/circus-tower-lcci/
#没做出来,直接看解法 https://leetcode-cn.com/problems/circus-tower-lcci/solution/python-solutiontan-xin-er-fen-cha-zhao-by-gareth/
#官方的贪心加二分查找方法
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
d = []
for n in nums:
if not d or n > d[-1]:
d.append(n)
else:
l, r = 0, len(d) - 1
loc = r
while l <= r:
mid = (l + r) // 2
if d[mid] >= n:
loc = mid
r = mid - 1
else:
l = mid + 1
d[loc] = n
return len(d)
|
2562f03842838fe680fdf60f5589166058747d1e | xxxwtc88/scir-training-day | /2-python-practice/5-numpy/listcount.py | 308 | 3.609375 | 4 | #!/usr/bin/env python
import numpy as np
import time
tStart = time.time()
x = np.random.randint(10, size=(10000000))
x = list(x)
y = np.random.randint(10, size=(10000000))
x = list(y)
for i in range(10):
t=0
for j in range(10000000):
t+=x[j]*y[j]
tEnd = time.time()
print "it cost %f sec" %(tEnd-tStart)
|
489245c445d42e2a8da39facd3fe2187bc1f2a68 | adilsachwani/PythonCrashCourse_Solutions | /7_8.py | 362 | 3.578125 | 4 | sandwich_orders = ['club','bbq','egg','special']
finisjed_sandwiches = []
while sandwich_orders:
current_sandwich = sandwich_orders.pop()
print("We have made for " + current_sandwich.title() + " sandwich.")
finisjed_sandwiches.append(current_sandwich)
print()
for sandwich in finisjed_sandwiches:
print(sandwich.title() + " sandwich is read.") |
bdbd4ce977f91119243314bc0153d0cad2cb317e | moon-light-night/learn_python | /complete - area.py | 317 | 4.09375 | 4 | print('Расчет площади прямоугольника по известным сторонам')
a = float(input('Введите значение стороны a: '))
b = float(input('Введите значение стороны b: '))
s = a * b
print('Площадь прямоугольника: ', s)
|
9bfa80c6ca8d734c57d5cad32cf889c15fc45414 | pedropmedina/python-bootcamp | /testing/tests.py | 1,394 | 3.765625 | 4 | import unittest
from activities import eat, is_funny, nap
class ActivityTest(unittest.TestCase):
def test_eat_healthy(self):
"""eat should have a positive message for healthy eating"""
self.assertEqual(
eat("broccoli", is_healthy=True),
"I'm eating broccoli, because it is healthy",
)
def test_eat_unhealthy(self):
"""eat should indicate unhealthy eating"""
self.assertEqual(
eat("pizza", is_healthy=False),
"I'm eating pizza, and I don't care.",
)
def test_short_nap(self):
"""short naps should be refreshing"""
self.assertEqual(nap(1), "I'm feeling refreshed after my 1 hour nap")
def test_long_nap(self):
"""short naps should be discouraging"""
self.assertEqual(
nap(3), "Ugh I overslept. I didn't mean to nap for 3 hour."
)
def test_is_funny_tim(self):
# self.assertEqual(is_funny("tim"), False)
self.assertFalse(is_funny("tim"), "Tim should not be funny")
def test_is_funny_anyone_else(self):
"""anyone else, but tim should be funny"""
self.assertTrue(is_funny("blue"), "blue should be funny")
self.assertTrue(is_funny("tammy"), "tammy should be funny")
self.assertTrue(is_funny("sven"), "sven should be funny")
if __name__ == "__main__":
unittest.main()
|
fbe9e6621156390808b59caf6a4c4ea9da5ca7de | nakahatar111/Python_Games | /tictactoe.py | 4,215 | 4.03125 | 4 | class TicTacToe:
board = [" "] * 10
player1 = "X"
player2 = "O"
db = False
playersTurn = 0
P1win = 0
P2win = 0
def __int__(self, _db):
self.db = _db
self.start()
self.resetGame()
def instruction(self):
print("When it's your turn type the number to represent the location")
print(" | | ")
print(" 6 | 7 | 8 ")
print(" | | ")
print("-----------")
print(" | | ")
print(" 3 | 4 | 5 ")
print(" | | ")
print("-----------")
print(" | | ")
print(" 0 | 1 | 2 ")
print(" | | ")
print()
def resetGame(self):
self.board = [" "] * 10
self.playersTurn = 0
def start(self):
choice = input("X or O").lower()
if choice == "o":
self.player1 = "O"
self.player2 = "X"
if self.db == True:
print("self.player1: " + self.player1)
print("self.player2: " + self.player2)
def play(self):
self.start()
self.instruction()
if self.db == True:
self.drawboard()
gameOver = False
while gameOver == False:
self.playersTurn += 1
if self.db:
print("Num of Turns: "+ str(self.playersTurn))
if self.playersTurn %2 ==0:
currentToken = self.player2
print("Player2 Turn")
else:
currentToken = self.player1
print("Player1 Turn")
validChoice = False
while validChoice == False:
choice = int(input("Where do you want to make your mark (Choose 0-8)"))
if choice < 0 or choice > 8:
print("You entered an invalid number, only choose a number between 0-8")
elif self.board[choice] != ' ':
print("Choose a different square. This one is already taken")
else:
validChoice = True
self.board[choice] = currentToken
if self.db:
print("self.player: "+ self.player1)
self.drawboard()
gameOver = self.bCheckGameOver()
if self.playersTurn %2 != 0:
self.P1win += 1
else:
self.P2win += 1
print("Player 1 won " + str(self.P1win) + " times")
print("Player 2 won " + str(self.P2win) + " times")
def drawboard(self):
print(" | |")
print(" " + self.board[6] +" | " + self.board[7] + " | " + self.board[8])
print(" | |")
print("-----------")
print(" | |")
print(" " + self.board[3] +" | " + self.board[4] + " | " + self.board[5])
print(" | |")
print("-----------")
print(" | |")
print(" " + self.board[0] +" | " + self.board[1] + " | " + self.board[2])
print(" | |")
def bCheckGameOver(self):
if self.board[7] != " " and self.board[6] == self.board[7] and self.board[7] == self.board[8]:
return True
elif self.board[4] != " " and self.board[3] == self.board[4] and self.board[4] == self.board[5]:
return True
elif self.board[1] != " " and self.board[0] == self.board[1] and self.board[1] == self.board[2]:
return True
elif self.board[3] != " " and self.board[6] == self.board[3] and self.board[3] == self.board[0]:
return True
elif self.board[4] != " " and self.board[7] == self.board[4] and self.board[4] == self.board[1]:
return True
elif self.board[5] != " " and self.board[8] == self.board[5] and self.board[5] == self.board[2]:
return True
elif self.board[4] != " " and self.board[6] == self.board[4] and self.board[4] == self.board[2]:
return True
elif self.board[4] != " " and self.board[8] == self.board[4] and self.board[4] == self.board[0]:
return True
return False
game = TicTacToe()
while True:
game.play()
if int(input("Type 1 to play a new game")) ==1:
game.resetGame()
else:
break |
726d31dbe3b03c0b463252e7d594a3dd5558b9c7 | mukeshv483/python_demo_programs | /Python-programs/Python-Training/python_programs3/pythonQno60/FilePackage/filefunc.py | 1,607 | 3.96875 | 4 | import os;
def readfile(file1):
file = open(file1, "r")
print "reading file"
str1=file.read()
print str1
file.close()
def writetofile(file1):
file = open(file1, "w")
print "writing to the file"
for num in range(0,5):
str2=raw_input("enter string to write to file")
file.write(str2)
file.close()
print "writing complete"
def appending(file1):
print "appending to the file"
file3 = open(file1, "a")
for num in range(0,5):
str2=raw_input("enter string to write to file")
file3.write(str2)
file3.close()
print "appending complete"
def searchpattern(directory):
pattern=raw_input("enter pattern to search")
dirs = os.listdir(directory)
count=0
for file in dirs:
f=open(directory+"/"+file,"r")
str1=f.read()
if pattern in str1:
print "pattern occurred in file :",file
count+=1
f.close()
print "pattern occured in %d files" % count
for file in dirs:
f=open(directory+"/"+file,"r")
str1=f.read()
count1=str1.count(pattern,0,len(str1))
print "occurrence of pattern in this file %s is = %d :" %(file,count1)
f.close();
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
def revlineorder(file):
file=open(file,"r")
str1=file.readlines()
count=len(str1)-1
for line in str1:
print str1[count]
count=count-1
file.close()
def reversecontent(file):
file=open(file,"r")
str3=reverse(file.read())
file.close();
print str3
|
34027116c6f161102d06e3a28b1b1ba759ff609a | haiyuanhe/learn_python | /sword_offer/reverse_list.py | 673 | 3.9375 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 翻转链表
# 链表
class Solution:
# 返回ListNode
def ReverseList(self, head):
p = None
while head:
tmp = head.next
head.next = p
p = head
head = tmp
return p
if __name__ == '__main__':
s = Solution()
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
p = s.ReverseList(l1)
while p != None:
print p.val
p = p.next
|
7007ff4c5d4cd9ae59ba9642bf27f5b38c6af4d1 | artbb/gb_python | /hw3_2.py | 1,048 | 4.25 | 4 | """
2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
def user_data(name, surname, birth, city, email, phone):
return (
f'Добрый день {name} {surname}! Проверьте ваши данные: вы родились {birth}, проживаете в {city}, ваш email {email}, телефон {phone}')
print(user_data(name=input('Ваше имя: '), surname=input('Ваша фамилия: '), birth=input('Год рождения: '),
city=input('Город проживания: '), email=input('email: '), phone=input('Телефон: ')))
|
2d0a7d53f633390da81528ea288b1c001bec18ce | VinayakBagaria/Python-Programming | /New folder/Queen's Attack.py | 1,892 | 3.640625 | 4 | def check(y,x):
for i in range(0,obstacle):
if(x==ob_x[i] and y==ob_y[i]):
return 1
return 0
sidelength,obstacle=input().split(' ')
sidelength,obstacle=[int(sidelength),int(obstacle)]
"""
(y,x)
4,4 and size 8,8
left : 4,3 4,2 4,1 [decrease x till 1]
right : increase x increase x till 8
up : increase y till 8
down : decrease y till 1
nw : increase y, decrease x till x=1 and y=8
ne : increase y, increase x till x=8 and y=8
sw : decrease y, decrease x till x=1 and y=1
se : decrease y, increase x till x=8 and y=1
"""
y,x=input().split(' ')
y,x=[int(y),int(x)]
ob_x=[]
ob_y=[]
for i in range(0,obstacle):
a,b=input().split(' ')
a,b=[int(a),int(b)]
ob_y.append(a)
ob_x.append(b)
moves=0
# left
leftX=x
while(leftX!=1):
if(check(y,leftX-1)==1):
break
moves+=1
leftX-=1
#right
rightX=x
while(rightX!=sidelength):
if (check(y,rightX+1) == 1):
break
moves+=1
rightX+=1
# up
upY = y
while (upY != sidelength):
if (check(upY+1,x) == 1):
break
moves += 1
upY += 1
# down
downY = y
while (downY != 1):
if (check(downY-1,x) == 1):
break
moves += 1
downY -= 1
#nw
incY=y
decX=x
while(decX!=1 and incY!=sidelength):
if (check(incY+1, decX-1) == 1):
break
moves+=1
decX-=1
incY+=1
#ne
incY=y
incX=x
while(incX!=sidelength and incY!=sidelength):
if (check(incY+1, incX+1) == 1):
break
moves+=1
incX+=1
incY+=1
#sw
decY=y
decX=x
while(decX!=1 and decY!=1):
if (check(decY-1, decX-1) == 1):
break
moves+=1
decX-=1
decY-=1
#se
decY=y
incX=x
while(incX!=sidelength and decY!=1):
if (check(decY-1, incX+1) == 1):
break
moves+=1
incX+=1
decY-=1
print(moves) |
c6538401bc363fa3683b236fa06e9e10c5adc1cb | Rishiidc/z-score | /file.py | 683 | 3.96875 | 4 | file1 = open("intro","r")
data = file1.readlines()
#print(data)
for line in data:
print(line)
temp = "things cup cars drinks"
print(temp.split(','))
def printmyname(i):
for a in range(i):
print("I am Rishi")
#printmyname(1)
def USDintoINR(money):
print("1 Dollar is equal to 72 Indian rupees")
print(money*72)
USDintoINR(500)
def countwords():
filename = input("Enter your file name")
f = open(filename,"r")
total = 0
for line in f:
words = line.split()
total = total + len(words)
print("Line:"+str(len(words)))
print("Total numeber of words ="+str(total))
countwords()
|
57015d9c969acdb8d3faf748b61c69c25da3ed16 | Aden-Q/LeetCode | /code/684.Redundant-Connection.py | 845 | 3.5 | 4 | class UF:
def __init__(self, n):
self.parent = list(range(n))
def union(self, key1, key2):
if not self.isConnected(key1, key2):
root1 = self.find(key1)
root2 = self.find(key2)
self.parent[root1] = root2
def find(self, key):
while self.parent[key] != key:
self.parent[key] = self.parent[self.parent[key]]
key = self.parent[key]
return key
def isConnected(self, key1, key2):
return self.find(key1) == self.find(key2)
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
n = len(edges)
uf = UF(n + 1)
for edge in edges:
p, q = edge
if uf.isConnected(p, q):
return edge
uf.union(p, q)
|
dd42a1ea14efc7e512257394b90066bda8510bb4 | IAMJINU/ProjectEuler | /python/ex06_SumSquareDifference.py | 1,148 | 3.75 | 4 | #ex06_SumSquareDifference.py
#total execution time : 0.0010006427764892578
#value : 25164150
import time
def computeSumOfSquare():
sumOfSquare = 1
for i in range(2, 101):
sumOfSquare = sumOfSquare + (i * i)
return sumOfSquare
def computeSquareOfSum():
squareOfSum = 0
for i in range(1, 51):
squareOfSum = squareOfSum + 101
squareOfSum = squareOfSum * squareOfSum
return squareOfSum
if __name__ == "__main__":
measureTimeToSumOfSquare = time.time()
result_Func_SumOfSquare = computeSumOfSquare()
print("function sumOfSquare execution time : ", time.time() - measureTimeToSumOfSquare)
print("sum of square(from 1 to 100) : ",result_Func_SumOfSquare)
measureTimeToSquareOfSum = time.time()
result_Func_SquareOfSum = computeSquareOfSum()
print("function squareOfSum execution time : ", time.time() - measureTimeToSquareOfSum)
print("total execution time : ", time.time() - measureTimeToSumOfSquare)
print("square of sum(from 1 to 100) : ", result_Func_SquareOfSum)
print("differnece between each sum : ", result_Func_SquareOfSum - result_Func_SumOfSquare)
|
56d6438431c0455f6686dc3d10695847356e465a | stevensonmat2/code-class | /spelling.py | 267 | 3.90625 | 4 | word = input('write a word: ').lower()
if 'c' in word and 'ei' in word:
ei_pos = word.index('ei')
c_pos = word.index('c')
if c_pos < ei_pos:
print('pass')
elif 'ei' in word:
print('fail')
elif 'ie' in word:
print('pass')
|
89a72e3c16565e53a460d6e331a0004a4427b523 | masakiaota/kyoupuro | /practice/E_ABC/abc129_e/abc129_e.py | 3,499 | 3.515625 | 4 | # https://atcoder.jp/contests/abc129/tasks/abc129_e
# 桁DPの理解が深まる一問
# 詳しくはeditorial参照
import sys
read = sys.stdin.readline
ra = range
enu = enumerate
class ModInt:
def __init__(self, x, MOD=10 ** 9 + 7):
'''
pypyじゃないと地獄みたいな遅さなので注意
'''
self.mod = MOD
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
if isinstance(other, ModInt):
return ModInt(self.x + other.x, self.mod)
else:
return ModInt(self.x + other, self.mod)
def __sub__(self, other):
if isinstance(other, ModInt):
return ModInt(self.x - other.x, self.mod)
else:
return ModInt(self.x - other, self.mod)
def __mul__(self, other):
if isinstance(other, ModInt):
return ModInt(self.x * other.x, self.mod)
else:
return ModInt(self.x * other, self.mod)
def __truediv__(self, other):
if isinstance(other, ModInt):
return ModInt(self.x * pow(other.x, self.mod - 2, self.mod), self.mod)
else:
return ModInt(self.x * pow(other, self.mod - 2, self.mod), self.mod)
def __pow__(self, other):
if isinstance(other, ModInt):
return ModInt(pow(self.x, other.x, self.mod), self.mod)
else:
return ModInt(pow(self.x, other, self.mod), self.mod)
__radd__ = __add__
def __rsub__(self, other): # 演算の順序が逆
if isinstance(other, ModInt):
return ModInt(other.x - self.x, self.mod)
else:
return ModInt(other - self.x, self.mod)
__rmul__ = __mul__
def __rtruediv__(self, other):
if isinstance(other, ModInt):
return ModInt(other.x * pow(self.x, self.mod - 2, self.mod), self.mod)
else:
return ModInt(other * pow(self.x, self.mod - 2, self.mod), self.mod)
def __rpow__(self, other):
if isinstance(other, ModInt):
return ModInt(pow(other.x, self.x, self.mod), self.mod)
else:
return ModInt(pow(other, self.x, self.mod), self.mod)
MOD = 10 ** 9 + 7
L = read()[:-1]
n = len(L)
# a+bの各桁についてDPで組み合わせの総和を数え上げる
# dp[i][j]...上位[0,i)桁まで見たときのa,bの組み合わせの総数。j=0→L[:i]まで一致している場合の通り数、j=1→未満が確定している状態の通り数
dp = [[0] * 2 for _ in ra(n + 1)]
dp[0][0] = ModInt(1)
for i in ra(n):
# i桁目が0の場合→a+bのi桁目はどちらも必ず0となるはず(通りの数は増えない)
if L[i] == '0':
# 未満の状態は未満の状態に
# ちょうどの状態もちょうどの状態に遷移する
dp[i + 1][0] += dp[i][0]
dp[i + 1][1] += dp[i][1]
else:
# ちょうどの数も未満に遷移する
dp[i + 1][1] += dp[i][0] + dp[i][1]
# i桁目が1の場合→a+bのi桁目はどちらかが1となるはず(通りの数2倍になる)
if L[i] == '0':
# 未満は未満のままだけど
# ちょうどだった状態は超えてしまう虚無に帰す
dp[i + 1][1] += dp[i][1] * 2
else:
# 未満は未満のままで、ちょうどはちょうどのまま
dp[i + 1][0] += dp[i][0] * 2
dp[i + 1][1] += dp[i][1] * 2
print(dp[-1][0] + dp[-1][1])
|
3cb83fc01ddbf2c347a0ed8a7214733c2229b77b | juny02/python-and-structure | /BST/BTS.py | 3,283 | 3.8125 | 4 | from treenode import TreeNode
class BTS:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def preorder_traverse(self, cur, func):
if not cur:
return
func(cur)
self.preorder_traverse(cur.left, func)
self.preorder_traverse(cur.right, func)
def inorder_traverse(self, cur, func):
if not cur:
return
self.inorder_traverse(cur.left, func)
func(cur)
self.inorder_traverse(cur.right, func) #탐색
#편의 함수
#cur의 왼쪽 자식을 (입력받은)left로 만든다
def __make_left(self,cur,left):
cur.left=left
if left: #논이면, 이런거 설정할 필요 없으니까 !
left.parent = cur
#cur의 오른쪽 자식을 입력받은 애로 만든다
def __make_right(self,cur, right):
cur.right=right
if right:
right.parent=cur
def insert(self, key):
'''
부모에서 쭉 크기 비교하면서 빈자리찾아서 감
(만난거랑 넣을거랑 비교햇을때, 넣을게 크면 오른쪽으로, 작으면 왼쪽으로감 )
'''
new=TreeNode(key)
cur=self.root()
if not cur:
self.root=new
return
while True:
parent=cur
if cur.key>key:
cur=cur.left
if not cur:
self.__make_left(parent, new)
return
else:
cur=cur.right
if not cur:
self.__make_right(parent, new)
return
def search(self, target): #이진탐색과 같은 알고리즘. 한번 탐색하면 그반대방향애들과는 탐색할 필요가 없어짐 !
cur=self.root
while cur:
if cur.key==target:
return cur
elif cur.key<target:
cur=cur.right
else:
cur=cur.left
return cur #못찾으면 cur이 끝까지 = None까지 가므로 이런 설정 해둔 것
def __delete_recursion(self, cur, target):
if not cur:
return None #cur끝까지 갓는데 target값없이 그냥 none까지 간 경우/ 걍 시작노드(cur)에 none이 제시된 경우
elif cur.key>target:
new_left=self.__delete_recursion(cur.left,target)
def min(self, cur):
while cur.left != None: #굿아이디어
cur=cur.left
return cur
def max(self,cur):
while cur.right !=None:
cur.right
return cur
def prev(self, cur): #해당 노드의 키보다 하나 작은거 찾는 함수
if cur.left:
return self.max(cur.left)
parent=cur.parent
while parent and parent.left==cur: #parent가 none일 수도 있으므로 !!
cur=parent
parent=parent.parent
return parent
def next(self, cur): #해당노드의 키보다 하나 큰 노드 찾는 함수
if cur.right:
return self.min(cur.right)
parent=cur.parent
while parent and parent.right==cur:
cur=parent
parent=parent.parent
return parent
|
4ff5a49dd85379d00161f5887ac7744fef7c4141 | aeasyo/python-learning | /py.project/神经网络处理房价数据.py | 3,234 | 3.625 | 4 | #import…as是一种导入库的方法
import numpy as np
# 定义存储输入数据x和目标数据y的数组
x, y = [], []
for sample in open("E:\_Data\prices3.txt", "r"):
x.append([float(sample.split(",")[0]),float(sample.split(",")[1])])
y.append(float(sample.split(",")[2]))
x, y = np.array(x), np.array(y)
# sigmoid激活函数定义
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义损失函数
def get_cost(input_x, input_y):
return 0.5 * ((input_x - input_y) ** 2)
#计算采用get_model 模型处理输入input_x得到的预测结果,与真实结果input_y,损失函数结果。
class NeuralNetwork():
def __init__(self):
self.w1 = np.random.normal()
self.w2 = np.random.normal()
self.w3 = np.random.normal()
self.w4 = np.random.normal()
self.w5 = np.random.normal()
self.w6 = np.random.normal()
self.b1 = np.random.normal()
self.b2 = np.random.normal()
self.b3 = np.random.normal()
def forward(self,x):
outh1=sigmoid(self.w1 * x[0] + self.w2 * x[1] +self.b1)
outh2=sigmoid(self.w3 * x[0] + self.w4 * x[1] +self.b2)
outh3=sigmoid(self.w5 * outh1 + self.w6 * outh2 + self.b3)
return outh3
def train(self, data, y):
learn_rate = 0.1
epochs = 100 # number of times to loop through the entire dataset
for epoch in range(epochs):
for x, y_trues in zip(data, y):
# 神经网络的前向(前馈)计算
h1 = self.w1 * x[0] + self.w2 * x[1] +self.b1
h2 = self.w3 * x[0] + self.w4 * x[1] +self.b2
outh1=sigmoid(h1)
outh2=sigmoid(h2)
h3 = self.w5 * outh1 + self.w6 * outh2 +self.b3
outh3=sigmoid(h3)
#梯度计算式子
d_E_outh3= (outh3 - y_trues)
d_outh3_h3= outh3 * (1-outh3)
d_outh1_h1= outh1 * (1-outh1)
d_outh2_h2= outh2 * (1-outh2)
#反向传播,调整权值
self.w5 -=learn_rate *d_E_outh3*d_outh3_h3*outh1
self.w6 -=learn_rate *d_E_outh3*d_outh3_h3*outh2
self.b3 -=learn_rate *d_E_outh3*d_outh3_h3
self.w1 -=learn_rate *d_E_outh3*d_outh3_h3*self.w5 * d_outh1_h1 * x[0]
self.w2 -=learn_rate *d_E_outh3*d_outh3_h3*self.w5 * d_outh1_h1 * x[1]
self.b1 -=learn_rate *d_E_outh3*d_outh3_h3*self.w5 * d_outh1_h1
self.w3 -=learn_rate *d_E_outh3*d_outh3_h3*self.w6 * d_outh2_h2 * x[0]
self.w4 -=learn_rate *d_E_outh3*d_outh3_h3*self.w6 * d_outh2_h2 * x[1]
self.b2 -=learn_rate *d_E_outh3*d_outh3_h3*self.w6 * d_outh2_h2
if epoch % 10 == 0:
loss = 0
for i, yy in zip(data, y):
y_preds = self.forward(i)
loss+= get_cost(y_preds,yy)
print("Epoch %d loss: %.3f", (epoch, loss))
network = NeuralNetwork()
network.train(x, y)
|
cf21c44e854ee9be64892012e3d6d72c9884c8ad | asenath247/COM404 | /windows-layouts/4-images/2-swapping.py | 1,965 | 3.546875 | 4 | from tkinter import *
class Gui(Tk):
def __init__(self):
super().__init__()
# load resources
self.cactusleaves_image = PhotoImage(file="U:/Problem Solving/COM404/windows-layouts/4-images/cactusleaves.gif")
self.palmtree_image = PhotoImage(file="U:/Problem Solving/COM404/windows-layouts/4-images/palmtree.gif")
# set window attributes
self.title("Gui")
# add components
self.__add_heading_label()
self.__add_cactusleaves_image()
self.__add_flip_button()
def __add_heading_label(self):
# create
self.heading_label = Label()
self.heading_label.grid(row=0, column=0, columnspan=2)
# style
self.heading_label.configure(text="Cactus Leaves" , font="Arial 37")
def __add_cactusleaves_image(self):
# create
self.cactusleaves_label = Label()
self.cactusleaves_label.grid(row=1, column=0)
self.cactusleaves_label.configure(image=self.cactusleaves_image, height=480, width=480)
def __add_palmtree_image(self):
# create
self.palmtree_label = Label()
self.palmtree_label.grid(row=1, colmun=0)
self.palmtree_label.configure(image=self.palmtree_image, height=360, width=360)
def __add_flip_button(self):
# create
self.flip_button = Button()
self.flip_button.grid(row=3, column=0)
self.flip_button.configure(text="Flip.")
self.flip_button.bind("<ButtonRelease-1>", self.__flip_button_clicked)
self.flip_button.bind("<ButtonRelease-3>", self.__flip_button_clickedright)
# events
def __flip_button_clicked(self, event):
self.cactusleaves_label.configure(image = self.palmtree_image)
def __flip_button_clickedright(self, event):
self.cactusleaves_label.configure(image = self.cactusleaves_image)
if (__name__ == "__main__"):
gui = Gui()
gui.mainloop() |
5049410b8b6f2276b69ee3d5815a7bb73276eceb | Mayur710/calendar | /exercise 12.py | 260 | 4.21875 | 4 | """Q)Write a Python program to print the calendar of a given month and year.
Note : Use 'calendar' module"""
import calendar
year = int(input("Please enter your year: "))
month = int(input("Please enter your month: "))
print(calendar.month(year, month))
|
1aadd4f7f24f7dff07b175f22e15a8515d7dc4c1 | mtgsjr/Machine_Learning | /prog02.py | 705 | 3.59375 | 4 | import cv2 # Importa o OpenCV
captura = cv2.VideoCapture(0) # liga a webcam
while(1): # Enquanto verdade
ret,frame = captura.read()
(b, g, r) = frame[200, 200]
frame[198:202, 198:202] = (0, 0, 255)
frame[10:90, 10:90] = (b, g, r)
cv2.imshow('Hello World!',frame)
k = cv2.waitKey(30) & 0xff # 'k' recebe o valor da tecla
if k == 27: # Se teclar ESC
break # Quebra o laco e sai
captura.release() # desliga a webcam
cv2.destroyAllWindows() # fecha a janela
|
a2cc1f90ce3cf700960b370d2dd7bd666edc059f | hujianli94/Python-code | /14.Python高阶学习(包和模块)/导入和使用标准模块和三方模块/random随机数模块.py | 737 | 3.71875 | 4 | #!/usr/bin/env python
#-*- coding:utf8 -*-
import random
#取 10 ~20 之间的3个随机数
for i in range(3):
a = random.randrange(10,20)
print(a,end=" ")
if __name__ == '__main__':
checkcode = '' #保存验证码的变量
for i in range(4):
index = random.randrange(0,4) #生成一个0~3中的一个数
if index != i and index +1 !=i:
checkcode += chr(random.randint(97, 122)) #生成A~Z中的一个小写字母
elif index +1 ==i:
checkcode += chr(random.randint(65, 90)) #生成A~Z中的一个大写字母
else:
checkcode += str(random.randint(1, 9)) #生成1~9中的一个数字
print(checkcode) |
5b7b24ad75d9caca83888935266565992ddb4826 | MitchellK/cp1404practicals | /prac_02/exceptions_demo.py | 1,031 | 4.4375 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
- When a numerator or denominator that is not a number is entered. Such as an 'A' or an '!'
2. When will a ZeroDivisionError occur?
- when you enter the denominator as 0.
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
- adding a while loop to warn and ask the user for a valid number
- we could do the same for numerator
- we could also offer the user an end choice within the while loop if they don't want to continue
"""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
denominator = int(input("Dividing by zero is dangerous!! Please enter any other number"))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.") |
5446081831c9e3b3ea2431af36b1fbafb79f86e4 | BrianARuff/Python-Code | /99 bottles song.py | 398 | 3.90625 | 4 | for i in range(99,0,-1):
if i == 1:
print(i, "bottle of beer on the wall", i, "bottle of beer.")
print("Take one down, pass it around.\n")
print(i-1, "bottles of beer on the wall.")
print("Now go home and don't drive while drunk.")
else:
print(i, "bottles of beer on the wall", i, "bottles of beer.")
print("Take one down, pass it around\n")
|
873163f952e1f1b9d6677c8a499f5759b574f838 | XyK0907/for_work | /LeetCode/HashTable/560_subarray_sum_equals_k.py | 633 | 3.515625 | 4 | class Solution(object):
def subarraySum(self, nums, k): #mei zuo chu lai
"""
time O(n)
space O(n)
前缀和 + 哈希表优化
:type nums: List[int]
:type k: int
:rtype: int
"""
dic = {0:1}
sum, res = 0, 0
for each in nums:
sum += each
if (sum - k) in dic:
res += dic[sum - k]
dic[sum] = dic.get(sum, 0) + 1
return res
if __name__ == '__main__':
solution = Solution()
print(solution.subarraySum(nums = [1,1,1], k = 2))
print(solution.subarraySum(nums = [1,2,3], k = 3)) |
25e33f22e3027ed4b95e60fba400dcee95c47029 | Kunal352000/python_program | /delete.py | 244 | 4.0625 | 4 | from array import*
arr1=[1,2,3,4],[5,6,7,8]
print("before delting the elements.")
print(arr1)
del(arr1[0][1])
#del(arr1[1])
print("After delting the elements.")
for i in arr1:
for x in i:
print(x,end=" ")
print()
|
bc67338b2a5b8d8d2b44ac8a29c6575061bac9b8 | therexone/sem4-uni | /OSTL/exp3-lists.py | 7,879 | 4.59375 | 5 | # menu driven program to illustrate use of list
print("-----------List Demo Program----------")
even_list = []
odd_list = []
merged_list = []
raw_list = []
choice = ''
def parity(n):
return True if n % 2 == 0 else False
def add_integer_to_list(val):
even_list.append(int(val)) if (val.isdigit() and parity(int(val))) else (
odd_list.append(int(val)) if (val.isdigit() and not parity(int(val))) else 'false')
def minimum_integer():
return min(odd_list) if min(odd_list) < min(
even_list) else min(even_list)
def maximum_integer():
return max(odd_list) if max(odd_list) > max(
even_list) else max(even_list)
def add_integer_at_index(index, element):
even_list.insert(index, int(element)) if (element.isdigit() and parity(int(element))) else (
odd_list.insert(index, int(element)) if (element.isdigit() and not parity(int(element))) else 'false')
while choice != 9:
print("1. Enter an element\n2. View Lists\n3. Merge Lists\n4. Sort List")
print("5. Minimum element\n6. Maximum element\n7. Update element\n8. Search for 'Python'\n9. Press 9 to exit")
choice = int(input())
print('-----------------------------------------')
if choice == 1:
val = input('Enter element to add to list: ')
raw_list.append(val)
print('Added to list: ', val)
add_integer_to_list(val)
elif choice == 2:
print('Raw List', raw_list)
print('Odd List', odd_list)
print('Even List', even_list)
print('Merged List', merged_list)
print()
elif choice == 3:
merged_list = list(set(odd_list + even_list))
print('Merged List: ', merged_list)
elif choice == 4:
merged_list.sort()
print('Sorted List: ', merged_list)
elif choice == 5:
minum = minimum_integer()
print('Minumum number is ', minum)
elif choice == 6:
maxum = maximum_integer()
print('Maximum Number is: ', maxum)
elif choice == 7:
index = int(input('Enter index to update: '))
if len(raw_list) > index:
element = (input('Enter element to update: '))
raw_list.append(element)
add_integer_at_index(index, element)
else:
print('Index out of Range')
elif choice == 8:
print('Found Python!' if 'python' or 'Python' in raw_list else 'Could not find Python!')
#---------------OUTPUT--------------------
# student@ubuntu~/Desktop/workspace/sem4-uni/OSTL$ python3 lists.py
# -----------List Demo Program----------
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 1
# Added to list: 1
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 2
# Added to list: 2
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 3
# Added to list: 3
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 4
# Added to list: 4
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 5
# Added to list: 5
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: 6
# Added to list: 6
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 2
# -----------------------------------------
# Raw List ['1', '2', '3', '4', '5', '6']
# Odd List [1, 3, 5]
# Even List [2, 4, 6]
# Merged List []
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 3
# -----------------------------------------
# Merged List: [1, 2, 3, 4, 5, 6]
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 4
# -----------------------------------------
# Sorted List: [1, 2, 3, 4, 5, 6]
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 5
# -----------------------------------------
# Minumum number is 1
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 6
# -----------------------------------------
# Maximum Number is: 6
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 7
# -----------------------------------------
# Enter index to update: 2
# Enter element to update: 18
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 2
# -----------------------------------------
# Raw List ['1', '2', '3', '4', '5', '6', '18']
# Odd List [1, 3, 5]
# Even List [2, 4, 18, 6]
# Merged List [1, 2, 3, 4, 5, 6]
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 3
# -----------------------------------------
# Merged List: [1, 2, 3, 4, 5, 6, 18]
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: "John"
# Added to list: "John"
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: "cena"
# Added to list: "cena"
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 1
# -----------------------------------------
# Enter element to add to list: "Python"
# Added to list: "Python"
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 8
# -----------------------------------------
# Found Python!
# 1. Enter an element
# 2. View Lists
# 3. Merge Lists
# 4. Sort List
# 5. Minimum element
# 6. Maximum element
# 7. Update element
# 8. Search for 'Python'
# 9. Press 9 to exit
# 9
# ----------------------------------------- |
07e143023cd029ecdfc4cb89d3cd0be4c26554f9 | robintux/Python-ML | /scikit-learn/Examples/Feature_Selection.py | 2,886 | 3.875 | 4 | # Feature Selection for Machine Learning
# http://machinelearningmastery.com/feature-selection-machine-learning-python/
# This section lists 4 feature selection recipes for machine learning in Python
# 1. Univariate Selection
# Feature Extraction with Univariate Statistical Tests (Chi-squared for classification)
import pandas
import numpy
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
# load data
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
# feature extraction
test = SelectKBest(score_func=chi2, k=4)
fit = test.fit(X, Y)
# summarize scores
numpy.set_printoptions(precision=3)
print(fit.scores_)
features = fit.transform(X)
# summarize selected features
print(features[0:5,:])
# 2. Recursive Feature Elimination
# Feature Extraction with RFE
from pandas import read_csv
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
# load data
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
# feature extraction
model = LogisticRegression()
rfe = RFE(model, 3)
fit = rfe.fit(X, Y)
print("Num Features: %d") % fit.n_features_
print("Selected Features: %s") % fit.support_
print("Feature Ranking: %s") % fit.ranking_
# 3. Principal Component Analysis
# Feature Extraction with PCA
import numpy
from pandas import read_csv
from sklearn.decomposition import PCA
# load data
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
# feature extraction
pca = PCA(n_components=3)
fit = pca.fit(X)
# summarize components
print("Explained Variance: %s") % fit.explained_variance_ratio_
print(fit.components_)
# 4. Feature Importance
# Feature Importance with Extra Trees Classifier
from pandas import read_csv
from sklearn.ensemble import ExtraTreesClassifier
# load data
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
# feature extraction
model = ExtraTreesClassifier()
model.fit(X, Y)
print(model.feature_importances_)
|
158fe369db68b828c1b7857966ac8011609a4cdb | acidjackcat/codeCampPython | /Training scripts/lesson8_classes.py | 1,264 | 3.9375 | 4 | class Animate:
pass
class Animals(Animate):
def breathe(self):
print('Breath')
def move(self):
print('Move')
def eat_food(self):
print('Eat')
class Mammals(Animals):
def feed_young_with_milk(self):
print('Feed youngs with milk')
class Giraffes(Mammals):
def __init__(self, spots):
self.giraffe_spots = spots
def eat_leaves_from_trees(self):
self.eat_food()
print('Eat leaves from the trees')
def find_food(self):
self.move()
print('I\'ve found food')
self.eat_food()
def left_foot_forward(self):
print('Left foot forward!')
def left_foot_back(self):
print('left foot back!')
def right_foot_forward(self):
print('right foot forward!')
def right_foot_back(self):
print('right foot back!')
def dance_a_jig(self):
self.right_foot_forward()
self.left_foot_forward()
self.right_foot_back()
self.left_foot_back()
ozwald = Giraffes(100)
gertrude = Giraffes(150)
reginald = Giraffes(50)
harold = Giraffes(10)
reginald.move()
reginald.eat_leaves_from_trees()
harold.move()
reginald.dance_a_jig()
reginald.dance_a_jig()
reginald.find_food()
reginald.eat_food()
|
69ea4fb8bca69db935b8f1d6cc7eb83540d9a1fd | armohamm/studyingPython | /Exercise 2/Exercise2.py | 169 | 4.125 | 4 | number = input("Enter a number: ")
rest = int(number) % 2
if rest > 0:
print(str(number) + " is an odd number.")
else:
print(str(number) + " is an even number.") |
9b49241b472f933c9ef226466ab1f7ffe6b401b9 | waldisjr/JuniorIT | /_2019_2020/Homeworks/_9_ hw_on_09_11_2019/_1.py | 233 | 3.578125 | 4 | str1 = input('Enter string: ')
new = ''
t = 0
while t + 2 < len(str1):
if str1[t].islower() and str1[t+1].isupper() and str1[t+2].islower():
new = new + ' ' + str1[t] + str1[t+1] + str1[t+2]
t += 1
print(new)
|
ed08df05ccc35b794ff1f96df12b6edff8b72d4c | vitkhab/Project-Euler | /0045/solution.py | 1,116 | 3.96875 | 4 | #!/usr/bin/env python
from time import time
from math import sqrt
def hexagonal(n):
return n * (2 * n - 1)
def is_natural_number(n):
return n % 1.0 == 0 and n > 0
def solve_quadratic_equation(a, b, c):
root1 = (-1.0 * b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
root2 = (-1.0 * b - sqrt(b**2 - 4.0 * a * c)) / (2.0 * a)
return root1, root2
def is_triangle(n):
(r1, r2) = solve_quadratic_equation(1, 1, -2 * n)
if is_natural_number(r1) or is_natural_number(r2):
return True
return False
def is_pentagonal(n):
(r1, r2) = solve_quadratic_equation(3, -1, -2 * n)
if is_natural_number(r1) or is_natural_number(r2):
return True
return False
def is_solution(n):
if is_pentagonal(n) and is_triangle(n):
return True
return False
def find_solution():
n = 144
solution = 3
while not is_solution(solution):
n += 1
solution = hexagonal(n)
return solution
def main():
start = time()
print "Answer: %d" % find_solution()
print "Time: %f" % (time() - start)
if __name__ == "__main__":
main() |
3c9ed75dbe304b16f373aab43ad2540dcc482a7d | vinaynayak2000/Email_Slicer | /Email_slicer.py | 222 | 3.8125 | 4 | try:
u=input("Enter Email : ").strip()
email=u.split('@')
username=email[0]
domain=email[1]
print("Your USERNAME is",username,"and your DOMAIN is",domain)
except:
print("Enter Valid Email")
|
c5d33fa71ba3f7f83cce310f9d22781370566875 | HenriqueRenda/CIFOProject | /charles/mutation.py | 996 | 3.765625 | 4 | from random import randint, uniform, sample
def random_mutation(individual, mutation_rate):
"""[summary]
Args:
individual ([type]): [description]
Returns:
[type]: [description]
"""
for i in range(len(individual)):
if(uniform(0, 1)<mutation_rate):
individual[i] = uniform(-1, 1)
return individual
def swap_mutation(individual):
#Get two mutation points
mut_points = sample(range(len(individual)),2)
#Rename to shorthen variable name
i = individual
i[mut_points[0]], i[mut_points[1]] = i[mut_points[1]], i[mut_points[0]]
return i
def inversion_mutation(individual):
i = individual
#position of the start and end of substring
mut_points = sample(range(len(i)), 2)
#This method assumes that the second point is after the first one
#sort the list
mut_points.sort()
#Invert for the mutation
i[mut_points[0]:mut_points[1]] = i[mut_points[0]:mut_points[1]][::-1]
return i |
b25ee6d11e83343ac29b7c13f1d9cdc0294a3001 | mlazza/estudos | /Studies/livro_Python/48_cubos.py | 163 | 3.8125 | 4 | #4.8 Cubos. Crie lista dos 10 primeiros cubos e laco for para exibir
lista = []
for cubo in range(1,11):
lista.append(cubo**3)
for cubo in lista:
print(cubo)
|
9ff7ca162e94d7948e9d179786ccfc23352db5df | ahemd1252005/cs50ide | /buildingblocks/pset7/houses/import.py | 2,028 | 4.4375 | 4 | # In import.py, write a program that imports data from a CSV spreadsheet.
import csv
import sys
import cs50
# Your program should accept the name of a CSV file as a command-line argument.
# Check for correct number of args.
if len(sys.argv) != 2:
print("Usage: python import.py data.csv")
sys.exit(1)
# Check for correct file type in args.
if not (sys.argv[1]).endswith('.csv'):
print("Usage: python import.py data.csv")
sys.exit(1)
# Reference SQL database saved in the same directory.
db = cs50.SQL("sqlite:///students.db")
with open(sys.argv[1], newline='') as csvDatabase:
if not csvDatabase:
print(f"Could not open {sys.argv[1]}.")
sys.exit(2)
# After making sure the CSV file will exist, confirm it has
# columns name, house, and birth.
reader = csv.DictReader(csvDatabase)
if not (reader.fieldnames == ["name","house","birth"]):
print("Invalid csv file.")
sys.exit(3)
# All good start running over the rows.
for row in reader:
# For each student in the CSV file, insert the student into the students table in the students.db database.
# While the CSV file provided to you has just a name column,
# the database has separate columns for first, middle, and last names.
name = [0,0,0]
name, house, birth = row["name"].split(" "), row["house"], row["birth"]
# For students without a middle name, you should leave their middle name field as NULL in the table.
if len(name) == 3:
# has three names.
first, middle, last = name[0], name[1], name[2]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", first, middle, last, house, birth)
else:
# Set middle name as NULL use name[1] as last name
first, last = name[0], name[1]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, NULL, ?, ?, ?)", first, last, house, birth)
csvDatabase.close() |
fc3fce8b730dd7224bedd0784ae5c4719fdc810f | Nikikapralov/Advent-of-Code-2020 | /Day_4_Task_1.py | 745 | 3.765625 | 4 | import re
pattern = r'\b\w+|\W+'
passport = ''
all_passports = []
valid_passports = []
def is_passport_valid(passport):
if 'byr' in passport and 'iyr' in passport and 'eyr' in passport and 'hgt' in passport and 'hcl' in passport and 'ecl' in passport and 'pid' in passport:
return True
else:
return False
while True:
data = input()
if data and data != 'Stop':
passport += data + ' '
elif data == 'Stop':
all_passports.append(passport)
break
else:
all_passports.append(passport)
passport = ''
for item in all_passports:
result = re.findall(pattern, item)
if is_passport_valid(result):
valid_passports.append(result)
print(len(valid_passports))
|
155bede2552d0f71e0c361261ea5dba964eb0c2e | ivanwakeup/algorithms | /algorithms/prep/ctci/1.3_is_str_permutat_of_palin.py | 740 | 4.21875 | 4 | '''
need to check if a string is a permutation of a palindrome
examples:
"baa" = yes
"aabb" = yes
"aabab" = yes
if strlen is even, all characters must appear even number of times
if strlen is odd, all chars must appear even num of times except 1
approaches:
1. could sort the string, and keep track of the number of times an odd character appears
2. could use a set, adding/removing as we traverse the string and ensure the set only contains 1 character if strlen is odd, or none if even
'''
def is_palindrome_permutation(s):
seen = set()
for char in s:
if char not in seen:
seen.add(char)
else:
seen.remove(char)
return len(seen) <= 1
print(is_palindrome_permutation("tact coa")) |
5c70309cb6fa1eadfd3a56e8dd41ef35f54fb118 | BryanYunche/Python-Exercicios-Basicos | /carrinho_de_compra.py | 1,264 | 4.125 | 4 | #Exercício Python 70: Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
#A) qual é o total gasto na compra.
#B) quantos produtos custam mais de R$1000.
#C) qual é o nome do produto mais barato.
#inicio da variavel de soma dos produtos
soma = prod = 0
#Constante
mil = 1000
nome = str(input('Digite o nome do produto: '))
val = float(input('Digite o valor do produto: '))
menor = val
while True:
#Faz o ususário ter que digitar S ou N
while True:
cont = str(input('Deseja continuar? [S/N]: ')).upper()
if cont == 'N':
break
if cont == 'S':
break
#termina o programa
if cont == 'N':
break
#Entrada de dados
nome = str(input('Digite o nome do produto: '))
val = float(input('Digite o valor do produto: '))
#Soma do preço dos produtos
soma = soma + val
#Calcula quantos produtos custa mais que R$1000
if val > mil:
prod = prod + 1
#Nome do menor preço
if val < menor:
menor = val
nomeMenor = nome
print('O total da compra foi: R${}'.format(soma))
print('{} produtos custaram mais de R$1000'.format(prod))
print('O menor produto foi {} que custa R${} .'.format(nomeMenor, menor)) |
3ef71d05d07110e0c914e33a4b7d2756cc6a1260 | Kestajon/MLP_NeuralNetwork | /AnnComp.py | 16,149 | 3.78125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import math
import sys
import csv
import pickle # Used to serialise Neural_Networks for later use
# ANN Neural Network Class, adapted from stephencwelch's code on GitHub
# https://github.com/stephencwelch/Neural-Networks-Demystified
#
# This Neural_Network class has a constant output layer sizes
# but variable hidden layer size, number of hidden layers and input
# layer size. The Neural_Network makes use of a activation function as its'
# activation function, and Sum Squared Error as its' cost function for
# training
#
# @author Jonathan Keslake
class NeuralNetwork(object):
# The passed in networkTopology describes the neural network,
# it is a list of integers, with the position of the integer
# representing the layer, and the integer representing the number
# of neurons in that layer
def __init__(self, networkTopology, inputNormalization, outputNormalization
, inverseNormalization, Lambda = 0):
# Define Network Topology
self.networkTopology = networkTopology
self.Lambda = Lambda
# Set normalization equations
self.inputNormalization = inputNormalization
self.outputNormalization = outputNormalization
self.inverseNormalization = inverseNormalization
# weightList contains a list of the weights for the system
self.weightList = []
for i in range(len(networkTopology)-1):
self.weightList.append(np.random.normal(0, self.networkTopology[i]**-0.5,
(self.networkTopology[i], self.networkTopology[i+1])))
# Activation function for the neural network
def activation(self, z):
# Apply activation activation function to scalar, vector, or matrix
return 1.7159*np.tanh((2.0/3)*z)
# Differential of the activation function
def activationPrime(self, z):
return 1.14393*(1.0 - np.tanh((2.0/3)*z)**2) # Check This calculation
# Compute costs from approximations and expected results, using the current state of the system
def cost(self, X, y):
X = self.inputNormalization(X)
y = self.outputNormalization(y)
weightSquareSum = 0
for i in nn.weightList:
weightSquareSum += np.sum(i**2)
return 0.5*sum((y-self.costPredict(X))**2)/X.shape[0] + (self.Lambda/2)*weightSquareSum
# Function that calculates the target from normalised data, used within the class, not for
# use by users of the class
def costPredict(self, X):
preWeight = X
for weight in self.weightList:
# Inputs to the layer are combinations of the preWeights
# and the weights
layerInput= np.dot(preWeight, weight)
# preWeight for next layer is the layerInput passed
# through the activation function
preWeight = self.activation(layerInput)
# At the end of the loop, the preWeight will contain the Y values
return preWeight
# Function to obtain the current layer z, and the previous layers a
# Specialised for use in the costFunctionPrime function
def forward(self, X, layerToReach):
# Set up the 1st layer (input -> 1st Hidden)
previousA = X
layerZ = np.dot(previousA, self.weightList[0])
# Only run if the layerToReach does not equal 0
# If it runs through the whole network layerZ will equal yHat
for j in range(layerToReach):
previousA = self.activation(layerZ)
layerZ = np.dot(previousA, self.weightList[j+1])
# Return
return layerZ, previousA
# Function to calculate the dJdW in order to update the individual layer weights
def costFunctionPrime(self, X, y):
#Generate final layer z (input to final layer) and output of previous
layerZ, previousA = self.forward(X, len(self.networkTopology)-2)
#yHat is the activation of the input to the final layer
yHat = self.activation(layerZ)
#Final delta
delta = np.multiply(-(y-yHat), self.activationPrime(layerZ))
# dJdW list instantiation
dJdW = [0]*(len(self.networkTopology)-1)
# Set final dJdW from previous, iterate over next for subsequent
dJdW[len(self.networkTopology)-2] = np.dot(previousA.T,delta) + self.Lambda*self.weightList[
len(self.networkTopology)-2]
for i in range(len(self.networkTopology)-3, -1, -1):
layerZ, previousA = self.forward(X, i)
delta = np.dot(delta, self.weightList[i+1].T) * self.activationPrime(layerZ)
dJdW[i] = np.dot(previousA.T,delta) + self.Lambda*self.weightList[i]
return dJdW
# Function for training the network using a batch back-propagation method
def backPropogationTraining(self, X, y, validX, validY, learningRate=0.2, epochs=30):
X = self.inputNormalization(X)
y = self.outputNormalization(y)
validX = self.inputNormalization(validX)
validY = self.outputNormalization(validY)
trainingCost = []
validationCost = []
trainingCostNL = []
validationCostNL = []
for i in range(epochs):
trainingCost.append(self.t_cost(X, y))
validationCost.append(self.t_cost(validX, validY))
trainingCostNL.append(self.nl_cost(X, y))
validationCostNL.append(self.nl_cost(validX, validY))
dJdW = self.costFunctionPrime(X,y)
for j in range(len(dJdW)):
self.weightList[j] = self.weightList[j] - learningRate*dJdW[j]
return trainingCost, validationCost, trainingCostNL, validationCostNL
# Function used to obtain the networks predictions for input X
def predict(self, X):
preWeight = self.inputNormalization(X)
for weight in self.weightList:
# Inputs to the layer are combinations of the preWeights
# and the weights
layerInput= np.dot(preWeight, weight)
# preWeight for next layer is the layerInput passed
# through the activation function
preWeight = self.activation(layerInput)
# At the end of the loop, the preWeight will contain the Y values
return self.inverseNormalization(preWeight)
# Cost function associated with the system, with the lambda generalisation term
def t_cost(self, X, y):
# Compute cost for given X,y, use weights already stored in class.
weightSquareSum = 0
for i in nn.weightList:
weightSquareSum += np.sum(i**2)
return 0.5*sum((y-self.costPredict(X))**2)/X.shape[0] + (self.Lambda/2)*weightSquareSum
# Cost function associated with the system, without the lambda generalisation term
def nl_cost(self, X, y):
return 0.5*sum((y-self.costPredict(X))**2)
# Function for training the network using a stochastic back-propagation method
def stochastic(self, X, y, validX, validY, learningRate=0.2, epochs=15):
X = self.inputNormalization(X)
y = self.outputNormalization(y)
validX = self.inputNormalization(validX)
validY = self.outputNormalization(validY)
trainingCost = []
validationCost = []
trainingCostNL = []
validationCostNL = []
# Add cost list so costs can be tracked over iterations
# Possibly also over index in indexList once for tracking purposes?
innerLayer = self.networkTopology[0]
outputLayer = self.networkTopology[len(self.networkTopology)-1]
indexList = np.arange(len(X))
if epochs >= 50:
spaces = 50
hashTime = int(epochs/spaces)
else:
spaces = epochs
hashTime = 1
print("Training Neural Network")
print("|" + "-"*spaces + "|")
sys.stdout.write(" ")
counter = 0
for i in range(epochs):
trainingCost.append(self.t_cost(X, y))
validationCost.append(self.t_cost(validX, validY))
trainingCostNL.append(self.nl_cost(X, y))
validationCostNL.append(self.nl_cost(validX, validY))
np.random.shuffle(indexList)
for index in indexList:
np.reshape(X[index], (1, innerLayer))
dJdW = self.costFunctionPrime(np.reshape(X[index], (1, innerLayer))
,np.reshape(y[index], (1, outputLayer)))
for j in range(len(dJdW)):
self.weightList[j] -= learningRate*dJdW[j]
# Handling Training Progress Bar
counter += 1
if counter >= hashTime:
sys.stdout.write ("#"*int((counter/hashTime)))
counter = 0
print("")
return trainingCost, validationCost, trainingCostNL, validationCostNL
# Load files from text as an np array
def loadFromFile(filename):
return np.genfromtxt(filename, delimiter=',')
# Function which instantiates an instance of the NeuralNetwork class shown above using the parameters
# passed in as keyword arguments. Loads the data from the "datao.csv" file, which is a manipulated
# version of the stock-market data. This function also takes care of the normalisation functions
# associated with the data and inputs them into the network, allowing raw data to be passed in to the
# system.
def loadData(inputLength = 1, outputPos = 5, trainingOffestFromBottom = 3, validationOffsetFromBottom = 3,
inputLambda = 0, hiddenLayers = [15]):
# Loading Training Data
# Assume the expected output is always the last element
X = loadFromFile("datao.csv")
tempX = np.array(X[0][:inputLength], ndmin=2)
tempy = np.array([X[0][outputPos]], ndmin=2)
close = np.array([X[0][outputPos + 1]], ndmin=2)
meanValue = np.zeros(inputLength + 1)
meanValue[:inputLength] = X[0][:inputLength]
meanValue[inputLength] = X[0][outputPos]
maxValue = np.copy(meanValue)
counter = 1
for i in range(1,len(X) - trainingOffestFromBottom):
tempX = np.append(tempX, np.array(X[i][:inputLength], ndmin=2), axis=0)
tempy = np.append(tempy, np.array(X[i][outputPos], ndmin=2), axis=0)
close = np.append(close, np.array(X[i][outputPos + 1], ndmin=2), axis=0)
# Retrieve the new row from the csv file
newRow = np.zeros(inputLength + 1)
newRow[:inputLength] = X[i][:inputLength]
newRow[inputLength] = X[i][outputPos]
# Add newRow to the average being counted
meanValue += newRow
for j in range(inputLength + 1):
if maxValue[j] < newRow[j]:
maxValue[j] = newRow[j]
if maxValue[j] < -1 * newRow[j]:
maxValue[j] = -1 * newRow[j]
counter += 1
# Calculate mean from average
meanValue /= counter
# Define the normalization functions to be used within the network
def inputNormalization(X):
return (X - meanValue[:inputLength]) / maxValue[:inputLength]
def outputNormalization(y):
return (y - meanValue[inputLength]) / maxValue[inputLength]
def inverseNormalization(y):
return y*maxValue[inputLength] + meanValue[inputLength]
nn = NeuralNetwork([inputLength] + hiddenLayers + [1], inputNormalization, outputNormalization
, inverseNormalization, Lambda=inputLambda)
# Loading Validation Data
X = loadFromFile("validation.csv")
validX = np.array(X[0][:inputLength], ndmin=2)
validy = np.array([X[0][outputPos]], ndmin=2)
validClose = np.array([X[0][outputPos + 1]], ndmin=2)
for i in range(1,len(X) - validationOffsetFromBottom):
validX = np.append(validX, np.array(X[i][:inputLength], ndmin=2), axis=0)
validy = np.append(validy, np.array(X[i][outputPos], ndmin=2), axis=0)
validClose = np.append(validClose, np.array(X[i][outputPos + 1], ndmin=2), axis=0)
return nn, tempX, tempy, validX, validy, close, validClose
# Statements used to carry out the learning rate tests within the report
'''
# Learning Rate Tests
plt.figure(1)
plt.xlabel('Epoch')
plt.ylabel('SSE Cost')
plt.grid(1)
learningRateTests = [0.01, 0.001, 0.0001]
for element in learningRateTests:
nn, X, y, validX, validy, close, validClose = loadData(inputLength=3, inputLambda=0.001, hiddenLayers=[6, 7, 4, 5, 2])
trainingCost, validationCost, trainingCostNL, validationCostNL = nn.stochastic(X, y, validX, validy, epochs=2000, learningRate=element)
plt.plot(validationCostNL, label='Topology = ' + str(element))
plt.legend()
plt.show()
'''
# Statements used to carry out the hidden layer tests within the report
'''
# Hidden Layer Tests
plt.figure(1)
plt.xlabel('Epoch')
plt.ylabel('SSE Cost')
plt.grid(1)
#plt.savefig('costPlot.png')
#hiddenLayerTests = [[0], [0.0005], [0.00075], [0.001], [0.00125]]
hiddenLayerTests = [[15], [6, 7, 4, 2], [10, 5, 3, 4], [8, 7, 4, 2], [6, 7, 4, 5, 2], [10, 5, 3, 4, 2], [10, 5, 3, 4, 2, 2,], [10, 5, 3, 4, 1]]
for element in hiddenLayerTests:
nn, X, y, validX, validy, close, validClose = loadData(inputLength=3, inputLambda=0.001, hiddenLayers=element)
trainingCost, validationCost, trainingCostNL, validationCostNL = nn.stochastic(X, y, validX, validy, epochs=600, learningRate=0.001)
legendString = '3, '
for i in element:
legendString += str(i) + ', '
legendString += ' 1'
plt.plot(validationCostNL, label='Topology = ' + legendString)
plt.legend()
plt.show()
'''
# Statements used to carry out the lambda tests within the report
'''
# Lambda Tests 96 88
plt.figure(1)
plt.xlabel('Epoch')
plt.ylabel('SSE Cost')
plt.grid(1)
#plt.savefig('costPlot.png')
lambdaTests = [0, 0.0005, 0.00075, 0.001, 0.00125]
for element in lambdaTests:
nn, X, y, validX, validy, close, validClose = loadData(inputLength=3, inputLambda=element)
trainingCost, validationCost, trainingCostNL, validationCostNL = nn.stochastic(X, y, validX, validy, epochs=400, learningRate=0.001)
plt.plot(validationCostNL, label='Lambda = ' + str(element))
plt.legend()
plt.show()
'''
# Statements used to carry out the input tests within the report
'''
# Input Tests
plt.figure(1)
plt.xlabel('Epoch')
plt.ylabel('SSE Cost')
plt.grid(1)
#plt.savefig('costPlot.png')
for i in range(1,6):
nn, X, y, validX, validy, close, validClose = loadData(inputLength=i)
trainingCost, validationCost, trainingCostNL, validationCostNL = nn.stochastic(X, y, validX, validy, epochs=250, learningRate=0.001)
plt.plot(validationCostNL, label='Number of Inputs = ' + str(i))
plt.legend()
plt.show()
'''
# Statements used to obtain the three graphs shown at the end of each test:
# Network instantiation using loadData function
nn, X, y, validX, validy, close, validClose = loadData(inputLength=3, inputLambda=0.001, hiddenLayers=[6, 7, 4, 5, 2])
# Call stochastic training method
trainingCost, validationCost, trainingCostNL, validationCostNL = nn.stochastic(X, y, validX, validy, epochs=200, learningRate=0.001)
# Validation Set Untreated
plt.plot(nn.predict(validX), label='Prediction')
plt.plot(validy, label = 'Actual')
plt.xlabel('Dataset Number')
plt.ylabel('(High/Close) - 1')
plt.grid(1)
plt.legend()
plt.savefig('valSetUn.png')
plt.show()
# Cost Plotting
plt.figure(1)
plt.plot(trainingCostNL, label='Training Data')
plt.plot(validationCostNL, label='Validation Data')
plt.xlabel('Epoch')
plt.ylabel('SSE Cost')
plt.grid(1)
plt.legend()
plt.savefig('costPlot.png')
plt.show()
# Prediction vs. Expected
totalX = np.concatenate((X, validX))
totaly = np.concatenate((y, validy))
totalClose = np.concatenate((close, validClose))
plotVals = (nn.predict(totalX) - totaly)*totalClose
some = np.absolute(plotVals)
mean = np.mean(some)
# Calculate standard deviation
stdv = 0
for x in some:
stdv += (x - mean)*(x - mean)
stdv = np.sqrt(stdv/some.size)
print(stdv)
print(mean)
plt.figure(1)
plt.plot(plotVals)
plt.xlabel('Dataset Number')
plt.ylabel('Prediction - Total')
plt.grid(1)
plt.savefig('predic_-_expec.png')
plt.show()
|
e76a4b56ed283fc900bac90ccfafe440d4e88b83 | NahshonSatat/KNN | /Point.py | 2,183 | 3.890625 | 4 | # 315823880- nahshon satat
import math
import doctest as doctest
class Point():
def __init__(self, x, gender, y):
self.x = float(x)
self.gender = int(gender)
self.y = float(y)
self.dis = float(0.0)
def pr(self):
print("First number = " + str(self.x))
print("Second number = " + str(self.y))
print("gender = " + str(self.gender))
print("the dis ="+str(self.dis))
def distance (self,index,point)-> float:
"""
:param index: to choose the correct equation
:param point: for to do distance between two points
:return:distance of correct equation
>>> x =Point(1,1,2)
>>> y =Point(7,1,6)
>>> x.distance(1,y)
10.0
>>> x.distance(2,y)
7.211102550927978
>>> x.distance(3,y)
6.0
"""
if (index==1):
sum = abs(self.x-point.x)+abs(self.y-point.y)
return sum
elif(index==2):
sum = math.pow(abs(self.x-point.x),2)+math.pow(abs(self.y-point.y),2)
sum = math.sqrt(sum)
return sum
else :
return max(abs(self.x - point.x), abs(self.y - point.y))
pass
#def sortbydis(point):
# return point.dis
if __name__ == '__main__':
# point = []
# with open('HC_Body_Temperature') as f:
# for line in f:
# a = line.strip().split()
# if a[1] == "2":
# a[1] = -1
# b = Point(a[0],a[1],a[2])
# point.append(b)
# length = len(point)
# random.shuffle(point)
# c = Point(5,1,3)
# d = Point(1,1,4)
# e = Point(9,1,7)
# c.dis = 5
# d.dis = 3
# e.dis = 4
#list = []
# list.append(c)
# list.append(d)
# list.append(e)
# list.sort(key=sortbydis)
# for i in list:
# i.pr()
(failures, tests) = doctest.testmod(report = True)
print("{} failures, {} tests".format(failures, tests)) |
62ad131c3d6874a06d354233d550f9c6d576ba4f | 3Juhwan/Python-Algorithm-Team-Notes | /Math/prime_number.py | 366 | 3.75 | 4 | import math
# 소수 판별 함수
def is_prime_number(x):
# 2부터 x의 제곱근까지
for i in range(2, int(math.sqrt(x)) + 1):
# x가 해당 수로 나눠떨어진다면
if x % i == 0:
return False # 소수가 아님
return True # 소수임
print(is_prime_number(4)) # False
print(is_prime_number(7)) # True |
87314bfed6e6735749e76b964b99ec3fada66328 | rapkeb/Data-Bases | /ass4/DB1/hw4.py | 1,644 | 3.953125 | 4 | import sqlite3
import csv # Use this to read the csv file
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
Parameters
----------
Connection
"""
pass
def update_employee_salaries(conn, increase):
"""
Parameters
----------
conn: Connection
increase: float
"""
pass
def get_employee_total_salary(conn):
"""
Parameters
----------
conn: Connection
Returns
-------
int
"""
pass
def get_total_projects_budget(conn):
"""
Parameters
----------
conn: Connection
Returns
-------
float
"""
pass
def calculate_income_from_parking(conn, year):
"""
Parameters
----------
conn: Connection
year: str
Returns
-------
float
"""
pass
def get_most_profitable_parking_areas(conn):
"""
Parameters
----------
conn: Connection
Returns
-------
list[tuple]
"""
pass
def get_number_of_distinct_cars_by_area(conn):
"""
Parameters
----------
conn: Connection
Returns
-------
list[tuple]
"""
pass
def add_employee(conn, eid, firstname, lastname, birthdate, street_name, number, door, city):
"""
Parameters
----------
conn: Connection
eid: int
firstname: str
lastname: str
birthdate: datetime
street_name: str
number: int
door: int
city: str
"""
pass
def load_neighborhoods(conn, csv_path):
"""
Parameters
----------
conn: Connection
csv_path: str
"""
pass |
9058db0b007fc924e8f632dc401b22fcd67137ce | saierding/leetcode-and-basic-algorithm | /leetcode/math and bit manipulation/Power of Two.py | 637 | 3.921875 | 4 | # 231. Power of Two
class Solution:
# 笨办法直接循环到这个数,用2的n次方去判断。
def isPowerOfTwo1(self, n):
i = 0
while i < n:
if 2 ** i == n:
return True
elif 2 ** i > n:
return False
i += 1
return False
# bit, 位方法,2的次方有特性,和比他小一个的数
# 位与得到0。n和n-1位与得到的就是0
def isPowerOfTwo(self, n):
if n < 1:
return False
if n & n-1 == 0:
return True
return False
s = Solution()
print(s.isPowerOfTwo(32)) |
d6a30247c5476506b965028ce8acee8196b5415b | SoenMC/Programacion | /Ejercicio42.py | 1,033 | 4.125 | 4 | ##Realizar un programa que lea los lados de n triángulos, e informar:
#a) De cada uno de ellos, qué tipo de triángulo es:
#equilátero (tres lados iguales), isósceles (dos lados iguales), o escaleno (ningún lado igual)
#b) Cantidad de triángulos de cada tipo.
cont1=0
cont2=0
cont3=0
n=int(input("Ingrese la cantidad de triangulos: "))
for f in range(n):
lado1=int(input("Ingrese el lado 1: "))
lado2=int(input("Ingrese el lado 2: "))
lado3=int(input("Ingrese el lado 3: "))
if lado1==lado2 and lado1==lado3:
print("Es un triangulo equilátero")
cont1=cont1+1
else:
if lado1==lado2 or lado1==lado3 or lado2==lado3:
print("Es un triangulo isósceles")
cont2=cont2+1
else:
print("Es un triangulo escaleno")
cont3=cont3+1
print(f"La cantidad de triangulos equiláteros es: {cont1}")
print(f"La cantidad de triangulos Isósceles es : {cont2}")
print(f"La cantidad de triangulos escalenos es: {cont3}") |
f4809e55ef3075e4e0d0b5ecf9b590fc53572671 | ScroogeZhang/Python | /day12 面向对象基础1/05-对象属性的增删改查.py | 2,676 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2018/7/31 13:53
# @Author :Hcy
# @Email : [email protected]
# @File : 05-对象属性的增删改查.py
# @Software : PyCharm
class Dog:
"""狗类"""
def __init__(self, age = 0, color = 'white'):
self.age = age
self.color = color
class Student:
def __init__(self, name='胡晨宇', sex='男', age='18'):
self.name = name
self.sex = sex
self.age = age
def study(self):
print('%s学习' % self.name)
if __name__ == '__main__':
# 1. 查(获取属性)
"""
方法一: 对象.属性(如果属性不存在,会报错)
方法二:对象.__getattribute__(属性名)和getattr(对象,属性名,默认值)
"""
dog1 = Dog(age=3, color='red')
print(dog1.age, dog1.color)
print(dog1.__getattribute__('age'))
print(getattr(dog1, 'age'))
#如果设置了default的值,那么当属性不存在的时候不会报错,并且返回默认值
print(getattr(dog1, 'abc', '无名氏'))
# 2. 改(修改属性的值)
"""
方法一:对象.属性 = 新值
方法二:对象.__setattr__(属性名,新值)和setattr(对象,属性名,默认值)
"""
dog1.age = 4
print(dog1.age)
dog1.__setattr__('color', 'black')
print(dog1.color)
setattr(dog1, 'color', 'blue')
print(dog1.color)
# 3.增加(增加对象属性)
"""
对象.属性 = 值(属性不存在)
注意:属性是添加给对象的,而不是类的
"""
dog1.name ='大黄'
print(dog1.name)
dog1.__setattr__('type', '哈士奇')
print(dog1.type)
setattr(dog1, 'sex', '公')
print(dog1.sex)
# 4.删(删除对象属性)
"""
方法一:del 对象.属性
注意:删除属性也是删的具体某个对象的属性。不会影响到这个类的其他对象
"""
# del dog1.age
# print(dog1.age)
dog1.__delattr__('age')
# print(dog1.age)
delattr(dog1, 'color')
# print(dog1.color)
# 练习:声明一个学生类,拥有属性:姓名,性别,年龄。方法:学习
# 声明学生类的对象,声明的时候就给姓名,性别和年龄赋值
# 通过三种方式分别获取姓名,性别和年龄,并且打印
# 给学生添加一个对象
# 修改学生的年龄
# 删除学生的性别
student1 = Student()
print(student1.name, student1.sex, student1.age)
print(student1.__getattribute__('name'))
print(getattr(student1, 'sex'))
student1.tel = '123456'
print(student1.tel)
student1.age = 22
del student1.sex
student1.study() |
45f4387cdf2ff3eb3cf4552f18f85bcd4b9496ec | pakruslan/Decorators | /tasksdecorator.py | 2,672 | 4.03125 | 4 | import time
from datetime import datetime
import functools
# 1. Напишите функцию say_whee, которая печатает «Whee!». Примените к этой функции
# декоратор, который будет запускать функцию say_whee только в течение дня (9:00 —
# 21:00), чтобы не беспокоить соседей.
# def data(fn):
# def wrapper():
# if 9 >= datetime.now().hour < 21:
# fn()
# else:
# print("Тише соседи спят")
# return wrapper
# @data
# def say_whee():
# print("WHEE!!!")
# say_whee()
# 2. Напишите декоратор, который может узнать время выполнения функции, к которой он
# применен.
# def timer(f):
# def tmp(*args, **kwargs):
# t = time.time()
# res = f(*args, **kwargs)
# print ("Время выполнения функции: %f" % (time.time()-t))
# return res
# return tmp
# @timer
# def func(x, y):
# return x + y
# func(1, 2)
# 3.
# def repeat(nbrTimes=4):
# def real_repeat(func):
# @functools.wraps(func)
# def wrapper_repeat(*args, **kwargs):
# nonlocal nbrTimes
# while nbrTimes != 0:
# nbrTimes -= 1
# func(*args, **kwargs)
# return wrapper_repeat
# return real_repeat
# @repeat(4)
# def display(x):
# print(x)
# display("Python")
# 4.
# users = {'Ruslan': 14365, 'Andriano': 234456, 'Miran': 345527}
# def decor(func):
# def wrapper(username='username', password = 'password'):
# if username in users.keys():
# if password == users[username]:
# func(username, password)
# else:
# print('Password is wrong')
# else:
# print('Username is not defind')
# return wrapper
# @decor
# def login(username, password ):
# print(f'Wellcome, {username}')
# login(username='Akylai', password=12033)
# 5.
# def myDecor(func):
# def wrapper(a, b=1, *args, **kwargs):
# print("Calling testFunc (", args, kwargs, ')')
# print('argument a:', a)
# print('argument b:', b)
# print('argument args:', args)
# print('argument kwargs:', kwargs)
# print('Finished testFunc', func(a, b, *args, **kwargs))
# return wrapper
# @myDecor
# def testFunc(a, b=1, *args, **kwargs):
# return a + b
# testFunc(2, 3, 4, 5, c=6, d=7)
# print()
# testFunc(2, c=5, d=6)
# print()
# testFunc(10) |
fecf921269a4135ef7e264719942c73491a3f41d | s3714217/IOT-OnlineLibrary | /reception/db_context.py | 1,443 | 3.671875 | 4 | import sqlite3
from sqlite3 import Error
class DbContext:
sql_create_users_table = 'CREATE TABLE IF NOT EXISTS Users (username TEXT PRIMARY KEY, password TEXT NOT NULL,' \
' first_name TEXT NOT NULL, last_name TEXT NOT NULL, email TEXT NOT NULL);'
def __init__(self, database_name):
"""Initializing user database"""
self.databaseName = database_name
self.connection = self.create_connection()
self.create_table(DbContext.sql_create_users_table)
def create_connection(self):
""""Creating connection to database"""
try:
conn = sqlite3.connect(self.databaseName, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
return conn
except Error as e:
print(e)
return None
def insert_into_table(self, table_sql, values):
""""Insert value to database"""
cur = self.connection.cursor()
cur.execute(table_sql, values)
self.connection.commit()
return
def query_from_table(self, table_sql, values):
"""Query command"""
cur = self.connection.cursor()
cur.execute(table_sql, values)
return cur.fetchall()
def create_table(self, create_table_sql):
"""Create table"""
try:
c = self.connection.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
|
7d4b8b3e32d32b0b499f0086d11ce7a08f9a485c | VictoriaSainter/CS50_pset6 | /sentiments/analyzer.py | 1,391 | 3.609375 | 4 | import nltk
class Analyzer():
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
self.positiveList = []
self.negativeList = []
with open(positives) as positivesFile:
for _ in range(35):
next(positivesFile)
for line in positivesFile:
cleanedLine = line.strip()
if cleanedLine:
self.positiveList.append(cleanedLine)
with open(negatives) as negativesFile:
for _ in range(35):
next(negativesFile)
for line in negativesFile:
cleanedLine = line.strip()
if cleanedLine:
self.negativeList.append(cleanedLine)
positivesFile.close()
negativesFile.close()
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
#print("text= {}".format(text))
score = 0
textList = text.split()
for i in textList:
i = i.lower()
for positiveWord in self.positiveList:
if i == positiveWord:
score += 1
for i in textList:
i = i.lower()
for negativeWord in self.negativeList:
if i == negativeWord:
score -= 1
return score
|
3cf28520a4f34481edc5b72d65c79738221b47f5 | hascong/ExerciseForPython | /helloworld.py | 486 | 4.125 | 4 | #!/usr/bin/python3
#
# Example file for HelloWorld
#
def someFunction():
# Global F
globalF = "def";
print(globalF)
def main():
print("Hello World!")
# Declare a variable and initialize it
f = 0;
print(f)
# Re-declaring the variable works
f = "abc"
print(f)
# Different types cannot be combined
# print("string type" + 123) gives error
print("string type" + str(123))
someFunction()
print(globalF)
if __name__ == "__main__":
main()
print("END")
|
7ffd86393583a00a033ebacd0335180e17bf3d5d | AddisonG/codewars | /python/sum-of-pairs/sum-of-pairs.py | 227 | 3.59375 | 4 | def sum_pairs(array, target):
passed = set()
for i in range(0, len(array)):
element = array[i]
if (target - element) in passed:
return [target - element, element]
passed.add(element)
|
f2da79290394fe9050fa870c6e26b7f9cc46e629 | devluke88/Python-CC | /cw.47.py | 707 | 3.890625 | 4 | # In the following 6 digit number:
# 283910
# 91 is the greatest sequence of 2 consecutive digits.
# In the following 10 digit number:
# 1234567890
# 67890 is the greatest sequence of 5 consecutive digits.
# Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.
# Adapted from ProjectEuler.net
def solution(digits):
lista = []
n = 5
for i in range(0, len(digits), 1):
lista.append(int(digits[i:i+n]))
result = max(lista)
return result |
7e50ca5014b0e4b7f940905aea3230f67914d87a | greenfox-velox/timikurucz | /week-03/day-1/33-for.py | 77 | 3.5 | 4 | af = [4, 5, 6, 7]
# print all the elements of af
for i in af:
print (i)
|
d3b00f0349bc555bcac2a7369afe5682bc4360d4 | MaciejChoromanski/design-patterns-python | /design_patterns_python/template_method.py | 1,024 | 4.1875 | 4 | # Example of 'Template-method' design pattern
from abc import ABC, abstractmethod
class AbstractClass(ABC):
"""Abstract Class"""
@abstractmethod
def do_something(self) -> None:
pass
@abstractmethod
def do_something_else(self) -> None:
pass
def template_method(self) -> None:
self.do_something()
self.do_something_else()
class FirstClass(AbstractClass):
"""Concrete Class A"""
def do_something(self) -> None:
print('FirstClass.do_something was called')
def do_something_else(self) -> None:
print('FirstClass.do_something_else was called')
class SecondClass(AbstractClass):
"""Concrete Class B"""
def do_something(self) -> None:
print('SecondClass.do_something was called')
def do_something_else(self) -> None:
print('SecondClass.do_something_else was called')
if __name__ == '__main__':
first = FirstClass()
first.template_method()
second = SecondClass()
second.template_method()
|
965cb54b06c699c0b41de6dfccfee905ad088d43 | hitrzajc/mid_programming | /book/fibonaci.py | 230 | 3.828125 | 4 | def fibonaci(n, a=1, b=1):
for i in range(n):
a, b = b, a+b
return a
#print(fibonaci(6))
def fib(n, a=1, b=1):
for i in range(n):
c = a
a = b
b = c+b
return a
#print(fib(100000)) |
5f35d8c94a506101c3c23e71bd104711143122d5 | t-tagami/100_knock | /Chapter_02/src/knock_16.py | 483 | 3.59375 | 4 | # 16. ファイルをN分割する
# 自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.
num_split = int(input())
num_line = sum(1 for _ in open('../data/hightemp.txt'))
with open('../data/hightemp.txt') as f:
for num in [(num_line + i) // num_split for i in range(num_split)]:
for _ in range(num): print(f.readline().rstrip())
print() |
09422e393cb45b0be67fb0f19629ea07d942f424 | uwspstar/DataStructures-Algorithms | /Data-Structure/Python/sort/sort-insertion-sort.py | 1,764 | 4.21875 | 4 | # range(start, stop[, step])
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
current = arr[i]
for j in range(i-1, -2, -1): # need to use -2, not -1 for end ??
if (current < arr[j]):
arr[j+1] = arr[j]
else:
break
arr[j + 1] = current
return arr
arr = [12, 11, 13, 5, 6]
print("Sorted array is:", insertion_sort(arr))
"""
def insertion_sort(array):
# We start from 1 since the first element is trivially sorted
for index in range(1, len(array)):
currentValue = array[index]
currentPosition = index
# As long as we haven't reached the beginning and there is an element
# in our sorted array larger than the one we're trying to insert - move
# that element to the right
while currentPosition > 0 and array[currentPosition - 1] > currentValue:
array[currentPosition] = array[currentPosition -1]
currentPosition = currentPosition - 1
# We have either reached the beginning of the array or we have found
# an element of the sorted array that is smaller than the element
# we're trying to insert at index currentPosition - 1.
# Either way - we insert the element at currentPosition
array[currentPosition] = currentValue
"""
"""
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
"""
|
e72e1f81ef3444afc1ba1f487be01c4e37352efd | humford/ProjectEulerSolutions | /Other/Python2.7/Problem30.py | 230 | 3.609375 | 4 | def digits(n):
return [int(i) for i in str(n)]
def digitnthPowers(n):
powers = []
for x in range(2, 355000):
if sum([d**n for d in digits(x)]) == x:
powers.append(x)
return sum(powers), powers
print(digitnthPowers(5)) |
4d7ee424b753285b6c90c4ba27eee00e64085d0d | crusenov/HackBulgaria-Programming101 | /week0/sp1/22_calculate_coins/solution.py | 387 | 3.703125 | 4 | def calculate_coins(num):
d = {}
coins = [100, 50, 20, 10, 5, 2, 1]
num *= 100
for i in coins:
count = 0
while num % i >= 0 and num // i != 0:
count += int(num // i)
num %= i
d[i] = count
return d
def main():
print(calculate_coins(0.53))
print(calculate_coins(8.94))
if __name__ == '__main__':
main()
|
ffc149d053127edeb1c819fc429bab034a2a1b13 | victorspgl/P2-AB2018 | /Vector.py | 5,064 | 4.15625 | 4 | # Clase que representa un vector y contiene las funciones de ordenacion
# Javier Corbalan y Victor Soria
# 15 Mayo 2018
import random
class Vector:
""" Constructor
"""
def __init__(self, size):
self.size = size
self.elements = []
for i in range(0,size):
self.elements.append(0)
"""
Modifica el elemento indexado por index, fijando el valor a element.
"""
def setElement(self, index, element):
self.elements[index] = element
"""
Sustituye la lista actual de elementos por la lista elements.
"""
def setAllElements(self, elements):
self.elements = elements
"""
Divide un vector en dos zonas, una con todos los elementos del vector
menores que el pivote y otra con todos los elementos mayores que el
pivote.
"""
def particion(self, izq, dch, pivoteIndex):
pivote = self.elements[pivoteIndex]
self.elements[pivoteIndex] = self.elements[dch]
self.elements[dch] = pivote
storeIndex = izq
for i in range(izq, dch+1):
if self.elements[i] < pivote:
aux = self.elements[storeIndex]
self.elements[storeIndex] = self.elements[i]
self.elements[i] = aux
storeIndex = storeIndex + 1
self.elements[dch] = self.elements[storeIndex]
self.elements[storeIndex] = pivote
return storeIndex
"""
QuickSort eligiendo como pivote el elemento mas a la izquierda del vector.
"""
def sort1(self):
lista_aux = self.elements
resultado = self.sort1RE(0, self.size-1)
self.elements = lista_aux
return resultado
"""
Funcion de inmersion de sort1
"""
def sort1RE(self, izq, dch):
if izq >= dch:
return self.elements
else:
pivote_index = izq
pivote_index = self.particion(izq, dch, pivote_index)
self.sort1RE(izq, pivote_index - 1)
self.sort1RE(pivote_index + 1, dch)
return self.elements
"""
QuickSort eligiendo la mediana como pivote
"""
def sort2(self):
lista_aux = self.elements
resultado = self.sort2RE(0, self.size - 1)
self.elements = lista_aux
return resultado
"""
Funcion de inmersion de sort2
"""
def sort2RE(self, izq, dch):
if izq >= dch:
return self.elements
else:
pivote_index = self.select(izq, dch, int((dch+izq)/2))
pivote_index = self.particion(izq, dch, pivote_index)
self.sort2RE(izq, pivote_index - 1)
self.sort2RE(pivote_index + 1, dch)
return self.elements
"""
Funcion que selecciona el elemento n-esimo del vector resultante de ordenar elements, en tiempo lineal O(n)
"""
def select(self, izq, dch, n):
while True:
if izq == dch:
return izq
pivotIndex = self.median(izq, dch)
pivotIndex = self.particion(izq, dch, pivotIndex)
if n == pivotIndex:
return n
elif n < pivotIndex:
dch = pivotIndex - 1
else:
izq = pivotIndex + 1
"""
Funcion que calcula la mediana de medianas
"""
def median(self, izq, dch):
num_elem = dch - izq
if num_elem < 5:
return self.insertionSort(izq, dch)
for iter in range(izq, dch, 5):
subDch = iter + 4
if subDch > dch:
subDch = dch
median5 = self.insertionSort(iter, subDch)
aux = self.elements[median5]
self.elements[median5] = self.elements[izq + int((iter - izq)/5)]
self.elements[izq + int((iter - izq)/5)] = aux
return self.select(izq, izq + int((dch - izq) / 5), izq + int((dch - izq) / 10))
"""
Algoritmo de ordenacion por insercion
"""
def insertionSort(self, izq, dch):
i = 1
while i < (dch - izq + 1):
j = i + izq
while j > 0 and self.elements[j - 1] > self.elements[j]:
aux = self.elements[j - 1]
self.elements[j - 1] = self.elements[j]
self.elements[j] = aux
j = j - 1
i = i + 1
return int((dch + izq)/2)
"""
QuickSort eligiendo como pivote un elemento aleatorio del vector
"""
def sort3(self):
lista_aux = self.elements
resultado = self.sort3RE(0, self.size - 1)
self.elements = lista_aux
return resultado
"""
Funcion de inmersion de sort3
"""
def sort3RE(self, izq, dch):
if izq >= dch:
return self.elements
else:
pivote_index = int(random.uniform(izq, dch))
pivote_index = self.particion(izq, dch, pivote_index)
self.sort3RE(izq, pivote_index - 1)
self.sort3RE(pivote_index + 1, dch)
return self.elements |
96bdea4ac63d709c012d4cf694e8d9399f84d18e | vamsitallapudi/Coderefer-Python-Projects | /programming/dsame/linkedLists/problems/Problem5.py | 608 | 3.8125 | 4 | # find nth node of linked list from the last in single scan without using any other data type like hashmap etc.
from dsame.linkedLists.problems.BaseLinkedList import BaseLinkedList
def nth_node_from_end(head, n):
p, temp = None, head
for i in range(1, n):
if temp:
temp = temp.next
while temp:
if p:
p = p.next
else:
p = head
temp = temp.next
if p:
print(p.data)
else:
print(None)
if __name__ == '__main__':
bll = BaseLinkedList()
head = bll.initializebll(bll)
nth_node_from_end(head, 5) |
05d40ca989c3349ade58bb07af4e849ea275f27b | 845318843/20190323learnPython | /withKid/代码清单5-end.py | 1,058 | 4.03125 | 4 | # test items
# anser = input("key a num,please!")
# print(type(anser)) # key in 12, will be stored as string form
# num = float(input()) # using float() can solve it
# print(num)
# try items
# item1
# firstname = "ke"
# lastname = "zj"
# print(firstname+lastname)
# item2
# firstname = input("hi,key your firstname")
# lastname = input("then, key your lastname")
# print("well i get it: ", firstname+lastname)
# item3
# border1 = float(input("how is the length?"))
# border2 = float(input("then, how is the width?"))
# totals = border1 * border2
#
# print("well i get it: ", totals, "pieces are enough!")
# item4
# border1 = float(input("how is the length?"))
# border2 = float(input("then, how is the width?"))
# price = float(input("well, how much is a piece?"))
# totals = border1 * border2 * price
#
# print("well it will cost: ", totals, "!")
# item5
# num_5 = int(input("how many 5fen do you have?"))
# num_2 = int(input("how many 2fen do you have?"))
# num_1 = int(input("how many 1fen do you have?"))
# print(num_5 * 5 + num_2 * 2 + num_1, "fen") |
a9f80499ff95d51bf2472876fc1845237fd6df51 | ceik/langunita | /algorithms/clustering/union_find.py | 5,680 | 3.765625 | 4 | #!/usr/bin/env python3
class UnionFind():
""" Implement a very basic Union Find datastructure."""
def __init__(self, components=[]):
self.mapping = [c for c in components]
self.cluster_count = len(self.mapping)
def find(self, x):
""" Find & return the group that x belongs to."""
return self.mapping[x - 1]
def union(self, x, y):
""" Merge the two groups that contain x and y."""
if self.find(x) == self.find(y):
return
else:
x_val = self.mapping[x - 1]
y_val = self.mapping[y - 1]
for i, v in enumerate(self.mapping):
if v == x_val:
self.mapping[i] = y_val
self.cluster_count -= 1
class UnionFindDict():
""" Implement a very basic Union Find datastructure."""
def __init__(self, components):
self.cluster_count = 0
self.mapping = {}
for c in components:
self.cluster_count += 1
self.mapping[str(c)] = c
def find(self, x):
""" Find & return the group that x belongs to."""
return self.mapping[str(x)]
def union(self, x, y):
""" Merge the two groups that contain x and y."""
if self.find(x) == self.find(y):
return 0
else:
x_val = self.mapping[str(x)]
y_val = self.mapping[str(y)]
# for i, v in enumerate(self.mapping):
for i, v in self.mapping.items():
# print(i, v)
if v == x_val:
self.mapping[i] = y_val
self.cluster_count -= 1
return 1
class UnionFindDictLazy():
""" Implement a basic Union Find datastructure with lazy unions."""
def __init__(self, components):
self.cluster_count = 0
self.mapping = {}
for c in components:
self.cluster_count += 1
self.mapping[str(c)] = c
def find(self, x):
""" Find & return the group that x belongs to."""
curr_x = x
curr_parent = self.mapping[str(curr_x)]
while curr_x != curr_parent:
curr_x = curr_parent
curr_parent = self.mapping[str(curr_x)]
return curr_parent
def union(self, x, y):
""" Merge the two groups that contain x and y."""
x_parent = self.find(x)
y_parent = self.find(y)
if x_parent == y_parent:
return 0
else:
x_val_parent = self.mapping[str(x_parent)]
self.mapping[str(y_parent)] = x_val_parent
self.cluster_count -= 1
return 1
class UnionFindDictLazyComp():
""" Implement a basic Union Find datastructure with lazy unions and path
compression."""
def __init__(self, components):
self.cluster_count = 0
self.mapping = {}
for c in components:
self.cluster_count += 1
self.mapping[str(c)] = c
def find(self, x):
""" Find & return the group that x belongs to."""
curr_x = x
curr_parent = self.mapping[str(curr_x)]
comp_list = []
while curr_x != curr_parent:
comp_list.append(curr_x)
curr_x = curr_parent
curr_parent = self.mapping[str(curr_x)]
for elem in comp_list:
self.mapping[str(elem)] = curr_parent
return curr_parent
def union(self, x, y):
""" Merge the two groups that contain x and y."""
x_parent = self.find(x)
y_parent = self.find(y)
if x_parent == y_parent:
return 0
else:
x_val_parent = self.mapping[str(x_parent)]
self.mapping[str(y_parent)] = x_val_parent
self.cluster_count -= 1
return 1
class UnionFindDictLazyCompNum():
""" Implement a basic Union Find datastructure with lazy unions and path
compression.
Names elements in consecutive numbers.
Also provides a reverse mapping that allows finding all elements that store
a certain value.
"""
def __init__(self, components):
self.cluster_count = 0
self.mapping = {}
self.reverse_mapping = {}
for c in components:
self.mapping[self.cluster_count] = [self.cluster_count, c]
if str(c) not in self.reverse_mapping:
self.reverse_mapping[str(c)] = [self.cluster_count]
else:
self.reverse_mapping[str(c)].append(self.cluster_count)
self.cluster_count += 1
def find_ids(self, x):
""" Find & return the ids that match a certain value."""
try:
ids = self.reverse_mapping[x]
except KeyError:
ids = []
return ids
def find_parents(self, x):
""" Find & return the ultimate parent that x belongs to.
Performs path compression."""
curr_x = x
curr_parent = self.mapping[curr_x][0]
compression_list = []
# TODO: Should this be curr_parent != curr_grandparent?
while curr_x != curr_parent:
compression_list.append(curr_x)
curr_x = curr_parent
curr_parent = self.mapping[curr_x][0]
for node_id in compression_list:
self.mapping[node_id][0] = curr_parent
return curr_parent
def union(self, x, y):
""" Merge the two groups that contain x and y."""
x_parent = self.find_parents(x)
y_parent = self.find_parents(y)
if x_parent == y_parent:
return 0
else:
self.mapping[y_parent][0] = x_parent
self.cluster_count -= 1
return 1
|
ee59ca6b78442b4ba31f6d647e7d09b2f80bb837 | pushparajkum/python | /10lecture_9feb/toggle.py | 384 | 3.984375 | 4 | # wap to accept a number, bit position and number of bits to toggle from bit position.
def toggle_bits(n, pos, bits):
x = 1 << bits
x = x << (pos - bits)
return n ^ x
def main():
n, pos, bits = eval(input("Enter number, bit position and number of bits to toggle :: "))
res = toggle_bits(n, pos, bits)
print("Result is : ", res)
if __name__ == '__main__':
main() |
b6f776d864771c951c6c4faed5c9e0688637099f | gaurikossambe/bank | /09_Tuples_Sets.py | 2,917 | 4.4375 | 4 | # Tuples
empty_tuple = ()
emp_IDs = 'P873874', "E948573", 46, "P248723"
#emp_IDs = ('P873874', "E948573", 46, "P248723") # both are fine
# print object types
print(type(empty_tuple))
print(type(emp_IDs))
print(type(emp_IDs[1]) is int)
print(emp_IDs)
# use tuple constructor to create a tuple of letters
# tuple constructor takes only one value
name_tuple = tuple("Ganesh Bhat")
print(type(name_tuple))
print(name_tuple)
# to create a tuple of one string value
names = "Ganesh Bhat", # remove the comma at the end and see the type of object created
print(type(names))
print(names)
# a list
names_list = ["Ganesh", "Manoj", "Pallavi", "Ravi", "Vijay"]
print((type(names_list)))
# Can not modify a tuple
empty_tuple[0] = "Srividya"
print("Empty tuple:", empty_tuple)
print("tuple from a string:", name_tuple)
# create a tuple from a list
empty_tuple = tuple(names_list) + name_tuple
print(empty_tuple)
# print tuple contents
print("Contents of tuple created from list:")
for el in empty_tuple:
print(el)
print("Contents of Emp_IDs tuple:")
print(emp_IDs)
print(emp_IDs.index("P248723"))
print(name_tuple.count('h'))
print(len(empty_tuple))
print(max(name_tuple))
# problems with different object types
# heterogeneous elements do not support comparison
print(min(emp_IDs))
all_entries = empty_tuple + emp_IDs
print(type(all_entries))
print(all_entries)
# unpacking tuple
v1, v2 = emp_IDs[0:2]
print(v1, " ", v2)
# if elements are not balanced on both sides
# tuple unpacking throws ValueError
v1, v2 = emp_IDs[0:3]
v1, v2, v3 = emp_IDs[0:2]
# tuple contains list as an element
new_tup = (names_list, "Kumar")
print(new_tup)
# can you modify the elements of the tuple?
new_tup[0] = ["Ramesh", "Maria"]
# can you modify the elements of the list, which is in a tuple?
new_tup[0].append("Maria")
print(new_tup[0])
# you are modifying the same list object
print(names_list)
# Sets
empty_set = set()
empty_set.add(234)
print(empty_set)
numbers = {25, 553, 863, 2, 634}
numbers.remove(863) # raises LookupError if not found
numbers.discard(863) # removes if found, no error if not found
print(numbers)
# duplicates will not be added to set
numbers.add(25)
print("Size: ", len(numbers))
emps = ["P12", "E34", "P17", "P12"]
emps_set = set(emps)
# search for exsistance of an element
print("P12" not in emps_set)
# Does not support indexing
print(numbers[1])
print(emps_set[0])
# convet a set to a list and use indexing
emp_list = list(emps_set)
print(emp_list[2])
odd_nums = [23, 553, 79, 91, 13, 7]
# add multiple elements (from a list/tuple/set) to a set
numbers.update(odd_nums)
print(numbers)
# remove the first element
print(numbers.pop())
# create a copy of the set
n1 = numbers.copy()
print(n1)
# empty the set
numbers.clear()
print(numbers)
|
e1bc8d977089d4e4513523a782f81b7682cd04c5 | trebor97351/Python-calculator | /main.py | 958 | 4.15625 | 4 | print("This is John's awsome (basic) calculator here are a few ground rules:")
print("1. Only use two numbers")
print("2. No fractions")
numb = input("What is your first number?") #ask for the users input
print("1 = Add")
print("2 = Subtract")
print("3 = Divide")
print("4 = Times")
print("5 = Square")
print("6 = Cube")
operator = input("What operator would you like to use?") #life=42
if operator == "5":
print(numb," squared is", int(numb)*int(numb))
elif operator == "6":
print (numb, " cubed is", int(numb)*int(numb)*int(numb))
else:
numb2 = input("What is your second number?")
if operator == "4":
print(numb,"*",numb2,"=", int(numb)*int(numb2))
elif operator == "3":
print(numb,"/",numb2,"=", int(numb)/int(numb2))
elif operator == "1":
print(numb,"+",numb2,"=", int(numb)+int(numb2))
elif operator == "2":
print(numb,"-",numb2,"=", int(numb)-int(numb2))
os.system("pause")
|
e6cc93b02acde36df324eed58108ec1aaa797e65 | RennanFelipe7/algoritmos20192 | /Lista 2/lista02ex06.py | 800 | 4.09375 | 4 | print("Digite 3 numeros inteiros diferentes")
Num1 = int(input("Digite seu primeiro numero: "))
Num2 = int(input("Digite seu segundo numero: "))
Num3 = int(input("Digite seu terceiro numero: "))
if Num3 > Num2 and Num2 > Num1:
print(Num3,Num2,Num1)
elif Num2 > Num3 and Num3 > Num1:
print(Num2,Num3,Num1)
elif Num1 > Num2 and Num2 > Num3:
print(Num1,Num2,Num3)
elif Num1 > Num2 and Num3 > Num1:
print(Num3,Num1,Num2)
elif Num1 > Num3 and Num3 > Num2:
print(Num1,Num3,Num2)
elif Num1 > Num3 and Num2 > Num1:
print(Num2,Num1,Num3)
# Bom professor Ricardo logo no começo da questao ja aviso ao usuario que ele tem que digitar 3 numeros diferentes, assim programando só as possiveis entradas respectivamente. é tambem 3 numeros inteiros assim tratando as variaveis como int. |
9f8c0e82289b3dded8e4818d8e69a7b2d3d9d6d2 | EvgeniiMorozov/studying_Python | /main/lessons/lesson_16/lesson_16.py | 5,562 | 4.09375 | 4 | import turtle
# Введение в ООП.
class Car:
count = 0 # аттрибут класса (общий для всех экземпляров класса)
# Конструктор объекта, экземпляра (вызывается при создании объекта)
def __init__(self, mark, wheels, speed):
Car.count += 1
self.mark = mark # переменные, поля, аттрибуты
self.wheels = wheels
self.speed = speed
# Функции, определённые внутри класса называются методами класса(объекта).
def drive(self):
print(f'{self.mark} едет со скоростью {self.speed}')
# Получает доступ к данным экземпляра (instance-метод)
def set_speed(self, speed):
self.speed = speed
# Получает доступ к данным ВСЕГО класса
@classmethod
def get_count_cars(cls):
print(f'Количество оставшихся машин: {cls.count}')
# Не получает доступ к данным экземпляра, но существует внутри его для удобства
@staticmethod
def print_hi():
print(f'Машина говорит привет!')
# Деструктор (вызывается, когда объект прекращает свою жизнь)
def __del__(self):
Car.count -= 1
print(f'{self.mark} разбилась со скоростью {self.speed}. Осталось машин: {Car.count}')
class Animals:
def move(self):
print('Животное передвигается.')
def eat(self):
print('Животное ест.')
# потомок класса Animals
class Insects(Animals):
def rit_noru(self):
print('Насекомое роёт нору')
def eat(self):
print('Насекомое ест листья и насекомых')
class Fish(Animals):
def __init__(self):
__var = 1
def play_in_water(self):
print('Рыба играет в воде')
def barahtatsya_in_water(self):
print('Рыба барахтается в воде')
def eat(self):
print('Рыба ест планктон')
def __live_in_leaves(self):
print('Рыба живёт в водорослях')
class Shark(Fish):
def broke_smth_via_tooth(self):
print('Акула что-то ломает зубами')
def eat(self):
print('Акула ест других рыб')
class Mammals(Animals):
def feed_milk(self):
print('Млекопитающие поят молоком')
def barahtatsya_in_water(self):
print('Млекопитающее барахтается в воде')
def eat(self):
print("Млекопитающее ест траву")
# Множественное наследование
class Dolphin(Mammals, Fish):
def smth(self):
Fish.barahtatsya_in_water(self)
def eat(self):
print('Дельфин есть планктон')
# Научно-технический рэп - Полиморфизм
def main():
# car1 = Car('Toyota', 4, 60) # Объект, экземпляр, instance
# car2 = Car('Bentley', 4, 80) # Другой объект, экземпляр, instance
# Это как бы свой тип данных
# print(type(car1))
# Все объекты независимы
# print(car1.mark) # Toyota
# print(car2.mark) # Bentley
# Методы объектов
# car1.drive()
# car1.set_speed(70)
# car1.drive()
#
# car2.drive()
# car2.set_speed(40)
# car2.drive()
#
# Car.get_count_cars()
# del car1
# car1.drive()
# Наследование, Полиморфизм, Инкапсуляция и иногда Абстракция.
# Наследование.
# Животные могут передвигаться и бегать, но такое разделение слишком общее
# animal1 = Animals()
# animal2 = Animals()
#
# # Добавили насекомых
# insect1 = Insects()
# insect2 = Insects()
#
# insect1.move()
# insect2.eat()
#
# fish1 = Fish()
# # fish1._broke_smth_via_tooth() # нет такой возможности у рыб, зато есть у акул
# shark1 = Shark()
# shark1.broke_smth_via_tooth()
# создадим дельфина
# dolphin1 = Dolphin()
# dolphin1.feed_milk()
# dolphin1.play_in_water()
# dolphin1.barahtatsya_in_water()
# dolphin1.smth()
# Полиморфизм
# insect1 = Insects()
# shark1 = Shark()
# mammal1 = Mammals()
# dolphin1 = Dolphin()
#
# insect1.eat()
# shark1.eat()
# mammal1.eat()
# dolphin1.eat()
#
# # Инкапсуляция
# # Public - публичный доступ
# # Protected - защищённый доступ (_method)
# # Private - привытный доступ (__method)
#
# # shark1.__live_in_leaves()
# fish1 = Fish()
# # fish1.__live_in_leaves()
# fish1.__var = 2
# print(fish1.__var)
turtle1 = turtle.Turtle('red')
turtle2 = turtle.Turtle('blue')
turtle1.circle(100)
for _ in range(4):
turtle2.forward(50)
turtle2.right(90)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.