blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a542c91ac9189fd1e81bd865385902c54aab6212 | kaihyperion/NeuralNetworks | /src/run_model.py | 8,267 | 3.5625 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import numpy as np
# Please read the free response questions before starting to code.
def run_model(model,running_mode='train', train_set=None, valid_set=None, test_set=None,
batch_size=1, learning_rate=0.01, n_epochs=1, stop_thr=1e-4, shuffle=True):
"""
This function either trains or evaluates a model.
training mode: the model is trained and evaluated on a validation set, if provided.
If no validation set is provided, the training is performed for a fixed
number of epochs.
Otherwise, the model should be evaluted on the validation set
at the end of each epoch and the training should be stopped based on one
of these two conditions (whichever happens first):
1. The validation loss stops improving.
2. The maximum number of epochs is reached.
testing mode: the trained model is evaluated on the testing set
Inputs:
model: the neural network to be trained or evaluated
running_mode: string, 'train' or 'test'
train_set: the training dataset object generated using the class MyDataset
valid_set: the validation dataset object generated using the class MyDataset
test_set: the testing dataset object generated using the class MyDataset
batch_size: number of training samples fed to the model at each training step
learning_rate: determines the step size in moving towards a local minimum
n_epochs: maximum number of epoch for training the model
stop_thr: if the validation loss from one epoch to the next is less than this
value, stop training
shuffle: determines if the shuffle property of the DataLoader is on/off
Outputs when running_mode == 'train':
model: the trained model
loss: dictionary with keys 'train' and 'valid'
The value of each key is a list of loss values. Each loss value is the average
of training/validation loss over one epoch.
If the validation set is not provided just return an empty list.
acc: dictionary with keys 'train' and 'valid'
The value of each key is a list of accuracies (percentage of correctly classified
samples in the dataset). Each accuracy value is the average of training/validation
accuracies over one epoch.
If the validation set is not provided just return an empty list.
Outputs when running_mode == 'test':
loss: the average loss value over the testing set.
accuracy: percentage of correctly classified samples in the testing set.
Summary of the operations this function should perform:
1. Use the DataLoader class to generate trainin, validation, or test data loaders
2. In the training mode:
- define an optimizer (we use SGD in this homework)
- call the train function (see below) for a number of epochs untill a stopping
criterion is met
- call the test function (see below) with the validation data loader at each epoch
if the validation set is provided
3. In the testing mode:
- call the test function (see below) with the test data loader and return the results
"""
# Dictionary with key train and valid
loss = {'train':[],'valid':[]}
acc = {'train':[],'valid':[]}
#Use the data loader class to generate train, validation, etc
if (running_mode == 'train'):
train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=shuffle)
#In the training mode, we have to define OPTIMIZER
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
#call the train function for a number of epoches until a stopping criterion is met
# this will require a for loop for all the epochs
#This is for checking the validation because we will need a dataloader for validation
if valid_set:
valid_loader = DataLoader(valid_set, shuffle=shuffle)
for epoch in range(n_epochs):
#train the function
model, train_loss, train_acc = _train(model, train_loader, optimizer)
#store the loss and acc into the dictionary for train lists we've created
loss['train'].append(train_loss)
acc['train'].append(train_acc)
#If validation set is provided:
if valid_set:
# call func _test to w/ validation dataloader
vl,va = _test(model, valid_loader)
#assign them into appropriate dictionary for valid lists
loss['valid'].append(vl)
acc['valid'].append(va)
if len(loss['valid']) > 1:
# check if the valid loss right efore and the currently measure vl difference is less than stop_thr
if loss['valid'][-2] - vl < stop_thr:
break
return model, loss, acc
# step 3 if it is in testing mode
elif running_mode == 'test':
testing_loader = DataLoader(test_set, batch_size=batch_size, shuffle=shuffle)
loss = []
acc = []
loss, acc = _test(model, testing_loader)
return loss, acc
def _train(model,data_loader,optimizer,device=torch.device('cpu')):
"""
This function implements ONE EPOCH of training a neural network on a given dataset.
Example: training the Digit_Classifier on the MNIST dataset
Use nn.CrossEntropyLoss() for the loss function
Inputs:
model: the neural network to be trained
data_loader: for loading the netowrk input and targets from the training dataset
optimizer: the optimiztion method, e.g., SGD
device: we run everything on CPU in this homework
Outputs:
model: the trained model
train_loss: average loss value on the entire training dataset
train_accuracy: average accuracy on the entire training dataset
"""
# we have to return train loss and accuracy. both AVG.
#criterion = nn.MSELoss() from pytorch documentation
criterion = nn.CrossEntropyLoss()
running_loss = 0.0
correct= 0
total = 0
for i, data in enumerate(data_loader):
# get the inputsl data is a list of [inputs, labels]
inputs, labels = data
#zero the parameter gradients
optimizer.zero_grad()
# forward plus backward plus + optimize
#outputs = net(inputs)
outputs = model.forward(inputs.float())
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
loss = criterion(outputs, labels.long())
loss.backward()
optimizer.step()
running_loss += loss.item()
train_loss = running_loss/len(data_loader)
train_acc = 100*correct/total
return model, train_loss, train_acc
def _test(model, data_loader, device=torch.device('cpu')):
"""
This function evaluates a trained neural network on a validation set
or a testing set.
Use nn.CrossEntropyLoss() for the loss function
Inputs:
model: trained neural network
data_loader: for loading the netowrk input and targets from the validation or testing dataset
device: we run everything on CPU in this homework
Output:
test_loss: average loss value on the entire validation or testing dataset
test_accuracy: percentage of correctly classified samples in the validation or testing dataset
"""
criterion = nn.CrossEntropyLoss(reduction='sum')
running_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for data in data_loader:
inputs, labels = data
inputs = inputs.float()
labels = labels.long()
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
loss = criterion(outputs, labels)
running_loss += loss.item()
test_loss = running_loss/total
test_acc = 100*correct/total
return test_loss, test_acc
|
346e73fadfb800cab47db99a93c269032565e60a | stuglaser/advent2020 | /days/day16.py | 2,769 | 3.5625 | 4 | #!/usr/bin/env python3
from collections import deque
from collections import namedtuple
import enum
import itertools
import unittest
import re
import sys
from utils import *
INPUT = 'inputs/input16.txt'
#INPUT='TEMP'
class TestToday(unittest.TestCase):
def test_common(self):
pass
def main():
with open(INPUT, 'r') as fin:
lines = [line.rstrip() for line in fin]
phase = 'fields'
fields = []
mine = None
nearby = []
for line in lines:
if phase == 'fields':
if line:
f, nums = line.split(': ')
both = nums.split(' or ')
pair1 = both[0].strip().split('-')
pair2 = both[1].strip().split('-')
fields.append( (f, list(map(int, pair1)), list(map(int, pair2))) )
else:
phase = 'mine'
elif phase == 'mine':
if not line:
phase = 'nearby'
elif line == 'your ticket:':
pass
else:
mine = list(map(int, line.split(',')))
elif phase == 'nearby':
if line == 'nearby tickets:':
pass
else:
nearby.append(list(map(int, line.split(','))))
ss = 0
good = []
for ticket in nearby:
bad_ticket = False
for n in ticket:
for f in fields:
in_any = False
if (f[1][0] <= n <= f[1][1] or f[2][0] <= n <= f[2][1]):
in_any = True
break
if not in_any:
bad_ticket = True
ss += n
if not bad_ticket:
good.append(ticket)
print('part 1', ss)
cand = [set(f[0] for f in fields) for _ in range(len(fields))]
# Striking out candidates
for ticket in good:
for i, n in enumerate(ticket):
for f, p1, p2 in fields:
if p1[0] <= n <= p1[1] or p2[0] <= n <= p2[1]:
# Ok
pass
else:
# Strike! f is not at position i
cand[i].remove(f)
assigned = {} # {field: index}
for _ in range(len(fields)):
for i, c in enumerate(cand):
left = c - assigned.keys()
if len(left) == 1:
assigned[list(left)[0]] = i
assert len(assigned) == len(fields), 'Failed to assign some fields to indices!'
prod = 1
for f, idx in assigned.items():
if f.startswith('departure'):
prod *= mine[idx]
print('Part 2:', prod)
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'test':
unittest.main(argv=sys.argv[:1] + sys.argv[2:])
else:
main()
|
a75ede225582d40726dc6d9bc743d16e01f94dd8 | rogamba/algorithms-python | /challenging/letters_and_numbers.py | 1,710 | 3.78125 | 4 | """ Given a list of numbers and letters,
find the longest subarray with the same
amount of letters and numbers
"""
a = 'a'
arr=[a,1,1,1,1,a,a,a,1,a,1,1,1,1,1,1,1,1,1,a]
def get_longest_equal_rec(arr):
count = {
"l" : 0,
"n" : 0
}
equal_subsets = []
memo = set()
max_subset = []
# Count
for a in arr:
t = 'n' if type(a) == int else 'l'
count[t]+=1
def _get_subsets(arr,n=0,l=0):
nonlocal equal_subsets, max_subset
# Base case
if len(arr) == 0 or tuple(arr) in memo:
return
# Append to subsets only if the n == l
print(n, l, arr)
memo.add(tuple(arr))
if n == l:
if len(arr) > len(max_subset):
max_subset = arr
equal_subsets.append(arr)
# Recurse adjacent nodes
adj_left = arr[1:]
adj_right = arr[:-1]
# New left and right count
type_l = 'n' if type(arr[0]) == int else 'l'
type_r = 'n' if type(arr[-1]) == int else 'l'
# New number
new_left_n = n-1 if type_l == 'n' else n
new_left_l = l-1 if type_l == 'l' else l
new_right_n = n-1 if type_r == 'n' else n
new_right_l = l-1 if type_r == 'l' else l
# Recurse
_get_subsets(adj_left, n=new_left_n, l=new_left_l)
_get_subsets(adj_right, n=new_right_n, l=new_right_l)
_get_subsets(arr, n=count['n'],l=count['l'])
return max_subset
if __name__ == '__main__':
print("Getting longest subsequence of equal number of letters and numbers for the set:")
print(arr)
sub = get_longest_equal_rec(arr)
print("Subset:")
print(sub) |
ab246936a84ec88b01ccaadf13a3dfd6931a9789 | Josmi27/Simple-File-Transfer-System | /Basic_Server.py | 1,623 | 3.84375 | 4 | '''
A simple example of an IPv6 server/client written in Python.
'''
import threading
import socket
import time
import sys
def fetch_local_ipv6_address(addr, port):
# try to detect whether IPv6 is supported at the present system and
# fetch the IPv6 address of localhost.
if not socket.has_ipv6:
raise Exception("the local machine has no IPv6 support enabled")
addrs = socket.getaddrinfo(addr, port, socket.AF_INET6, 0, socket.SOL_TCP)
# example output: [(23, 0, 6, '', ('::1', 10008, 0, 0))]
if len(addrs) == 0:
raise Exception("there is no IPv6 address configured for localhost")
entry0 = addrs[0]
sockaddr = entry0[-1]
return sockaddr
def main(addr, port):
# Echo server program
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sockaddr = fetch_local_ipv6_address(addr, port)
s.bind(sockaddr)
s.listen(1)
print ("server opened socket connection:", s, ", address: '%s'" % sockaddr[0])
conn, addr = s.accept()
time.sleep(1)
print ('Server: Connected by', addr)
if True: # answer a single request
data = self.conn.recv(1024)
if not data:
break
try:
f = open(data.decode(), 'r')
contents = f.read()
f.close()
self.conn.send(contents.encode())
except FileNotFoundError:
self.conn.send("File Not Found\n".encode())
# Keep preset values`
conn.close()
if __name__ == "__main__":
serverAddr = 'localhost'
serverPort = 8080
if len(sys.argv) > 1:
serverAddr = sys.argv[1]
if len(sys.argv) > 2:
serverPort = sys.argv[2]
main(serverAddr, serverPort)
|
9a3600b7a8557ee9a209f0ef334d3e79a35c09df | haileykr/CS50 | /Week 6 - Python/swap.py | 91 | 3.78125 | 4 | x=1
y=2
print(f"x is {x}, and y is {y}")
x,y=y,x
print(f"x is {x}, and y is {y}")
x,y=1,2
|
07cb993849a2b5e5c99fa011a5478681c9194075 | seanhu24/python101 | /csv/csv_reader.py | 322 | 3.671875 | 4 | import csv
def csv_reader(object):
"""
read a csv file
:param object:
:return:
"""
reader=csv.reader(object)
for row in reader:
print(" ".join(row))
if __name__=="__main__":
csv_path="TB_data_dictionary_2017-07-09.csv"
with open(csv_path) as f_obj:
csv_reader(f_obj)
|
658e29774dd8c668cd185b21241ecf71fbe0b554 | ShangruZhong/leetcode | /String/165.py | 1,179 | 3.609375 | 4 | """
165. Compare Version Numbers
Pay attemtion to '1.0.1' vs '1'
@date: 2017/05/11
"""
class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
version1 = version1.split('.')
version2 = version2.split('.')
i1 = i2 = 0
while i1 < len(version1) and i2 < len(version2):
a, b = int(version1[i1]), int(version2[i2])
res = self.compare(a, b)
if res:
return res
else:
i1 += 1
i2 += 1
while i1 < len(version1):
res = self.compare(int(version1[i1]), 0)
if res:
return res
else:
i1 += 1
while i2 < len(version2):
res = self.compare(0, int(version2[i2]))
if res:
return res
else:
i2 += 1
return 0
def compare(self, a, b):
if a > b:
return 1
elif a < b:
return -1
else:
return 0 |
b224ffc5185d7e976f03cab99b34d1c24bb6bedc | Trerick/Violent_Python_Py3 | /Chapter 6/urlcookies.py | 472 | 3.59375 | 4 | #Program to parse data contained within a cookie from a session
#Chapter 6 converted Python2 to Python3
import mechanicalsoup
import http.cookiejar
def showCookies(url):
browser = mechanicalsoup.StatefulBrowser()
cookieJar = http.cookiejar.CookieJar()
browser.set_cookiejar(cookieJar)
browser.open(url)
for cookie in cookieJar:
print(cookie.__dict__)
if __name__ == '__main__':
tgtUrl = 'http://www.yahoo.com'
showCookies(tgtUrl)
|
6b4a988b8dde8a0d12e387221c910775cb6f6d99 | AndreSlavescu/DMOJ | /From1987to2013.py | 345 | 3.515625 | 4 | #https://dmoj.ca/problem/ccc13j3
year = int(input())
nextyear = None
while nextyear is None:
year = year+1
nextyear = str(year)
digits = {}
for i in range(0, len(nextyear)):
if not (nextyear[i] in digits):
digits[nextyear[i]] = 1
else:
nextyear = None
break
print(nextyear) |
cc421238f9e169eb2b5c15a6f4b45b414c3e069b | eyjho/zettelkasten_converter | /zettelkasten_txt_to_csv/strategy.py | 3,179 | 4.09375 | 4 | """Zettelkasten converter
Eugene Ho, 16 Aug 2020
Implmenting strategy pattern from
https://refactoring.guru/design-patterns/strategy/python/example
Strategy is a behavioral design pattern. It enables an algorithm's behavior to
be selected at runtime. We can implement it by creating a common (abstract)
interface and subclassing it with a new class for each strategy, how it's done
in [1], or by creating a single class and replacing a method of that class with
a different function, how it's done in [2]. The latter implementation is
possible because in Python functions are first class objects.
"""
from __future__ import annotations
from typing import List, Dict
from zettelkasten_txt_to_csv import Zettelkasten
class Context():
"""
The Context defines the interface of interest to clients.
"""
def __init__(self, strategy: Strategy) -> None:
"""
Usually, the Context accepts a strategy through the constructor, but
also provides a setter to change it at runtime.
"""
self._strategy = strategy
@property
def strategy(self) -> Strategy:
"""
The Context maintains a reference to one of the Strategy objects. The
Context does not know the concrete class of a strategy. It should work
with all strategies via the Strategy interface.
"""
return self._strategy
@strategy.setter
def strategy(self, strategy: Strategy) -> None:
"""
Usually, the Context allows replacing a Strategy object at runtime.
"""
self._strategy = strategy
def do_some_business_logic(self) -> None:
"""
The Context delegates some work to the Strategy object instead of
implementing multiple versions of the algorithm on its own.
"""
# ...
print("Context: Sorting data using the strategy (not sure how it'll do it)")
result = self._strategy.do_algorithm({})
print(len(result))
# ...
class Strategy(Zettelkasten):
"""
The Strategy interface declares operations common to all supported versions of some algorithm.
The Context uses this interface to call the algorithm defined by Concrete Strategies.
"""
# @abstractmethod
def do_algorithm(self, data: List):
pass
"""
Concrete Strategies implement the algorithm while following the base Strategy
interface. The interface makes them interchangeable in the Context.
"""
class import_csv(Strategy):
def do_algorithm(self, data: Dict) -> Dict:
file_path = 'C:/Users/Eugene/Documents/GitHub/zettelkasten_txt_to_csv/data/Zettelkasten v0_2.csv'
return self.import_csv_zk(file_path = file_path)
class import_txt(Strategy):
def do_algorithm(self, data: List) -> List:
file_path = 'C:/Users/Eugene/Documents/GitHub/zettelkasten_txt_to_csv/data/00 Gardening zettlelkasten.txt'
return self.import_txt_zk(file_path = file_path)
if __name__ == "__main__":
# The client code picks a concrete strategy and passes it to the context.
# The client should be aware of the differences between strategies in order
# to make the right choice.
context = Context(import_csv())
print("Client: Strategy is set to import csv.")
context.do_some_business_logic()
print()
print("Client: Strategy is set to import txt.")
context.strategy = import_txt()
context.do_some_business_logic() |
96fe19f77c554d83e671d1443c6b13b43bbc5f43 | RAMMVIER/Data-Structures-and-Algorithms-in-Python | /Algorithm/10.Merge_sort.py | 1,871 | 3.640625 | 4 | # 归并排序:假设原始列表分两段有序,将其合成为一个有序列表
# 归并排序不可在原地排序
# 步骤:
# 1. 分解:将列表越分越小,直至分成一个元素
# 2. 终止条件:一个元素必然是有序的
# 3. 合并:将两个有序列表合并,列表逐渐增大
# 时间复杂度:O(nlogn)
# 一次归并复杂度为O(n)
# 递归层数为logn层
# 空间复杂度:O(n)
import random
# 合并过程
def merge(li, low, mid, high):
"""
:param li: 输入的原始列表
:param low: 列表第一个元素的下标
:param mid: 第一段有序列表中最后一个元素的下标
:param high: 列表最后一个元素的下标
:return: void
"""
i = low
j = mid + 1 # j指向第二段有序列表的第一个元素
ltmp = [] # 存储排序后的列表
while i <= mid and j <= high: # 只要左右都有数,比大小
if li[i] < li[j]:
ltmp.append(li[i])
i += 1
else:
ltmp.append(li[j])
j += 1
# while执行结束后,两个有序列表必有一个没有元素了
# 如果第一部分害有元素
while i <= mid:
ltmp.append(li[i])
i += 1
# 如果第二部分害有元素
while j <= high:
ltmp.append(li[j])
j += 1
li[low:high + 1] = ltmp
def merge_sort(li, low, high):
if low < high: # 至少有两个元素,递归
mid = (low + high) // 2
merge_sort(li, low, mid)
merge_sort(li, mid + 1, high)
merge(li, low, mid, high)
# test
test_list = list(range(1000))
random.shuffle(test_list)
print(test_list)
merge_sort(test_list, 0, len(test_list) - 1)
print(test_list)
|
61959df9aeed90583b68dff3dfc4ae4565817d9b | KSrinuvas/ALL | /srinivas/PY_FILES/TASKS/DAY1/l1.py/day.py | 1,707 | 4.09375 | 4 | #!/usr/bin/python
a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
print("\n")
print( "Original List ===>{}".format(a))
even_no = []
odd_no = []
first_ele_list = []
last_ele_list = []
#first_element's in a list
for i in a:
for h in i:
# print (h)
### even no's in a list's
if (h%2==0):
even_no.append(h)
### odd no's in a list's
else:
odd_no.append(h)
print("\n")
print ("Even_no's in a List's ==> {}".format(even_no))
print("\n")
print ("Odd_no's in a List's ==> {}".format(odd_no))
print("\n")
### first element's in a list's and list element's in a list
for i in a:
#print (i)
### first element's in a list's
bb =i.pop([0][0])
#print (i)
#print(bb)
first_ele_list.append(bb)
## last element's in a list's
cc = i.pop()
last_ele_list.append(cc)
#print(cc)
print ("First_Elemen's in a List's ==> {}".format(first_ele_list))
print("\n")
print ("Last_Elemen's in a List's ==> {}".format(last_ele_list))
print("\n")
## build the list in dynamic way
dynamic_list1 = []
a = []
b = []
c = []
a.append(1)
a.append(2)
a.append(3)
a.append(4)
b.append(5)
b.append(6)
b.append(7)
b.append(8)
c.append(9)
c.append(10)
c.append(11)
c.append(12)
dynamic_list1.insert(0,a)
dynamic_list1.insert(1,b)
dynamic_list1.insert(2,c)
print("To Build The List Dynamic ==> {}".format(dynamic_list1))
print("\n")
'''
dynamic_list1.append([5,6,7,8])
dynamic_list1.append([9,10,11,12])
print(dynamic_list1)
'''
'''
a = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
dynamic_list = []
for i in a:
dynamic_list.append(i)
print(dynamic_list)
'''
|
2f7b8f99d4a36857c865e718efbcc851d047a142 | yinccc/leetcodeEveryDay | /94-20190321-Binary Tree Inorder Traversal.py | 427 | 3.75 | 4 | class TreeNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def BinaryTreeInorderTraversal(root):
res=[]
helper(root,res)
return res
def helper(root,res):
if root:
helper(root.left,res)
res.append(root.val)
helper(root.right,res)
a=TreeNode(1)
b=TreeNode(2)
c=TreeNode(3)
a.left=b
a.right=c
print(BinaryTreeInorderTraversal(a)) |
bf929b3d3db72d0c7767babe4e30e56895a4fe73 | riteshsharma29/matplotlib_visulaizations | /bar_ver.py | 510 | 3.65625 | 4 | #!/usr/bin/python
# coding: utf-8 -*-
#http://www.chartblocks.com/en/support/faqs/faq/when-to-use-a-bar-chart
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("budget.csv")
y = df['Values'].values
df.plot(kind='bar',color='c',grid=True)
plt.ylabel('Values')
plt.xlabel('Activity')
# range(Number of categories)
plt.xticks(range(6),df['Activity'])
plt.title('2014 Budget: Variance')
for i, v in enumerate(y):
plt.text(v,i ,str(v), color='blue', fontweight='bold')
plt.show()
|
398f4fd5b5b2109d51ff2484057ab631feff1f0c | MuhammadAbbasi/DSA_Semester3 | /Assignments/Assignment 3/2_.py | 706 | 4.09375 | 4 | class Flower():
def __init__(self):#,name = '',petal = 0,price = 0.0):
self.name = ''
self.petal = 0
self.price = 0.0
def setName(self):
self.name = input("Enter Name: ")
def setPetal(self):
self.petal = int(input("Enter Number of Petals: "))
def setPrice(self):
self.price = (float(input("Enter Price: ")))
def showName(self):
print("Name of flower is:",self.name)
def showPetal(self):
print("Number of Petals are: ", str(self.petal))
def showPrice(self):
print("Price is: ",str(self.price))
rose = Flower()
rose.setName()
rose.setPetal()
rose.setPrice()
rose.showName()
rose.showPetal()
rose.showPrice() |
04cd932dc27203027af315c8033732f2af5cf3be | Yeshwanthyk/algorithms | /trees/dfs.py | 945 | 3.640625 | 4 | class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
"""
in_order: LDR
pre_order: DLR
post_order: LRD
"""
def in_order_rec(root):
if not root:
return []
res = []
res = in_order_rec(root.left)
res.append(root.data)
res = res + in_order_rec(root.right)
return res
def in_order_iter(root):
if not root:
return []
res = []
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.data)
root = root.right
return res
if __name__ == '__main__':
n1 = Node(100)
n2 = Node(50)
n3 = Node(150)
n4 = Node(25)
n5 = Node(75)
n6 = Node(125)
n7 = Node(175)
n1.left, n1.right = n2, n3
n2.left, n2.right = n4, n5
n3.left, n3.right = n6, n7
print(in_order_rec(n1))
|
cbadf1adf44b6e4ff10114ca56fb42e87533d468 | AyushiK16/C98-H | /swappingFiles.py | 982 | 3.546875 | 4 | A = 'fileA.txt'
B = 'fileB.txt'
dataA = ''
dataB = ' '
def readData(file1, file2):
global dataA
global dataB
fA = open(file1, 'r')
fB = open(file2, 'r')
dataA = fA.read()
dataB = fB.read()
print('FileA', dataA)
print('FileB', dataB)
writeData(file1,file2)
#print(dataA, dataB)
def writeData(file1, file2):
global dataA
global dataB
fA = open(file1, 'w')
fB = open(file2, 'w')
fA.write(dataB)
fB.write(dataA)
readData(A,B)
#writeData(A.B)
'''
file1.write(dataB)
file2.write(dataA)
print('FileA', dataA)
print('FileB', dataB)
readData(A,B)
print('FileA', dataA)
print('FileB', dataB)
writeData(A,B)
print('AFTER SWAP')
print('FileA', dataA)
print('FileB', dataB)
def readText(file):
global totalCount
f = open(file, 'r')
lines = f.readlines()
for i in lines:
list = i.split()
list2 = len(list)
totalCount = totalCount + list2
'''
|
f43d8bc00f7dc81df5c40183df0e980d20c33609 | akchandankhede/tasks- | /idship.py | 801 | 3.8125 | 4 | '''
ID and BattleShip
Pesudo Code
1. Initilized for in range of no of test cases form user
2. initilized s variable to take a character
3. convert character into lower case
4. if s==b
then print BattleShip
5. else if s==c
then print Cruiser
6. else if s==d
then print Destroyer
7. else if s==f
then print Frigate
end of step 4 elif
'''
# enter no of test cases
for i in range(int(input())):
# enter character stores in s variable
s=input()
# convert character into lower case
s=s.lower()
# checking the character taken form user and print the result
if(s=='b'):
print("BattleShip")
elif(s=='c'):
print("Cruiser")
elif(s=='d'):
print("Destroyer")
elif(s=='f'):
print("Frigate") |
5d17cf51398e903be12b41ab9ba1b927c4332560 | MilanMolnar/Codecool_SI_week3 | /Game statistics reports/reports.py | 3,545 | 3.625 | 4 | def sorting(list): #Buble sorting algorithm
sorted = False
while sorted == False:
sorted = True
for obj in range(len(list) - 1):
if list[obj] > list[obj + 1]:
temp = list[obj]
list[obj] = list[obj + 1]
list[obj + 1] = temp
sorted = False
return list
# Report functions
def count_games(file_name): #Test1
with open(file_name, "r") as file_handler:
number_of_games = 0
for lines in file_handler:
number_of_games += 1
return number_of_games
def decide(file_name, year): #Test2
with open(file_name, "r") as file_handler:
lines = file_handler.read()
if str(year) in lines:
return True
else:
return False
def get_latest(file_name): #Test3
with open(file_name, "r") as file_handler:
lines = file_handler.readlines()
list_of_game_year = []
for line in lines:
f_line = line.split('\t')
list_of_game_year.append(f_line[2])
latest_year = max(list_of_game_year)
for line in lines:
f_line = line.split('\t')
if f_line[2] == latest_year:
return f_line[0]
def count_by_genre(file_name, genre): #Test4
with open(file_name, "r") as file_handler:
lines = file_handler.readlines()
num_of_games_by_genre = 0
for line in lines:
f_line = line.split('\t')
if f_line[3].lower() == genre.lower():
num_of_games_by_genre += 1
return num_of_games_by_genre
def get_line_number_by_title(file_name, title): #Test5
with open(file_name, "r") as file_handler:
num_of_line = 0
lines = file_handler.readlines()
for line in lines:
f_line = line.split('\t')
num_of_line += 1
if f_line[0].lower() == title.lower():
return num_of_line
raise ValueError
def sort_abc(file_name): #Bonus Test1
list_of_titles = []
with open(file_name, "r") as file_handler:
lines = file_handler.readlines()
for line in lines:
f_line = line.split('\t')
list_of_titles.append(f_line[0])
return sorting(list_of_titles)
def get_genres(file_name): #Bonus Test2
list_of_genres = []
list_of_genres_cutted = []
with open(file_name, "r") as file_handler:
lines = file_handler.readlines()
for line in lines:
f_line = line.split('\t')
list_of_genres.append(f_line[3])
for genre in list_of_genres:
if genre not in list_of_genres_cutted:
list_of_genres_cutted.append(genre)
return sorting(list_of_genres_cutted)
def when_was_top_sold_fps(file_name): #Bonus Test3
with open(file_name, "r") as file_handler:
lines = file_handler.readlines()
list_of_game_sold = []
for line in lines:
f_line = line.split('\t')
if f_line[3] == "First-person shooter":
list_of_game_sold.append(float(f_line[1]))
max_sold = max(list_of_game_sold)
for line in lines:
f_line = line.split('\t')
if float(f_line[1]) == float(max_sold):
return int(f_line[2])
|
f25269a0afc50e3b32d86b350d7c157df3f9417f | StarCoder09/PythonTkinter | /App's/DatabaseApp.py | 8,389 | 4.21875 | 4 | '''
This App is to illustrate simple CRUD operations using Tkinter.
'''
#Packages
from tkinter import *
from PIL import ImageTk,Image
from tkinter import messagebox
from tkinter import filedialog
import sqlite3
window = Tk()
window.title("Database")
window.iconbitmap('D:/e-Learning/Tkinter/Images/India-flag.ico')
window.geometry("400x400")
#----- Run the below commented code one time only for just to create database. ----#
'''
#Databases
conn = sqlite3.connect('address_book.db')
c = conn.cursor()
#create table
c.execute("""CREATE TABLE address (
first_name text,
last_name text,
address text,
city text,
state text,
zipcode integer
)""")
conn.commit()
conn.close()
'''
#---------------------------------------------------------------------------------#
# create function to delete records
def delete():
#Create a DB or connect
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
#delete records
c.execute("DELETE from address WHERE oid = " + dlt_box.get())
dlt_box.delete(0, END)
#commit changes
conn.commit()
#close connection
conn.close()
# create edit function
def edit():
#Create a DB or connect
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
record_id = dlt_box.get()
c.execute("""UPDATE address SET
first_name = :first,
last_name = :last,
address = :address,
city = :city,
state = :state,
zipcode = :zipcode
WHERE oid = :oid""",
{'first': f_name_updator.get(),
'last': l_name_updator.get(),
'address': address_updator.get(),
'city': city_updator.get(),
'state': state_updator.get(),
'zipcode': zipcode_updator.get(),
'oid': record_id
})
#commit changes
conn.commit()
#close connection
conn.close()
messagebox.showinfo("Alert!", "Records saved!!!")
updator.destroy()
# create function to update
def update():
global updator
updator = Tk()
updator.title("Update Database")
updator.iconbitmap('D:/e-Learning/Tkinter/Images/India-flag.ico')
#updator.geometry("400x200")
#Create a DB or connect
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
record_id = dlt_box.get()
#Query DB
c.execute("SELECT * from address WHERE oid = " + record_id)
records = c.fetchall()#it can be fetchone(), fetchmany(value), fetchall()
# print(records)
#loping results
#print_records = ''
#for record in records:
#print_records += str(record) + "\n"
#print_records += str(record[0]) + " " + str(record[1]) + "\n"
#print_records += str(record[0]) + " " + str(record[1]) + " " + "\t\t" + str(record[6]) + "\n"
#commit changes
conn.commit()
#close connection
conn.close()
#create global
global f_name_updator
global l_name_updator
global address_updator
global city_updator
global state_updator
global zipcode_updator
# Create text boxes
f_name_updator = Entry(updator, width=30)
f_name_updator.grid(row=0, column=1, padx=20, pady=(10, 0))
l_name_updator = Entry(updator, width=30)
l_name_updator.grid(row=1, column=1)
address_updator = Entry(updator, width=30)
address_updator.grid(row=2, column=1)
city_updator = Entry(updator, width=30)
city_updator.grid(row=3, column=1)
state_updator = Entry(updator, width=30)
state_updator.grid(row=4, column=1)
zipcode_updator = Entry(updator, width=30)
zipcode_updator.grid(row=5, column=1)
#create text box labels
f_name_lbl = Label(updator, text="First Name:")
f_name_lbl.grid(row=0, column=0, pady=(10, 0))
l_name_lbl = Label(updator, text="Last Name:")
l_name_lbl.grid(row=1, column=0)
address_lbl = Label(updator, text="Address:")
address_lbl.grid(row=2, column=0)
city_lbl = Label(updator, text="City:")
city_lbl.grid(row=3, column=0)
state_lbl = Label(updator, text="State:")
state_lbl.grid(row=4, column=0)
zipcode_lbl = Label(updator, text="Zipcode:")
zipcode_lbl.grid(row=5, column=0)
#looping results
for record in records:
f_name_updator.insert(0, record[0])
l_name_updator.insert(0, record[1])
address_updator.insert(0, record[2])
city_updator.insert(0, record[3])
state_updator.insert(0, record[4])
zipcode_updator.insert(0, record[5])
#create an update button
save_btn = Button(updator, text="Save Records", command=edit)
save_btn.grid(row=6, column=0, columnspan=2, padx=10, pady=10, ipadx=105)
#Create submit function
def submit():
#Create a DB or connect
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
#Insert into table
c.execute("INSERT INTO address VALUES (:f_name, :l_name, :address, :city, :state, :zipcode)",
{
'f_name': f_name.get(),
'l_name': l_name.get(),
'address': address.get(),
'city': city.get(),
'state': state.get(),
'zipcode': zipcode.get()
})
#commit changes
conn.commit()
#close connection
conn.close()
#Clear the text boxes
f_name.delete(0, END)
l_name.delete(0, END)
address.delete(0, END)
city.delete(0, END)
state.delete(0, END)
zipcode.delete(0, END)
#Create query function
def query():
#Create a DB or connect
conn = sqlite3.connect('address_book.db')
#Create cursor
c = conn.cursor()
#Query DB
c.execute("SELECT *, oid FROM address")
records = c.fetchall()#it can be fetchone(), fetchmany(value), fetchall()
# print(records)
#loping results
#print_records = ''
f=open('Records.txt','w')
for record in records:
f.write(str(record) + "\n")
f.close()
#print_records += str(record[0]) + " " + str(record[1]) + "\n"
#print_records += str(record[0]) + " " + str(record[1]) + " " + "\t\t" + str(record[6]) + "\n"
#query_lbl = Label(window, text=print_records)
#query_lbl.grid(row=12, column=0, columnspan=2)
#commit changes
conn.commit()
#close connection
conn.close()
#Clear the text boxes
import subprocess as sp
pName='notepad.exe'
fName='Records.txt'
sp.Popen([pName,fName])
# Create text boxes
f_name = Entry(window, width=30)
f_name.grid(row=0, column=1, padx=20, pady=(10, 0))
l_name = Entry(window, width=30)
l_name.grid(row=1, column=1)
address = Entry(window, width=30)
address.grid(row=2, column=1)
city = Entry(window, width=30)
city.grid(row=3, column=1)
state = Entry(window, width=30)
state.grid(row=4, column=1)
zipcode = Entry(window, width=30)
zipcode.grid(row=5, column=1)
dlt_box = Entry(window, width=30)
dlt_box.grid(row=9, column=1, pady=5)
#create text box labels
f_name_lbl = Label(window, text="First Name:")
f_name_lbl.grid(row=0, column=0, pady=(10, 0))
l_name_lbl = Label(window, text="Last Name:")
l_name_lbl.grid(row=1, column=0)
address_lbl = Label(window, text="Address:")
address_lbl.grid(row=2, column=0)
city_lbl = Label(window, text="City:")
city_lbl.grid(row=3, column=0)
state_lbl = Label(window, text="State:")
state_lbl.grid(row=4, column=0)
zipcode_lbl = Label(window, text="Zipcode:")
zipcode_lbl.grid(row=5, column=0)
dlt_box_lbl = Label(window, text="ID Number:")
dlt_box_lbl.grid(row=9, column=0, pady=5)
#Create submit button
sb_btn = Button(window, text="Submit UR Data", command=submit)
sb_btn.grid(row=6, column=0, columnspan=2, padx=10, pady=10, ipadx=100)
#Create a query btn
query_btn = Button(window, text="Show Records", command=query)
query_btn.grid(row=7, column=0, columnspan=2, padx=10, pady=10, ipadx=105)
#create delete btn
delete_btn = Button(window, text="Delete Records", command=delete)
delete_btn.grid(row=10, column=0, columnspan=2, padx=10, pady=10, ipadx=105)
#create an update button
update_btn = Button(window, text="Update Records", command=update)
update_btn.grid(row=11, column=0, columnspan=2, padx=10, pady=10, ipadx=105)
#event handler
window.mainloop()
|
4f398588cc768a4f1c88fcc71db857ac379aeea3 | dongpodu/python | /me/For.py | 987 | 4 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# for循环可以遍历任何序列的项目,如一个列表或者一个字符串
print('----------1------------')
for l in 'python':
print(l)
print('----------2------------')
li = [1, 2, 3, 4]
for e in li:
print(e)
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print('当前水果 :', fruits[index])
print('----------3------------')
print(range(10)) # 定义从0-10的有序序列,步长为1
print(range(10, 20)) # 定义从10-20的有序序列,步长为1
print(range(10, 20, 2)) # 定义从10-20的有序序列,步长为2
print('----------4------------')
# 在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样
for index in range(1, 10):
print('执行for循环')
else:
print('结束for循环')
|
2857d8b359751c37ff134d0668600c5ab5b40d33 | eyee0309/DL | /cnn-mnist-1.4.1.py | 2,460 | 3.75 | 4 | # Keras code for MNIST digit classification using CNNs
import numpy as np
from keras.models import Sequential
from keras.layers import Activation, Dense, Dropout
from keras.layers import Conv2D, MaxPool2D, Flatten
from keras.utils import to_categorical, plot_model
from keras.datasets import mnist
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Compute the number of labels
num_labels = len(np.unique(y_train))
# Convert labels to one-hot vectors
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
# Get image dimensions
image_size = x_train.shape[1]
# Resize input and normalize image values to unit interval
# Input to CNN is of shape (instances, h, w, c)
x_train = np.reshape(x_train, [-1, image_size, image_size, 1])
x_test = np.reshape(x_test, [-1, image_size, image_size, 1])
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# Network parameters
# Image is processed as is (square grayscale)
input_shape = (image_size, image_size, 1) # 1 channel (c) - BW image
batch_size = 128
kernel_size = 3
pool_size = 2
filters = 64 # number of feature maps
dropout = 0.2 # dropout rate
# Model is a stack of CNN-ReLU-MaxPooling
model = Sequential()
model.add(Conv2D(filters=filters,
kernel_size=kernel_size,
activation='relu',
input_shape=input_shape))
model.add(MaxPool2D(pool_size=pool_size))
model.add(Conv2D(filters=filters,
kernel_size=kernel_size,
activation='relu'))
model.add(MaxPool2D(pool_size=pool_size))
model.add(Conv2D(filters=filters,
kernel_size=kernel_size,
activation='relu'))
model.add(Flatten())
# Dropout added as a regularizer
model.add(Dropout(rate=dropout))
# Output layer is a 10-dimensional one-hot vector
model.add(Dense(num_labels))
model.add(Activation('softmax'))
model.summary()
#plot_model(model, to_file='cnn-mnist.png', show_shapes=True)
# Loss function for one-hot vector
# Use of ADAM optimizer
# Accuracy is a good metric for classification tasks
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# Train the network
model.fit(x_train, y_train, batch_size=batch_size, epochs=10)
# Evaluate the model
loss, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
print('\nTest accuracy: {0:.1f}%'.format(100.0 * acc))
|
f5662f98c90d77cdca1d0f6c614e3a5eb6144a26 | hrvach/CheckiO | /Feed Pigeons.py | 546 | 3.734375 | 4 | def checkio(number):
pigeons = [0]
for add in range(2, 10**5):
for n in range(len(pigeons)):
pigeons[n] += 1
number-=1
if number < 1: return len([p for p in pigeons if p>0])
pigeons += [0]*(add)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(1) == 1, "1st example"
assert checkio(2) == 1, "2nd example"
assert checkio(5) == 3, "3rd example"
assert checkio(10) == 6, "4th example" |
07f5155a8013812e8b95ebb5031ae6fd2d809f9d | Maxaravind/TF_Tutorial_IIT_Delhi_feb_2019 | /visualize_graphs.py | 777 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 00:18:49 2019
@author: aravind
"""
"""
This code let's you visualize the graph you have created in TF
"""
import tensorflow as tf
c = tf.constant(5.0,name='Constant_c')
v = tf.Variable(2.0,name='Variable_v')
x = tf.placeholder(tf.float32, [1,], name='Placeholder_x')
mul = tf.multiply(v,x,name="Multiply_x_v")
y = tf.add(mul,c,name='Add_mul_c')
init = tf.global_variables_initializer()
with tf.Session() as sess:
writer = tf.summary.FileWriter("output", sess.graph)
sess.run(init)
print(sess.run(y,feed_dict={x:[4]}))
writer.close()
# after you run the graph, run the below command to get tensorboard running using the output folder
# tensorboard --logdir=output
|
701a12080eabd9a2e032773e2ff61d1e00129405 | smatkovi/sputter | /variableplot2.py | 3,237 | 3.953125 | 4 | """
===========
Slider Demo
===========
Using the slider widget to control visual properties of your plot.
In this example, a slider is used to choose the frequency of a sine
wave. You can control many continuously-varying properties of your plot in
this way.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.6)
t = np.arange(0.00000001, 0.0005, 0.0000001) #this is the pressure p
J = 4.0
S_N = 0.1
T = 273.0
S_M = 1.0
z_t = 1
S = 50
m = 4.6518e-26
z_c = 1
A_t = 0.127
A_c = 1.27
s = (A_c*z_c*t*(1-(S_N/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)+(A_c*z_c*t)/(A_t*np.sqrt(m*T)))/(S_M*(1-1/((J*S_N*np.sqrt(m*T))/(z_t*t)+1))+S_N/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)+(A_c*z_c*t)/(A_t*J*np.sqrt(m*T)))))/np.sqrt(m*T)+(A_t*z_t*t*(1-1/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)))/np.sqrt(m*T)+S*t
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([-0.00005, 0.00055, -4e9, 4e8])
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
axS_M = plt.axes([0.25, 0.2, 0.65, 0.03], facecolor=axcolor)
axz_t = plt.axes([0.25, 0.25, 0.65, 0.03], facecolor=axcolor)
axT = plt.axes([0.25, 0.3, 0.65, 0.03], facecolor=axcolor)
axS = plt.axes([0.25, 0.35, 0.65, 0.03], facecolor=axcolor)
axz_c = plt.axes([0.25, 0.4, 0.65, 0.03], facecolor=axcolor)
axA_t = plt.axes([0.25, 0.45, 0.65, 0.03], facecolor=axcolor)
axA_c = plt.axes([0.25, 0.5, 0.65, 0.03], facecolor=axcolor)
sfreq = Slider(axfreq, 'J', 0.1, 30.0, valinit=J)
samp = Slider(axamp, 'S_N', 0.1, 10.0, valinit=S_N)
sS_M = Slider(axS_M, 'S_M', 1.0, 3.0, valinit=S_M)
sz_t = Slider(axz_t, 'z_t', 0.1, 1.0, valinit=z_t)
sT = Slider(axT, 'T', 273.0, 500.0, valinit=T)
sS = Slider(axS, 'S', 10.0, 200.0, valinit=S)
sz_c = Slider(axz_c, 'z_c', 0.1, 1.0, valinit=z_c)
sA_t = Slider(axA_t, 'A_t', 0.001, 0.3, valinit=A_t)
sA_c = Slider(axA_c, 'A_c', 0, 3.0, valinit=A_c)
def update(val):
J = samp.val
S_N = sfreq.val
S_M = sS_M.val
z_t = sz_t.val
T = sT.val
S = sS.val
z_c = sz_c.val
A_t = sA_t.val
A_c = sA_c.val
l.set_ydata((A_c*z_c*t*(1-(S_N/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)+(A_c*z_c*t)/(A_t*np.sqrt(m*T)))/(S_M*(1-1/((J*S_N*np.sqrt(m*T))/(z_t*t)+1))+S_N/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)+(A_c*z_c*t)/(A_t*J*np.sqrt(m*T)))))/np.sqrt(m*T)+(A_t*z_t*t*(1-1/((J*S_N*np.sqrt(m*T))/(z_t*t)+1)))/np.sqrt(m*T)+S*t)
fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)
sS_M.on_changed(update)
sz_t.on_changed(update)
sT.on_changed(update)
sS.on_changed(update)
sz_c.on_changed(update)
sA_t.on_changed(update)
sA_c.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
sfreq.reset()
samp.reset()
sS_M.reset()
sz_t.reset()
sT.reset()
sS.reset()
button.on_clicked(reset)
rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
def colorfunc(label):
l.set_color(label)
fig.canvas.draw_idle()
radio.on_clicked(colorfunc)
plt.show()
|
7615313f2c8ed09722bfb5f2adbb5091e7e5ffb4 | deboraprudencio/python | /outros/agua-ferve.py | 262 | 3.6875 | 4 | #recebe uma temperatura e retorna se a água ferve e evapora ou não
temp = int(input("Qual a temperatura?"))
if temp > 100:
aguaferve = True
evaporacao = "muito rápida"
else:
aguaferve = False
evaporacao = "não"
print(aguaferve, evaporacao) |
806993754562c007c94e3a44cfcd7bfdd35a21bb | Will-Fahie/gravitation-simulator | /gravitation.py | 9,366 | 3.6875 | 4 | import math
import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
screen_width = screen_height = 750
screen = pygame.display.set_mode([750, 750])
pygame.display.set_caption("Will's orbital modeller")
centre_x = screen_width // 2
centre_y = screen_height // 2
# gravitational constant
G = 6.67 * 10 ** -11
# astronomical Unit
AU = 1.50 * 10 ** 11
distance_scale = 200 / AU
day = 60 * 60 * 24 # one day in seconds
time_step = day # each step is one day
instantiated = False
freq_changing = False
final_freq = 0
class Body(object):
"""A class representing an astronomical body"""
def __init__(self, name, mass, vel_x, vel_y, pos_x, pos_y, colour, diameter):
self.name = name
self.mass = mass # mass of body in kg
self.vel_x = vel_x # horizontal velocity in m/s
self.vel_y = vel_y # vertical velocity in m/s
self.pos_x = pos_x # horizontal position in m
self.pos_y = pos_y # vertical position in m
self.colour = colour
self.diameter = diameter
self.radius = diameter // 2
# draw lines method needs to points in positions list
self.positions = [(self.pos_x * distance_scale + centre_x, self.pos_y * distance_scale + centre_y),
(self.pos_x * distance_scale + centre_x, self.pos_y * distance_scale + centre_y)]
def calc_grav_force(self, other_body):
"""Calculates gravitational force acting on this body from another body"""
# calculates distance
dx = other_body.pos_x - self.pos_x
dy = other_body.pos_y - self.pos_y
d = math.sqrt(dx ** 2 + dy ** 2)
# calculates resultant force
f = G * self.mass * other_body.mass / (d ** 2)
# resolves force into x and y components
theta = math.atan2(dy, dx) # unlike atan, atan2 considers signs
f_x = f * math.cos(theta)
f_y = f * math.sin(theta)
return f_x, f_y
def draw(self):
pygame.draw.circle(screen,
self.colour,
(self.pos_x * distance_scale + centre_x, self.pos_y * distance_scale + centre_y),
self.radius)
def print_info(bodies):
"""Prints each body's position and velocity"""
for body in bodies:
print(f"""
{body.name}
Position = x: {body.pos_x} y: {body.pos_y}
Velocity = y: {body.vel_x} x: {body.vel_y}\n""")
print()
def calc_total_force(bodies):
"""Calculates the net force acting on each body"""
forces = {}
for body in bodies:
total_f_x = 0
total_f_y = 0
for other in bodies:
if other is body:
continue # doesn't calculate force from body on itself
f_x, f_y = body.calc_grav_force(other)
total_f_x += f_x
total_f_y += f_y
forces[body] = (total_f_x, total_f_y)
return forces
def update_velocities_positions(bodies, forces, trail=False):
"""Updates the velocity and position of each body based on the net force acting on it"""
for body in bodies:
f_x, f_y = forces[body]
# updates velocities
body.vel_x += f_x / body.mass * time_step
body.vel_y += f_y / body.mass * time_step
# updates positions
body.pos_x += body.vel_x * time_step
body.pos_y += body.vel_y * time_step
# adds new position to positions list
if trail:
body.positions.append((body.pos_x * distance_scale + centre_x, body.pos_y * distance_scale + centre_y))
if len(body.positions) == 75:
body.positions.pop(0)
def get_choice():
"""Prints model options, gets choice from user, and runs the according model function"""
options = {"1:": "Solar system",
"2:": "Two suns",
"3:": "Earth and sun",
"4:": "Earth and moving sun",
"5:": "Exit"}
# prints options
print()
for k, v in options.items():
print(k, v)
# loops until valid options given
while True:
try:
usr_choice = int(input("\nSelect model: "))
if usr_choice == 5:
sys.exit()
else:
draw_trail = input("Draw trail? (y/n): ")
if draw_trail.upper() == "Y":
return usr_choice, True
elif draw_trail.upper() == "N":
return usr_choice, False
else:
raise ValueError
except ValueError:
print("Not valid")
def draw(bodies, start, trail):
"""Updates forces, positions and velocities and draws bodies on screen, and trail if trail is True"""
screen.fill((0, 0, 0))
if start:
forces = calc_total_force(bodies)
update_velocities_positions(bodies, forces, trail)
for body in bodies:
body.draw()
if trail:
pygame.draw.lines(screen, body.colour, False, body.positions, body.diameter // 4)
def change_frequency():
"""Used to gradually increase time_step (and thus period of orbit) up to a resonant frequency"""
global time_step, freq_changing, final_freq
difference = abs(final_freq - time_step)
if difference > 100000:
if time_step < final_freq:
time_step += 25000
elif time_step > final_freq:
time_step -= 25000
else:
time_step = final_freq
freq_changing = False
def main():
"""Main function (bottom of stack)"""
global instantiated, time_step, freq_changing, final_freq
start = False
usr_choice, trail = get_choice()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Pauses/resumes simulation
if event.type == pygame.MOUSEBUTTONDOWN:
if start is False:
start = True
else:
start = False
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
time_step += day // 4 # accelerates time by 1/4 day
if key[pygame.K_LEFT]:
time_step -= day // 4 # decelerates time by 1/4 day
if key[pygame.K_UP]:
time_step += day // 8 # accelerates time by 1/8 day
print(time_step)
if key[pygame.K_DOWN]:
time_step -= day // 8 # decelerates time by 1/8 day
print(time_step)
if freq_changing:
# allows for a gradual increase in frequency until the desired frequency is met, without "breaking" paths
change_frequency()
# resonant frequencies
if key[pygame.K_0]:
freq_changing = True
final_freq = 0
if key[pygame.K_1]:
freq_changing = True
final_freq = 4946400
if key[pygame.K_2]:
freq_changing = True
final_freq = 6048000
if key[pygame.K_3]:
freq_changing = True
final_freq = 7844400
if key[pygame.K_4]:
freq_changing = True
final_freq = 9248400
if key[pygame.K_5]:
freq_changing = True
final_freq = 11296800
if not instantiated:
if usr_choice == 1:
"""The sun and first 4 planets of our solar system"""
sun = Body("Sun", 1.99 * 10 ** 30, 0, 0, 0, 0, (252, 207, 3), 40)
mercury = Body("Mercury", 3.29 * 10 ** 23, 0, 47.4 * 1000, 0.39 * AU, 0, (213, 210, 209), 6)
venus = Body("Venus", 4.87 * 10 ** 24, 0, 34.8 * 1000, 0.72 * AU, 0, (139, 125, 130), 15)
earth = Body("Earth", 5.97 * 10 ** 24, 0, 29.8 * 1000, 1 * AU, 0, (27, 164, 209), 16)
mars = Body("Mars", 6.39 * 10 ** 23, 0, 24.1 * 1000, 1.52 * AU, 0, (156, 46, 53), 10)
bodies = [sun, mercury, venus, earth, mars]
if usr_choice == 2:
"""Two suns both moving at 7.5 km/s but in opposite directions, with a distance of 2 AU between the two
*undisturbed* parallel paths"""
sun_1 = Body("Sun", 1.99 * 10 ** 30, 0, 7.5 * 1000, -1 * AU, -1 * AU, (252, 207, 3), 40)
sun_2 = Body("Sun", 1.99 * 10 ** 30, 0, -7.5 * 1000, 1 * AU, 1 * AU, (252, 207, 3), 40)
bodies = [sun_1, sun_2]
if usr_choice == 3:
"""Earth orbiting the sun, where sun is stationary relative to observer"""
sun = Body("Sun", 1.99 * 10 ** 30, 0, 0, 0, 0, (252, 207, 3), 40)
earth = Body("Earth", 5.97 * 10 ** 24, 0, 29.8 * 1000, 1 * AU, 0, (27, 164, 209), 16)
bodies = [sun, earth]
if usr_choice == 4:
"""Earth orbiting the sun, but sun is moving relative to observer"""
sun = Body("Sun", 1.99 * 10 ** 30, 5 * 1000, 0, -1 * AU, 0, (252, 207, 3), 40)
earth = Body("Earth", 5.97 * 10 ** 24, 0, 29.8 * 1000, 0, 0, (27, 164, 209), 16)
bodies = [sun, earth]
instantiated = True # Prevents bodies from being recreated
draw(bodies, start, trail)
pygame.display.update()
if __name__ == "__main__":
main()
|
a294d72017236d7a091152a07c126d7aa55a33c6 | CathyZzzzz/CS4701_Project | /Gui.py | 6,385 | 3.625 | 4 | import tkinter as tk
import math
from Board import Board
from AI import AI
# Reference: the main idea of this gui is from github:TongTongX/Gomoku
class Gui_helper(tk.Canvas):
def __init__(self, size = 15, master=None, height=0, width=0):
self.size = size
tk.Canvas.__init__(self, master, height=height, width=width)
self.create_board()
self.Board = Board(size)
self.AI = AI(size)
self.AI.board = self.Board.get_board()
self.player = 2
self.undo = False
self.depth = 2
self.prev_exist = False
self.prev_row = 0
self.prev_col = 0
def create_board(self):
"""
create the Board on the canvas with [size]
"""
#print(self.size)
for i in range(self.size):
start_pixel_x = (i + 1) * 30
end_pixel_x = (i + 1) * 30
start_pixel_y = (0 + 1) * 30
end_pixel_y = self.size * 30
self.create_line(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y)
start_pixel_x = (0 + 1) * 30
start_pixel_y = (i + 1) * 30
end_pixel_x = self.size * 30
end_pixel_y = (i + 1) * 30
self.create_line(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y)
# stars
loc1 = self.size//2//2
loc2 = self.size//2
loc3 = loc2 + loc1 + 1
self.star(loc1,loc1)
self.star(loc3,loc1)
self.star(loc2,loc2)
self.star(loc1,loc3)
self.star(loc3,loc3)
def star(self, row, col):
"""
Place a star at [row, col] for reference
"""
start_pixel_x = (row + 1) * 30 - 2
end_pixel_x = (row + 1) * 30 + 2
start_pixel_y = (col + 1) * 30 - 2
end_pixel_y = (col + 1) * 30 + 2
self.create_oval(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y, fill = 'black')
def stone(self, row, col):
"""
Place a double circle from the last move on the board at [row, col]
"""
loc4 = self.size//2//2+1
loc5 = self.size//2 - 1
loc6 = loc4 + loc5
inner_start_x = (row + 1) * 30 - loc4
inner_start_y = (col + 1) * 30 - loc4
inner_end_x = (row + 1) * 30 + loc4
inner_end_y = (col + 1) * 30 + loc4
outer_start_x = (row + 1) * 30 - loc5
outer_start_y = (col + 1) * 30 - loc5
outer_end_x = (row + 1) * 30 + loc5
outer_end_y = (col + 1) * 30 + loc5
start_pixel_x = (row + 1) * 30 - loc6
start_pixel_y = (col + 1) * 30 - loc6
end_pixel_x = (row + 1) * 30 + loc6
end_pixel_y = (col + 1) * 30 + loc6
if self.player == 1:
self.create_oval(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y, fill='black')
self.create_oval(outer_start_x, outer_start_y, outer_end_x, outer_end_y, fill='white')
self.create_oval(inner_start_x, inner_start_y, inner_end_x, inner_end_y, fill='black')
elif self.player == 2:
self.create_oval(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y, fill='white')
self.create_oval(outer_start_x, outer_start_y, outer_end_x, outer_end_y, fill='black')
self.create_oval(inner_start_x, inner_start_y, inner_end_x, inner_end_y, fill='white')
def prev_stone(self, row, col):
"""
update the stone style to a single circle from previous move at [row, col]
"""
loc4 = self.size//2//2+1
loc5 = self.size//2 - 1
loc6 = loc4 + loc5
start_pixel_x = (row + 1) * 30 - loc6
start_pixel_y = (col + 1) * 30 - loc6
end_pixel_x = (row + 1) * 30 + loc6
end_pixel_y = (col + 1) * 30 + loc6
if self.player == 1:
self.create_oval(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y, fill='white')
elif self.player == 2:
self.create_oval(start_pixel_x, start_pixel_y, end_pixel_x, end_pixel_y, fill='black')
def main_game(self, event):
"""
display the game on gui as well as on terminal
"""
while True:
print('Your turn!!\n')
self.player = 1
invalid = True
# check for the nearest position where the user click
for i in range(self.size):
for j in range(self.size):
pixel_x = (i + 1) * 30
pixel_y = (j + 1) * 30
square_x = math.pow((event.x - pixel_x), 2)
square_y = math.pow((event.y - pixel_y), 2)
distance = math.sqrt(square_x + square_y)
# calculate the distance
if (distance < self.size) and (self.Board.get_board()[i][j] == 0):
self.stone(i, j)
invalid = False
if self.prev_exist == False:
self.prev_exist = True
else:
self.prev_stone(self.prev_row, self.prev_col)
self.prev_row = i
self.prev_col = j
row, col = i, j
# waiting for the AI's move
self.unbind('<Button-1>')
break
else:
continue
break
# invalid position
if invalid:
print('Invalid! Please choose another position!\n')
break
else:
break
# Place a black stone after determining the position
self.Board.get_board()[row][col] = 1
# the player wins
if self.Board.check_winner() == 'Black':
print('BLACK WINS !!')
self.create_text(240, 500, text = 'OMG! You beat the AI!')
self.unbind('<Button-1>')
return 0
# AI's turn
self.player = 2
print('AI needs some time...')
row, col = self.AI.minimax(self.player, self.depth)
coord = '%s%s'%(chr(ord('A') + row), chr(ord('A') + col))
print('AI moves to {}\n'.format(coord))
self.Board.get_board()[row][col] = 2
self.stone(row,col)
if self.prev_exist == False:
self.prev_exist = True
else:
self.prev_stone(self.prev_row, self.prev_col)
self.prev_row = row
self.prev_col = col
self.print_board()
print('\n')
self.bind('<Button-1>', self.main_game)
# the AI wins
if self.Board.check_winner() == 'White':
print('The AI wins!!!')
self.create_text(240, 500, text = 'The AI wins!!!')
self.unbind('<Button-1>')
return 0
def print_board(self):
print(' A B C D E F G H I J K L M N O')
self.Board.check_winner()
for col in range(15):
print(chr(ord('A') + col), end=" ")
for row in range(15):
ch = self.Board.get_board()[row][col]
if ch == 0:
print('.', end=" ")
elif ch == 1:
print('X', end=" ")
elif ch == 2:
print('O', end=" ")
print()
class Gui(tk.Frame):
def __init__(self, size = 15, master = None):
tk.Frame.__init__(self, master)
self.size = size
self.create_widgets()
def create_widgets(self):
self.boardCanvas = Gui_helper(height = 600, width = 500)
self.boardCanvas.bind('<Button-1>', self.boardCanvas.main_game)
self.boardCanvas.pack()
def main():
window = tk.Tk()
window.wm_title("GOMOKU GAME WITH AI")
gui_board = Gui(window)
gui_board.pack()
window.mainloop()
if __name__ == "__main__":
main() |
199672741b05c194355a49ca04cfa9eded050c1e | EyadLotfy/TODO | /TODO/edittask.py | 2,077 | 4.125 | 4 | '''This module is made to edit the tasks'''
def clear_tasks():
'''clear "tasks.txt" file.'''
try:
file_handle = open('tasks.txt', 'w')
except:
print "You haven't added anything to the TODO list, yet!"
return -1
def update_tasks(tasks):
'''update "tasks.txt" file.'''
if clear_tasks() == -1:
return -1
try:
file_handle = open('tasks.txt', 'a')
for task in tasks:
file_handle.write(task)
except:
print "You haven't added anything to the TODO list, yet!"
def edit_task(tasks, task_number, new_task):
'''edits tasks reterieved with the new task edits.'''
try:
if task_number+1 == len(tasks):
tasks[task_number] = '-%s'%new_task
else:
tasks[task_number] = '-%s\n'%new_task
return tasks
except:
print 'Task was not found!'
return -1
def reterieve_tasks():
'''reterieves tasks from "tasks.txt" file.'''
try:
file_handle = open('tasks.txt', 'r')
tasks = file_handle.readlines()
return tasks
except:
print "You haven't added anything to the TODO list, yet!"
return 0
def promote_user_to_insert_the_edit():
'''This function is used to ask the user for the edit'''
new_task = raw_input('Task edit >>>')
return new_task
def promote_user_to_insert_task_number():
'''This function is used to ask the user for the task number.'''
try:
task_number = input('Task number? [EDIT]>>>')
except:
print 'Only numbers accepted!'
return -1
return task_number
def start_edit_task():
'''Starting function.'''
task_number = promote_user_to_insert_task_number()
if task_number == -1:
return 0
if task_number == 0:
print 'Task was not found!'
return 0
tasks = reterieve_tasks()
if tasks == 0:
return 0
edited_tasks = edit_task(tasks, task_number, promote_user_to_insert_the_edit())
if edited_tasks == -1:
return 0
update_tasks(edited_tasks)
return 1
|
3467d81a32136af3174a3ceb9a9ec838da5c1070 | gdibattista/SoftwareDesign | /basic_fortune/basic_fortune.py | 1,239 | 3.796875 | 4 | #!/usr/bin/python
"""
basic_fortune.py
date created: 2014 September 10
This python script is a basic program that allows users to introduce themselves to the computer and receive a fortune message. If another user runs the program and introduces his or herself, it is possible that s/he will receive a different message (provided that the name is of a different length in this version).
Students should use this script to get familiar with the Olin College Software Design course Fall 2014 GitHub repository. Each student should add a message and/or some functionality. We will explore how to get past any merge messes that arise.
author = amonmillner
"""
def fortuna():
"""
This function allows a user to type a name and receive a fortune.
The fortune selected from the list of possibilities depends on the
length of the name or string that a user inputs.
"""
nombre = raw_input('Cual es tu nombre')
fortuna = ['Luego vas a recibir una gran sorpresa', 'Encontraras la felicidad', 'things are looking up', 'a wish that you made in the past is about to come true', 'you will be greeted with a gift in the near future', 'the sky will fall on you tomorrow']
print fortuna[(len(nombre)-1)%len(fortuna)]
fortuna()
|
b15790cb4ee8564e56f117f8d61f620f4e312053 | AndyLee0310/108-1_Programming | /HW044.py | 1,269 | 3.5625 | 4 | """
044.解密碼
小淞是有錢大地主,他將所有金銀財寶都收藏在一個藏寶箱裡,藏寶箱要輸入正確密碼才能開啟。
寶箱密碼寫在一卷捲軸,捲軸內有一組英文句子,由數字 0~9 和大小寫英文字母、空格組成。
解碼方式為將出現在句子的連續數字取出反轉,將所有反轉後的數字相加,則得出密碼。
例如 :
Today is my 45 birthday , There are 65guest come for the 1000 party,I got789gifts t0 open.
則取出其中數字 45,65,1000,789, 和 0, 分別作反轉後相加可得 54+56+1+987+0=1098 ,密碼即為 1098 。
輸入說明 :
輸入為一行的文章,含有 26 個英文字母 ( 大小寫 ) ,及數字 (0~9) 、空格、標點符號、特殊符號任意組合而成。
輸出說明 :
將密碼輸出。
Sample Input
Today is my 45 birthday , There are 65guest come for the 1000 party,I got789gifts t0 open.
Sample Output
1098
"""
import re
words = input()
a = 0
#「r"\d+\d*"」此為re的正規表達式
#\d匹配任意數字
# #" \d+ "則是匹配一次或多次數字," \d* "則是匹配小數點後的數字0次或多次
nums = re.findall(r"\d+\d*",words)
for j in range(len(nums)):
a += int(nums[j][::-1])
print(a) |
ddc787950a1778c6f149ced8b140573f17208cf8 | jarehec/holbertonschool-higher_level_programming | /0x06-python-test_driven_development/5-text_indentation.py | 592 | 4.09375 | 4 | #!/usr/bin/python3
"""Module that prints text with two lines after '.', '?', ':'
"""
def text_indentation(text):
"""Function that prints text with two lines after '.', '?', ':'
@text: text string
"""
if isinstance(text, str) is not True:
raise TypeError("text must be a string")
n_str = text.split()
n_str = " ".join(n_str)
n_str = n_str.replace(".", ".\n\n")
n_str = n_str.replace(":", ":\n\n")
n_str = n_str.replace("?", "?\n\n")
n_str = n_str.replace("\n ", "\n")
# if i == ',' or i == ':' or i == '?':
print(n_str, end='')
|
93b90957b973dad1fe0d48aff3b139a23ef4d92c | ISANGDEV/Algorithm_Study | /2_Simulation/maybe/stats.py | 604 | 3.828125 | 4 | def average(num):
return int(round(sum(num) / len(num), 0))
def median(num):
return sorted(num)[len(num)//2]
def mode(num):
cnt = {}
for i in list(set(num)):
cnt[i] = num.count(i)
a = list(filter(lambda x: cnt[x] == max(cnt.values()), cnt.keys()))
if len(a) > 1:
return sorted(a)[1]
else:
return sorted(a)[0]
def _range(num):
return max(num) - min(num)
num_list = []
n = int(input(''))
for _ in range(n):
num_list.append(int(input('')))
print(average(num_list))
print(median(num_list))
print(mode(num_list))
print(_range(num_list))
|
cbbff565ace2ed078e630b4ef5252c59d48c491f | uc-rosenbkt/it3038c-scripts | /python/nameage.py | 760 | 4.25 | 4 | import time
start_time = time.time()
###comment
print("What is your name?")
myName = input()
print("Hello " + myName + ". That is a good name. How old are you?")
myAge = int(input())
if myAge < 13:
print("You're not even a teenager yet!")
elif myAge == 13:
print("You're a teenager now...yay...")
elif myAge > 13 and myAge < 30:
print("You're young and dumb")
elif myAge >= 30 and myAge < 65:
print("You're adulting...")
else:
print("... and you're not dead yet?")
###set the program age before giving it to the use
programAge = int(time.time() - start_time)
print("%s? That's funny, I'm only %s seconds old." % (myAge, programAge))
print("I wish I was %s years old" % (myAge * 2))
time.sleep(2)
print("I'm tired. I'm done. Goodnight.") |
c4650a02a8b55ea4cef6df84eb8e1f1f631bef10 | Ambrosio-dev/AI_projects | /AI_Project1/Node.py | 1,004 | 3.59375 | 4 |
class Node:
def __init__(self, value=None):
self.misplaced = True
self.value = value
self.up = None
self.down = None
self.right = None
self.left = None
def get_misplace(self):
return self.misplaced
def set_misplaced(self, misplaced):
self.misplaced = misplaced
def get_previous(self):
return self.previous
def set_previous(self, previous):
self.previous = previous
def get_value(self):
return self.value
def set_value(self, value):
self.value = value
def set_up(self, node):
self.up = node
def set_down(self, node):
self.down = node
def set_left(self, node):
self.left = node
def set_right(self, node):
self.right = node
def get_up(self):
return self.up
def get_down(self):
return self.down
def get_right(self):
return self.right
def get_left(self):
return self.left
|
3f4a34fc3f5a572ea6cb9db49fa8595c1c19f215 | zavakare/MyGitPictionairy | /CheckGuess.py | 2,618 | 3.53125 | 4 | #!/usr/bin/env python
#determines whether answer matches chosenWord and saves round info
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import os
import WinnerLoser
roundNumber=0
team1Drawing=0
team2Drawing=0
team1Score=0
team2Score=0
ChosenWord='nada'
# opens files to determine current round, score, and who's turn it is
def openFiles():
global team1Drawing
global team2Drawing
global roundNumber
global ChosenWord
global team1Score
global team2Score
with open("roundInfo.txt","r") as ins:
lines = ins.readlines()
for line in lines:
words = line.split(",")
roundNumber = int(words[0])
team1Drawing = int(words[1])
team2Drawing = int(words[2])
team1Score = int(words[3])
team2Score = int(words[4])
#determines chosen word
with open("drawThis.txt","r") as ins:
lines = ins.readlines()
for line in lines:
words = line.split()
ChosenWord = words[0]
# save info pertaining to playing round
def saveRoundInfo():
print "Saving into file:" + str(roundNumber+1)+','+str(team1Drawing)+','+str(team2Drawing)+','+str(team1Score) +','+str(team2Score)
outf = open('roundInfo.txt', 'w')
outstr = str(roundNumber+1)+','+str(team1Drawing)+','+str(team2Drawing)+','+str(team1Score) +','+str(team2Score)
outf.write(outstr)
outf.close()
# when 4 rounds is over : display
if (roundNumber+1 > 4):
print "END OF GAME"
WinnerLoser.main()
# or restart round
else:
os.system('./killItAgain.sh')
def main():
global team1Score
global team2Score
global team1Drawing
global team2Drawing
root = Tk()
root.minsize(1780, 1080)
openFiles()
result = tkSimpleDialog.askstring("Ask Audience", "What is your guess?")
# if team guesses word correctly :
if(result== ChosenWord):
# message box is displayed
tkMessageBox.showinfo("You got it dude!","Your guess is correct. Your team recieves one point")
# changes score
if (roundNumber % 2 == 0):
team2Score = int(team2Score) + 1
else:
team1Score = int(team1Score) + 1
#saves all information in round
saveRoundInfo()
# if team guesses word incorrectly
else:
# message box is displayed
tkMessageBox.showinfo("You didn't get it dude","Your guess is not correct. You recieve nothing :(")
saveRoundInfo()
root.mainloop()
if __name__ == "__main__":
main()
|
593cf9d4ae9fe207d7571f128c4bb7718926d98b | Ajaysingh647/_HOUSECODER | /alphabet_or_not.py | 263 | 4.40625 | 4 | # write a python program to check whether the character is alphabet or not.
v=int(input('Enter the characters:-'))
if (v>="a" and v<="z") or (v>='A' and v<='Z'):
print('the characters are alphabets ')
else:
print('the characters are not alphabets')
|
32a0df21e425724055b2f149a2ac8517edb15b15 | SabitDeepto/BoringStuff | /chapter4_lists/basic.py | 1,402 | 3.78125 | 4 | # try except
try:
spam = ['cat', 'bat', 'rat', 'elephant']
x = spam[23]
print(x)
except IndexError:
print("An exception occurred")
""" প্রথম ইনডেক্স > শো করে লিস্টের কোন ইনডেক্সে আমি এক্সেস নিবো ,
দ্বিতীয় ইনডেক্স > কত তম ইনডেক্সের ভ্যালু চাই সেইটার জন্য দায়ী ।
spam[1][2] --> [1] দ্বিতীয় লিস্ট [২] দুই নাম্বার ইনডেক্স
output: 30"""
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]]
print(spam[1][2])
# Delete index
spam = ['cat', 'bat', 'rat', 'elephant']
del spam[1]
spam.remove("bat")
# append index
spam.append("apple") #added to the last index
spam.insert(1, "orange")
# loop
name = 'Zophie'
for i in name:
print(f'*********{i}**********')
*********Z**********
*********o**********
*********p**********
*********h**********
*********i**********
*********e**********
# tuple
'''
append() or extend() || remove() or pop() || insert , del
- বলে টাপলে কিছু নাই । যখন রাইট প্রটেক্টেড অনেক গুলা ভ্যালূ কোথাও স্টোর করতে চাই তখন ই টাপল ব্যবহার করবো ।
'''
|
8000760bbb441cc7a0a5089fe766b07c8bdc48a5 | BANSAL-NISHU/JOCP | /Magic_Square.py | 1,698 | 3.9375 | 4 | """
Magic number,M = n(n^2+1)/2
Conditions:
1. In any magic square, 1 is located at position(n/2,n-1).
2. Let's say the position of 1 i.e.(n/2,n-1) is (p,q), then next number which is 2 is located at (p-1,q+1) position.
Anytime if the calculated row position becomes -1 then make it n-1 and if column position becomes n then make it 0.
3. If the calculated position already contains a number, then decrement the column by 2 and increment the row by 1.
4. If anytime row position becomes -1 and column becomes n (together), switch it to (0,n-2).
"""
def MagicSquare(n):
magic_square = []
for i in range(n):
l = []
for j in range(n):
l.append(0)
magic_square.append(l)
i = n // 2 # Condition 1
j = n - 1
num = n * n
count = 1
while (count <= num):
if (i == -1 and j == n): # Condition 4
i = 0
j = n - 2
else:
if (j == n): # Column n -> 0
j = 0
if (i < 0): # Row -1 -> n-1
i = n - 1
if (magic_square[i][j] != 0): # Condition 3
i = i + 1
j = j - 2
continue
else:
magic_square[i][j] = count
count += 1
i = i - 1 # Condition 2
j = j + 1
for i in range(n):
for j in range(n):
print(magic_square[i][j], end=" ")
print()
print("The sum of each row/column/diagonal: " + str(n * (n ** 2 + 1) / 2))
x = int(input("Enter a number: "))
MagicSquare(x)
|
e18fff11d090e3aa5fd5a3c9668c69c67f9c9e9a | abelwong2017/Projects | /IntentApi/wordCounter.py | 959 | 3.6875 | 4 | def findWord(arr):
for sentence in arr:
sentence = sentence.lower()
start_index = sentence.find(label)
end_index = 5
print(sentence)
print("Start position: ", start_index)
print("End position: ", start_index + end_index)
print ("\n")
arr = ["Glasses", "Where can I throw my glasses", "Where can I throw my glass bottles", "I need to dump these glass bottles", "Where is the nearest place to throw glass?", "glasses should be trashed"]
eWaste = [
"phone",
"throw my phone away",
"throw my telephone away",
"throw my mobile phone away",
"where do I recycle my mobile phone",
]
label = "light"
light = [
"light bulbs",
"lighting",
"lights"
"light",
"Throw my light away",
"recycle my lights",
"dump my light bulbs",
]
findWord(light)
|
bb081b16465782a6fcb9ff61813b64b1a7a1cbca | kunalkumar37/allpython---Copy | /string.py | 2,265 | 4.125 | 4 | #multiline strings are """
# """ or three single quote'''
#'''
a="hello world "
print(a[1])
for x in "banana":
print(x)
a="hello world "
print(len(a))
# to check if a certain phrase or character is present in a string we can use the keyboard
# in
txt="the best things in life aare freee!!!"
print("free " in txt)
# use it in an if statemnet
txt="the best things in life are free!!!"
if "!!!!" in txt:
print("yes , free is present ")
else:
print("no prsent in the sting")
#check if not certain chaaracter jor phrase in a string
#using not in
txt="the best things in life are free!!"
if "expensive" not in txt:
print("expensive is not present" )
a="kunal is a good boy"
print(a.upper())
b="kunal is GOOD PROGRAMMER"
print(b.lower())
#remove whitespace
#strip() fucntions remove any whitespace from the beginning and the end
a=" hello, world "
print(a.strip())
#replace("h","j") replcaes the h with j
a="hello world"
print(a.replace("h",'j'))
#split string
#split() method returns a list where the text between the specified separator the list items
#split() method splits the string into substring if it finds instance s of the separaot
a="hello, world, is, a ,first, line, of ,every, programmer"
print(a.split(","))
age=36
#txt="my name is john , i am " + age
print(txt)
#as till now we have learnt we cannot combine string and integer at a time
#but we can combine using format ( ) mathod
age=36
txt="my name is john , and i am {}"
print(txt.format(age))
#the formaat () method takes unlimited number of arguments and are placed into the respective placeholders
quantity=3
itemno=567
price=49.95
myorder="i want {} pieces of item {} for {} dollars."
print(myorder.format(quantity,itemno,price))
#we can use indexes also
# to insert characters that are illegal in a strings use an escape character
#escape character \
#you are not allowed to use double quotes inside the another double quotes
txt="we are the so-called \"vikings\" from the north"
print(txt)
txt = "\x48\x65\x6c\x6c\x6f"
print(txt)
txt = "\110\145\154\154\157"
print(txt)
txt="hello \bworld!!!"
print(txt)
#python has a set of built in methods that you can use on strings
#all strings methods returns new values they don not change the original string
|
9046c6399acbd002f0655e0b3706d7423823e38b | jgingh7/Problem-Solving-Python | /Hard/LongestConsecutiveSequence.py | 822 | 3.515625 | 4 | # https://leetcode.com/problems/longest-consecutive-sequence/
# Time O(n) - O(n + n) because iterate through n, and while loop touches just n elements since it is blocked by "if num - 1 ..."
# Space O(n)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
ans = 0
numsSet = set(nums)
for num in numsSet:
if num - 1 not in numsSet: # if num is the start of the consecutive sequence, start counting length
currSeqLen = 1
while num + 1 in numsSet: # while there is a number 1 above, keep iterating
num += 1
currSeqLen += 1
ans = max(ans, currSeqLen) # after getting currSeqLen, compare it to ans
return ans |
ccddf3ed4c283e75c5fbc8ff4026186b1b1bd9eb | archeranimesh/tth-Introducing-lists | /SRC/Chapter_01-Meet-Lists/01_list_creation.py | 311 | 3.703125 | 4 | a = []
print(type(a))
b = ["Python", "JavaScript", "Java"]
print(b)
languages = ["C#", "Ruby", "Swift"]
print(languages)
print(len(languages))
# There should be one and only one way to do it.
# Boolean Values
print(bool(languages))
print(bool([])) # Empty list is false.
# List are mutable unlike string.
|
070f1fc0be5dad550f4d05ef0cbd69e7375c093e | anudeepb97/Python | /Regular Expressions/reg_exp.py | 697 | 3.765625 | 4 | import re
string = 'Search this inside of this text please!'
# 1
print(re.search('this', string))
# 2
a = re.search('this', string)
print(a.span())
print(a.start())
print(a.end())
# 3
pattern = re.compile('this')
a = pattern.search(string)
print(a.group())
# Multiple searches
b = pattern.findall(string)
print(b)
# 4 Only Full Match
pattern1 = re.compile('Search this inside of this text please!')
c = pattern1.fullmatch(string)
print(c)
# 5 Match ( looks for start of the string and doesn't care about what comes afterwards
string1 = 'Anudeep Search this inside of this text please!'
pattern2 = re.compile('Search this inside of this text please!')
d = pattern2.match(string1)
print(d)
|
e94d97c0a5253af1dc92812c9649c0e036f1baad | lipegomes/python-django-udemy-studies | /Lessons/Section-02/lesson_0030.py | 2,060 | 4.09375 | 4 | # 30. While - Estrutura de repetição em Python
from itertools import product
print("---------------------------------------------------")
male_anime_char = ["Akira", "Goku", "Luffy", "Gajeel", "Ken", "Masaru"]
female_anime_char = ["Emiko", "Hana", "Harumi", "Kaori", "Mayu", "Naomi"]
while True:
print(f"\n{male_anime_char}")
print(f"\n{female_anime_char}")
char = input("\nEnter a name from the lists: ")
for male, female in product(male_anime_char, female_anime_char):
if char in male:
print(f"\nThe character {char} is male.")
break
elif char in female:
print(f"\nThe character {char} is female.")
break
else:
if male != male_anime_char:
print(f"\nThe name {char},is not contained in the lists.")
break
elif female != male_anime_char:
print(f"\nThe name {char},is not contained in the lists.")
break
print("---------------------------------------------------")
pass
x = 0
while x < 10:
if x == 10:
x += 1
break
print(x)
x += 1
print("End")
pass
print("---------------------------------------------------")
while True:
num1 = float(input("Enter a number: ")) # type cast
num2 = float(input("Enter another number: ")) # type cast
operator = input("Enter a numeric operator: ")
# Operators + - / *
if operator == "+":
print(f"The sum between {num1} and {num2} is {num1 + num2}.")
elif operator == "-":
print(f"The subtraction between {num1} and {num2} is {num1 - num2}.")
elif operator == "/":
print(f"The division between {num1} and {num2} is {num1 / num2}.")
elif operator == "*":
print(
f"The multiplication between {num1} and {num2} is {num1 * num2}.")
else:
print(
f"The operator '{operator}' entered is invalid."
f" Enter any of + - / * operators ."
)
continue
break
print("---------------------------------------------------")
|
668a1d716b4d8606f1f088ddee604be0e3f92cc2 | Sakshamgupta20/Python-Programs | /The Full counting sort.py | 1,246 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 17:57:42 2019
@author: Saksham
"""
"""
In this challenge you need to print the string that accompanies each integer in a list sorted by the integers. If two strings are associated with the same integer, they must be printed in their original order so your sorting algorithm should be stable. There is one other twist. The first half of the strings encountered in the inputs are to be replaced with the character "-".
Insertion Sort and the simple version of Quicksort are stable, but the faster in-place version of Quicksort is not since it scrambles around elements while sorting.
In this challenge, you will use counting sort to sort a list while keeping the order of the strings preserved.
20
0 ab
6 cd
0 ef
6 gh
4 ij
0 ab
6 cd
0 ef
6 gh
0 ij
4 that
3 be
0 to
1 be
5 question
1 or
2 not
4 is
2 to
4 the
- - - - - to be or not to be - that is the question - - - -
"""
n=int(input())
a=[[] for i in range(100)]
for i in range(n):
x,s=input().split()
if i < n//2:
s="-"
a[int(x)].append(s)
print(*[element for sublist in a for element in sublist])
|
7599e9acd85516259a46efb9d47aca0932b25318 | Byunggun/TIL | /Visualization/wordcloud1.py | 538 | 3.53125 | 4 | #wordcloud(워드 클라우드)
from wordcloud import WordCloud
import matplotlib.pyplot as plt
#%matplotlib inline
text = "coffee phone phone phone phone phone phone phone phone phone cat dog dog"
# Generate a word cloud image
wordcloud = WordCloud(max_font_size=100).generate(text)
# Display the generated image:
# the matplotlib way:
fig = plt.figure()
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
# plt.savefig('../../assets/images/markdown_img/wordcloud_ex1.svg')
plt.savefig('MyGitHub\NLP/wordcloud_ex1.svg') |
bf215d44669d6a0da0b0f1a9e3b68457259e4bad | abbad/code-snippets-and-algorithms | /python_snippets/master_mind_game.py | 1,417 | 3.734375 | 4 | __author__ = 'Abbad'
"""
This is related to master mind game. This is taken from Cracking the coding interview questions.
Write a method that, given a guess and a solution, return the number of hits and pseudo-hits.
example of output = "RGBY", "GBBY", "YYGG"
Chapter 17 --> moderate.
ex: 17.5
"""
class Result(object):
def __init__(self):
self.hits = 0
self.pseudo_hits = 0
def get_result(self):
return "Hits:" + str(self.hits) + " Pseudo Hits:" + str(self.pseudo_hits)
def estimate(guess, solution):
"""
:param guess: a string of the following combination RGBY
:param solution: a string of the following combination RGBY
:return: Result object
"""
result = Result()
frequencies = {
'R': 0,
'B': 0,
'G': 0,
'Y': 0
}
# loop over the solution and save the hits.
for idx, x in enumerate(solution):
if x == guess[idx]:
result.hits += 1
else:
frequencies[x] += 1
for idx, x in enumerate(guess):
if frequencies[x] > 0 and x != solution[idx]:
result.pseudo_hits += 1
frequencies[x] -= 1
return result
if __name__ == "__main__":
#result = estimate("RGBY", "GGBY")
print estimate("RGYY", "YYYY").get_result() # h: 2 p:0
print estimate("YYYY", "BBBB").get_result()
print estimate("BBGR", "BBGB").get_result()
|
9f44633c3595cf7c02625b55e321a45391997924 | OF222/lesson.py | /AtCoder Beginners Selection/Product.py | 92 | 3.625 | 4 | a, b = map(int,input().split())
p = a * b
if p % 2:
print("Odd")
else:
print("Even") |
222aecbf147e3ca7e35540f68ca3568f9a9a9624 | felipellima83/UniCEUB | /Semestre 01/ProjetoIntegrador1/Aula 04.03.2020/l04e11tabuada.py | 451 | 4.21875 | 4 | ''' 11 Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo:
Tabuada de 5:
5 X 1 = 5
5 X 2 = 10
...
5 X 10 = 50
OBS: Deve ser utilizado a estrutura de repetição "while"
'''
tabuada = int(input("Tabuada do número: "))
i = 0
while i <=10:
print(tabuada, "x", i, "=", tabuada*i)
i+=1 |
c19fb14abaafc86dd890dfa13693b53d856588f0 | pedroareis/Curso_Python | /Exercícios/Aula22.py | 360 | 3.921875 | 4 | nome = str(input('Digite seu nome: ')).strip()
print('Analisando seu nome...')
print('Seu nome em maiúscula é:', nome.upper())
print('Seu nome em minúsculo é:', nome.lower())
print('Seu nome possui {} letras'.format(len(nome) - nome.count(' ')))
separa = nome.split()
print('Seu primeiro nome é {} e possui {} letras'.format(separa[0], len(separa[0])))
|
e353a666f633b17a3812ad9aee37587620b10f7b | Fromsyxs/Blue_Bridge_Cup_Python | /1.rumen/1.1_Fibonacci_斐波那契数列.py | 762 | 3.578125 | 4 | """问题描述
Fibonacci数列的递推公式为:Fn=Fn-1+Fn-2,其中F1=F2=1。
当n比较大时,Fn也非常大,现在我们想知道,Fn除以10007的余数是多少。
输入描述
n
输入格式输入包含一个整数n。
输出描述
输出格式输出一行,包含一个整数,表示Fn除以10007的余数。
说明:在本题中,答案是要求Fn除以10007的余数,因此我们只要能算出这个余数即可,
而不需要先计算出Fn的准确值,再将计算的结果除以10007取余数,直接计算余数往往比先算出原数再取余简单。
数据规模与约定1 <= n <= 1,000,000
"""
n = int(input())
F = [1 for i in range(n+1)]
k = 3
while k <= n:
F[k] = (F[k-1] + F[k-2]) % 10007
k +=1
print(F[n]) |
171391c1004935da02b3d7d87815f38235f2f8a2 | milley/ARTS | /week54/algo/lc138/Solution.py | 1,795 | 3.625 | 4 | from typing import Optional
"""
# Definition for a Node.
"""
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
cached_map = dict()
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head is None:
return None
if self.cached_map.get(head) is None:
head_new = Node(head.val, None, None)
self.cached_map[head] = head_new
head_new.next = self.copyRandomList(head.next)
head_new.random = self.copyRandomList(head.random)
return self.cached_map[head]
def copyRandomList1(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head is None:
return None
cached_map = dict()
p = head
while p:
new_node = Node(p.val, None, None)
cached_map[p] = new_node
p = p.next
p = head
while p:
if p.next:
cached_map[p].next = cached_map[p.next]
if p.random:
cached_map[p].random = cached_map[p.random]
p = p.next
return cached_map[head]
def test1():
solution = Solution()
node7 = Node(7, None, None)
node13 = Node(13, None, None)
node11 = Node(11, None, None)
node10 = Node(10, None, None)
node1 = Node(1, None, None)
node7.next = node13
node7.random = None
node13.next = node11
node13.random = node7
node11.next = node10
node11.random = node1
node10.next = node1
node10.random = node11
node1.next = None
node1.random = node7
new_node = solution.copyRandomList(node7)
if __name__ == '__main__':
test1()
|
353acc4ced19177b409e68f4432235251bfd17b5 | Goal-GeekTime/Python005-01 | /week06/bak/zoo.py | 2,335 | 3.65625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : zoo_.py
@Time : 2021/01/12 23:57:47
@Author : Goal
@Release : 1.0
@Desc :
@Reference : https://github.com/hjjof001/Python005-01/tree/main/week06
"""
"""
【考点1 - Animal 为抽象类】
正确实现。
【考点2 - 是否凶猛动物】
使用另外3个值计算得到,且使用 @perperty 装饰器提供访问,正确实现。
【考点3 - 动物园里同一只动物只能添加一次,且支持 hasattr 查询】
使用 Zoo.__dict__ 保存动物类名来支持 hasattr 查询,正确实现。
"""
from abc import ABCMeta
class Animal(metaclass=ABCMeta):
def __init__(self, kind, shape, character):
self.kind = kind
self.shape = shape
self.character = character
# 是否凶猛动物
@property
def is_ferocious(self):
return self.shape in ['中', '大'] and self.kind == '食肉' and self.character == '凶猛'
class Cat(Animal):
voice = '喵'
def __init__(self, name, kind, shape, character):
super().__init__(kind, shape, character)
self.name = name
@property
def is_pet(self):
if self.is_ferocious:
return False
else:
return True
class Dog(Animal):
voice = '汪'
def __init__(self, name, kind, shape, character):
super().__init__(kind, shape, character)
self.name = name
@property
def is_pet(self):
if self.is_ferocious:
return False
else:
return True
class Zoo(object):
def __init__(self, name):
self.name = name
def add_animal(self, animal):
"""
添加动物
:param animal:
:return:
"""
item = type(animal).__name__
if item not in self.__dict__:
self.__dict__[item] = animal
else:
print(f'{item}已经存在')
if __name__ == '__main__':
# 实例化动物园
z = Zoo('时间动物园')
# 实例化一只猫,属性包括名字、类型、体型、性格
cat1 = Cat('大花猫 1', '食肉', '小', '温顺')
# 增加一只猫到动物园
z.add_animal(cat1)
# 动物园是否有猫这种动物
have_cat = hasattr(z, 'Cat')
print('有') if have_cat else print('无') |
c2cf55f94f069ab5ba43a694e777fd0d6eb43d82 | jacobdpatterson/Python | /.github/BasicTutorial/MinMaxSort.py | 562 | 4.21875 | 4 | stocks = {'GOOG' : 520.54, 'FB' : 76.54, 'YHOO' : 39.28 , 'AMZN' : 306.21, 'AAPL' : 99.76}
# - SPLITTING THIS INTO A LIST OF KEYS AND VALUES
# - You can't sort a dictionary, but you can sort a zipped list (of touples). List thrown in first is how its sorted.
print(min(zip(stocks.values(), stocks.keys()))) # - Lowest price
print(max(zip(stocks.values(), stocks.keys()))) # - Highest Price
print(sorted(zip(stocks.values(), stocks.keys()))) # - Entire list sorted by price.
print(sorted(zip(stocks.keys(), stocks.values()))) # - Entire list sorted by name. |
c21394479239e45602521fa103cd830e6030e205 | Emmalinda/testpoints | /codetest.py | 344 | 3.765625 | 4 | class prime_num:
def prime_num(y):
"""y as function to calculate prime numbers from 0 to n"""
if count > 1:
""" count is any number greater than 1"""
if count == count%1:
return count
"""count is only divisible by 1"""
elif count == count%count:
"""count is only divisible by itself"""
return count
|
2979749d960dcc66738638f3d13368ed09d823b3 | kyungsubbb/Coding-Test | /Baekjoon/Python/2193.py | 127 | 3.515625 | 4 | n = int(input())
arr = [0] * (n+1)
arr[1] = 1
arr[2] = 1
for i in range(2,n+1):
arr[i] = arr[i-1] + arr[i-2]
print(arr[n]) |
be539a08cd8c4261a9764967596fb16a26756e12 | Kai-Chen/the-lambda-club | /python/basic.py | 213 | 3.625 | 4 | def max2(a,b):
return a if a > b else b
def max3(a,b,c):
return max2(max2(a,b),c)
def reverse(s):
return s if len(s) <= 1 else reverse(s[1:]) + s[0]
def reverse2(s):
return ''.join(reversed(s))
|
a38211530e344c2ec57b8225b325f65d86a5ad3d | D-sourav-M044/NSL_RA_TRAINNING | /Data structur algorithm/Week-01/Binary_search.py | 461 | 3.671875 | 4 |
def search(data,num):
begin = 0
end = len(data)-1
index = None
while begin<=end:
mid = int((begin+end)/2)
if num == data[mid]:
index = mid
break
elif num>data[mid]:
begin = mid+1
elif num<data[mid]:
end = mid-1
return index
info = [10,60,70,80,40,100,120]
info = sorted(info)
print(info)
while True:
x = int(input())
y = search(info,x)
print(y) |
48c0037d1cef7f17661e50c57c8e86a609bbedf0 | sshukla31/solutions | /nth_to_the_last_element_singly_link_list.py | 1,718 | 3.953125 | 4 | '''
Implement an algorithm to find the kth to last element of a linked list.
4->3->1->5->6->7->8
k=1, output=7
k=2, output=6
Solution:
1) Create k distance between pointer and end of the node
2) To create a distance, define an extra pointer and move k distance from
the first pointer
Steps:
1) Create 2 pointers and point to head node, say i and j
2) Move pointer j by k positions
3) Move pointer i and j one by one until j reaches end of the node
4) Print value at pointer i
'''
class Node(object):
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
class LinkList(object):
def __init__(self):
self.head = None
self.tail = None
def add(self, data):
new_node = Node(data)
if self.head is None:
self.head = self.tail = new_node
else:
temp = self.tail
temp.next = self.tail = new_node
def find_kth_to_last_element(self, k):
if any([
k is None,
isinstance(k, int) == False,
k < 0
]):
return "Invalid value k: {}".format(k)
i = j = self.head
while(k > 0):
j = j.next
k = k - 1
while(j.next != None):
i = i.next
j = j.next
return i.data
if __name__ == '__main__':
link_list = LinkList()
for val in [4, 3, 1, 5, 6, 7, 8]:
link_list.add(val)
link_list.find_kth_to_last_element(k=1)
link_list.find_kth_to_last_element(k=2)
link_list.find_kth_to_last_element(k='a')
link_list.find_kth_to_last_element(k=None)
link_list.find_kth_to_last_element(k=-1) |
a5ac2b028a45767ba51a485225813b632d897928 | chiahsienlin/NYC_ParkingViolation_Hadoop | /task1/map.py | 651 | 3.671875 | 4 | #!/usr/bin/env python
import sys
import os
from csv import reader
def isINT(value):
try:
int(value)
return True
except:
return False
for s in reader(sys.stdin):
filepath = os.environ.get("mapreduce_map_input_file")
#if "park" in filepath:
if len(s) == 22:
#if(isINT(s[0]) == False or isINT(s[6]) == False or isINT(s[2]) == False):
# continue
print ("{0:s}\t{1:s},{2:s},{3:s},{4:s},{5:s}".format(s[0],"1park",s[14],s[6],s[2],s[1]))
#elif "open" in filepath:
else:
print ("{0:s}\t{1:s},{2:s},{3:s},{4:s},{5:s}".format(s[0],"2open","value","value","value","value"))
|
737f11f3a854ff641f4abf2f537e540e03ad82ee | shasha9/30-days-of-code-hackerrank | /Day_28_RegExPatternsDatabases.py | 723 | 4.28125 | 4 | #Task
#Consider a database table, Emails,
#which has the attributes First Name and Email ID.Given N rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com .
import sys,re
names = []
pattern = re.compile('@gmail.com$')
N = int(input().strip())
for a0 in range(N):
firstName,emailID = input().strip().split(' ')
if pattern.search(emailID):
names.append(firstName)
import sys, re
names = []
pattern=re.compile('@gmail.com$')
N = int(input().strip())
for a0 in range(N):
firstName,emailID=input().strip().split(' ')
if pattern.search(emailID):
names.append(firstName)
names.sort()
for name in names:
print(name)
|
75460f6c43d6d93d1430f936e4e0230fa8b38498 | ulisseslimaa/SOLUTIONS-URI-ONLINE-JUDGE | /Solutions/1173_Preenchimento_de_Vetor_I.py | 143 | 3.5625 | 4 | n = int(input())
vetor = []
inicio = n
for i in range(10):
vetor.append(inicio)
print("N[{}] = {}".format(i,inicio))
inicio+=inicio |
2da253125413e98c8ab1c3f60c94c80b9521ec29 | wyldshadowlore/learningsofaogsfool | /lineofnumbergenerator.py | 91 | 3.625 | 4 | x = 0
while x < 100:
x += 1
print(x)
y= 200
while y > 100:
y= y - 1
print (y)
|
d4c67b0b184d82b25c45984f843a4c856c18c065 | refresh6724/APS | /Jungol/Lv1_LCoder_Python/py60_선택제어문/Main_JO_807_선택제어문_자가진단7-1.py | 378 | 3.90625 | 4 | # 영문 대문자를 입력받아 'A'이면 "Excellent",
# 'B'이면 "Good", 'C'이면 "Usually", 'D'이면 "Effort",
# 'F'이면 "Failure", 그 외 문자열이면 "Mistake"이라고 출력하는 프로그램을 작성하시오.
def switch(x):
print({"A":"Excellent", "B":"Good", "C":"Usually", "D": "Effort", "F":"Failure"}.get(x, "Mistake"))
a = input()
switch(a)
|
165d14253cb81e00e8808d9affb912bd5c2ab88e | joyrahman/ctci_notes | /stare_case.py | 337 | 3.75 | 4 |
def main(test):
stair = [0] * 20
def stair_case(n):
if n<0:
return 0
if n==0:
return 1
if stair[n] == 0:
stair[n] = stair_case(n-1) + stair_case(n-2) + stair_case(n-3)
return stair[n]
print(stair_case(test))
if __name__ == "__main__":
main(1)
main(2)
main(3)
main(4)
|
20e0a307893c5478e81cb2aa3bcb60d9a98440ee | csuzll/python_DS_Algorithm | /3、基本数据结构/orderlist.py | 4,417 | 3.953125 | 4 | # python创建有序链表
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def __str__(self):
return self.getData()
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
class OrderedList:
# 初始化,头结点为空
def __init__(self):
self.head = None
# 判空,O(1)
def isEmpty(self):
return self.head == None
# 获取链表长度,O(n)
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.getNext()
return count
# 增加结点,需要在现有的有序列表中查找新项所属的特定位置。最坏O(n)
def add(self, item):
current = self.head
previous = None
stop = False
# 寻找新结点的位置
while current != None and not stop:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
# 根据位置(开始或者中间)添加
temp = Node(item)
if previous == None: # 插入在头结点位置
temp.setNext(self.head)
self.head = temp
else: # 插入在中间或者尾部
temp.setNext(current)
previous.setNext(temp)
# 删除结点,最坏O(n)
def remove(self, item):
current = self.head # 头结点
previous = None
found = False
stop = False
while current != None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item:
stop = True
else:
previous = current
current = current.getNext()
if found:
if previous == None: # 删除头结点
self.head = current.getNext()
else: # 删除中间或尾部的结点
previous.setNext(current.getNext())
else:
print("Not found!")
# 查询是否存在某个结点,最坏O(n)
def search(self, item):
current = self.head # 从头结点开始查询
found = False # 是否找到
stop = False # 是否停止。如果大于查找值,则停止查找
while current != None and not found and not stop:
if current.getData() == item: # 查找到,True
found = True
else:
# 过了需要查询的值
if current.getData() > item:
stop = True
else:
current = current.getNext() # 查询下一个节点
return found
def pop(self, pos=0):
# 判断pos是否越界
if pos > self.size() - 1 or pos < 0:
print("pos is not ture!")
return
current = self.head
previous = None
# pos为0
if pos == 0:
self.head = current.getNext()
return current.getData()
# pos非0
cur_ind = 0
while cur_ind < pos:
previous = current
current = current.getNext()
cur_ind += 1
previous.setNext(current.getNext())
return current.getData()
# index()查找item是否在链表中,并返回其下标
def index(self, item):
current = self.head
cur_ind = 0
found = False
stop = False
while current != None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item:
stop = True
else:
current = current.getNext()
cur_ind += 1
if found:
return cur_ind
else:
return -1
if __name__ == '__main__':
# 测试
mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)
print(mylist.size())
print(mylist.search(93))
print(mylist.search(100))
|
488e65f13115b4ddf56133e0190923c8c5f1b28c | KabirVerma8163/HaltonCoders | /2021/February/Meet3_25th/pong1.py | 2,445 | 3.796875 | 4 | import sys
import pygame
# Text to RGB
# A dictionary where the color word is the key and the rbg equivalent is the value
Colors = {
"black": (0, 0, 0),
"white": (255, 255, 255),
"red": (255, 0, 0),
"darkRed": (55, 0, 0),
"lightRed": (255, 108, 23),
"green": (0, 255, 0),
"darkGreen": (0, 55, 0),
"blue": (0, 0, 255),
"darkBlue": (0, 0, 55),
"navyBlue": (0, 30, 100),
"lightPurple": (113, 0, 155),
"darkPurple": (55, 0, 55),
"lightGrey": (200, 200, 200),
"paleTurquoise": (175, 238, 238),
"lightYellow": (255, 240, 23)
}
pygame.init() # init stands for initialize
clock = pygame.time.Clock() # Makes a clock in pygame that you can access with the variable 'clock'
# win: window
winWidth, winHeight = 800, 600 # Sets the dimensions of the window
win = pygame.display.set_mode((winWidth, winHeight)) # makes the display(window) with the dimensions you gave
pygame.display.set_caption("Pong") # sets the name of the window
winColor = pygame.Color('grey12') # Sets a color for the window that I will use in the future
paddleWidth, paddleHeight = 10, 90 # sets the dimensions of the paddles
paddleColor = Colors['lightGrey'] # the colour of the paddle
paddleSpeed = 5 # the number of pixels the paddle will move by each time
ballDiameter = 16
ballSpeedX = 4
ballSpeedY = 4
ballStartX = winWidth/2 - ballDiameter/2
ballStartY = winHeight/2 - ballDiameter/2
ball = pygame.rect.Rect(ballStartX, ballStartY, ballDiameter, ballDiameter)
# As the height and width are the same, it will be a square
ballMove = False # Variable for the whether the ball is moving
while True:
keysPressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if keysPressed[pygame.K_SPACE]:
ballMove = not ballMove
if ballMove:
if ball.x < 0:
ballSpeedX = abs(ballSpeedX)
if ball.y < 0:
ballSpeedY = abs(ballSpeedY)
if ball.x + ballDiameter > winWidth:
ballSpeedX = - abs(ballSpeedX)
if ball.y + ballDiameter > winHeight:
ballSpeedY = - abs(ballSpeedY)
ball.x += ballSpeedX
ball.y += ballSpeedY
win.fill(winColor)
pygame.draw.ellipse(win, Colors["lightGrey"], ball)
pygame.display.flip() # update the pygame window/redraw it
clock.tick(60) # in milliseconds
|
ab90762f00c28163be09a8a7f363e6aa08fcac03 | TheXer/CollatzConjecture | /View.py | 448 | 3.515625 | 4 | from typing import List
import matplotlib.pyplot as plt
class GraphView:
"""
View for the 'model' (CollatzCalculation class), shows graphs with the numbers.
"""
def __init__(self):
self.plt = plt
def plot(self, numbers: List[int]):
self.plt.plot(numbers)
for index, number in enumerate(numbers):
self.plt.text(index, number, str(number))
self.plt.grid()
self.plt.show()
|
d7c569397eda1af86aca927281eb381ddfeb8dd3 | sergeiissaev/Kattis-solutions | /detaileddifferences.py | 373 | 3.71875 | 4 | def comparison(s1, s2):
#Print original strings
print(s1)
print(s2)
#Make comparison
for i in range(len(s1)):
if s1[i] == s2[i]:
print(".", end = "")
else:
print("*", end = "")
#Print blank line
print("\n")
for i in range(int(input())):
s1 = str(input())
s2 = str(input())
comparison(s1, s2)
|
393b834ed757d11471a1724f7468d44fe3fce856 | DNCHOW1/Python-Projects | /FactoringPractice/DivisorsModule.py | 1,420 | 4.34375 | 4 | # Better way to find divisors of a number, because it prints it nicely for the eyes
# Also, it's very simple! Since the factor of a number will most likely appear at
# the end, it's just like absolute value. If 1st index, get 2nd last item.
def divisor(num):
num_divisible = []
for i in range(1, num + 1): # +1 so that it includes the number as well
if num % i == 0:
num_divisible.append(i) # If no remainder, will add to the empty list
else: # If remainder, will just keep going
pass
return num_divisible
def match(num): # Function matches the factors, nice to see
divisors = {}
num_divisible = divisor(num)
if len(num_divisible) % 2 == 0: # When len of list is even, there aren't much problems
for i in range(int(len(num_divisible)/2)):
divisors[num_divisible[i]] = num_divisible[0 - (1 + i)] # Will use the -1 to get the last factor,
# As it keeps going, will get 2nd to last, etc.
else: # When len is odd however, won't print
# out the full set of factors, so +1 to iterate fully
for i in range(int(len(num_divisible)/2) + 1):
divisors[num_divisible[i]] = num_divisible[0 - (1 + i)]
return divisors
|
dd86e4303e2e0ce7c4c423a7c29469ad3449dd7c | cbates8/ACS-Online | /Predator vs Prey/Version 3/superturtle_prey.py | 1,436 | 4.03125 | 4 | from turtle import *
from math import sqrt
from random import randint
#######################################################################
# The prey team copies and pastes their superturtle code
# below, and renames their class Superturtle_prey.
#
# Below are empty functions necessary for running the main.py program.
# You will replace the pass command with your code.
#######################################################################
class Superturtle_prey():
''' A class of turtle with enhanced capabilities (methods) '''
def __init__(self, init_x, init_y, init_heading, step, color):
self.__turtle = Turtle()
self.__turtle.color(color)
self.__turtle.penup()
self.__x = init_x
self.__y = init_y
self.__turtle.goto(init_x, init_y)
self.__turtle.setheading(init_heading)
self.__step = step # the amount of movement each time
def start_trace(self):
self.__turtle.pendown()
def get_turtle(self):
return self.__turtle
def get_x(self):
return self.__turtle.xcor()
def get_y(self):
return self.__turtle.ycor()
def distance_to(self, predator):
dist = sqrt((self.get_x() - predator.get_x())**2 + (self.get_y() - predator.get_y())**2)
return dist
def go(self, predator, time):
if self.distance_to(predator) > randint(30,70):
self.__turtle.circle(-50, 50, self.__step)
else:
self.__turtle.circle(60, 40, self.__step)
|
e1d2ff712c03cef54d17dbe668757d1cd9ba8c94 | AnTznimalz/python_prepro | /Prepro2019/0019.py | 251 | 3.609375 | 4 | """0019: Get Digit"""
def main():
"""Func. main"""
num = abs(float(input()))
digit = int(input())
sub_i = int(num)%(10**(digit))
sub_f = int(num)%(10**(digit-1))
want = (sub_i-sub_f)/(10**(digit-1))
print(int(want))
main()
|
378aa90b0a18573f554fffc0a8b15aec19c15929 | ryancarr/PY4E | /exercises/Exercise3-1.py | 436 | 4.125 | 4 | # Name : Exercise3-1.py
# Author : Ryan Carr
# Date : 02/03/19
# Purpose : Calculates pay based on user input hours and rate.
# Capable of handling overtime at time and a half rate
hours = float(input('Enter hours: '))
rate = float(input('Enter rate: '))
if(hours > 40):
hours_over = hours - 40
overtime = hours_over * (rate * 1.5)
pay = 40 * rate + overtime
else:
pay = hours * rate
print('Pay:', pay)
|
aff0ac81ad354e88431f055ba75f29c48d2a5899 | thyua/source-code | /Untitled25.py | 2,528 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
print("input n")
n=input()
#nを代入
print("input W")
W=input()
#Wを代入
if W.isdecimal():
W=int(W)
#Wを数字化
import math
if n.isdecimal():
n=int(n)
i=0
weight=[0]*n
#空リスト作成
value=[0]*n
while i<=n-1:
print("input weight",i)
#iというintは使えなくてstrしかprintの()の中には入れられない。
weight[i]=input()
#数列weight[i]に数字を代入
if weight[i].isdecimal():
weight[i]=int(weight[i])
print("input value",i)
value[i]=input()
if value[i].isdecimal():
value[i]=int(value[i])
i +=1
else:
pass
wlist=[]
vlist=[]
#空リスト作成
k=0
while k<=n-1:
wlist.append(weight[k])
vlist.append(value[k])
#####数列weight[n]をリストとして一つにまとめる
k +=1
else:
pass
from itertools import permutations
wper=permutations(wlist,n)
vper=permutations(vlist,n)
#wlistの全順列=wnの全順列のリスト化 リストの要素の数はn!で要素の一つ一つはn個の数列
wpl =list(wper)
#wperのリスト化
vpl =list(vper)
#vperのリスト化
tlist=[0]*math.factorial(n)
#tを特定、記録するためのリストを作成
s=0
t=0
wsum=[0]*math.factorial(n)
#wsum=[0,0,0,,,,,0] 要素がn!個のリスト
while wsum[s]<W and t<=n-1 and s<=math.factorial(n)-1 :
wsum[s]=wsum[s]+wpl[s][t]
if wsum[s]>W:
tlist[s]=t-1
elif wsum[s]==W:
tlist[s]=t
else:
t +=1
#Wにギリギリまで近づいた時のtを記録 wperの要素の数列w1に対するWに最も近づいた時のtを記録
t=0
#tの初期化
s +=1
break
#ここでsum[s]の最後のwpl[s][t]のtを特定する関数、行tlistを書く→書いた。さらにvperからそれぞれの数列に対する和vsum[s]を出した後、その中での最大値を答えとする。例えばvperの要素の数列、というかリストのvper[0]のvper[0][0]からvper[0][tlist[0]]までの和を出す。得られた数値を全て記録してリスト化してそのリストの最大値が求めるもの。
vsum=[0]*math.factorial(n)
#vsum=[0,0,0,0,0,,,,0]とn!個のリスト。valueの和を出すために作られた。
h=0
d=0
while h<=math.factorial(n)-1 and d<=tlist[h]:
vsum[h]=vsum[h]+vpl[h][d]
d +=1
else:
h +=1
d=0
#vsumの作成
klist=[]
#空リスト作成
p=0
while p<=math.factorial(n)-1:
klist.append(vsum[p])
p +=1
else:
pass
print(max(klist))
|
8eb48d9b6970ac7654c600e508e62f7a55ccac7b | awkyu/YahooWebScrapeTest | /src/webscrape.py | 8,046 | 3.625 | 4 | import requests
from bs4 import BeautifulSoup
from collections import deque
import pandas as pd
import numpy as np
class YahooWebScrapeInstance:
"""
An Instance of a webscrape of recent prices of a given stock symbol
Ex: YahooWebScrapeInstance('ISRG')
"""
def __init__(self, stock_symbol):
self.symbol = str(stock_symbol).upper()
self.url = self.__build_url(self.symbol)
self.dataframe_table = None # Initialize dataframe as None
self.dataframe_table, self.footnotes = self.process_response(self.url)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
@staticmethod
def __build_url(stock_symbol):
"""
simple "private" method to build the url to get stock price history of a given stock symbol
:param stock_symbol: the stock symbol for a corresponding company ('ISRG' is Intuitive Surgical)
:return: the url for the corresponding stock symbol's price history from yahoo
"""
return 'https://finance.yahoo.com/quote/' + str(stock_symbol) + '/history?p=' + str(stock_symbol)
def process_response(self, url):
"""
Processes the html response from the given url
:param url: yahoo stock history url link
:return: DataFrame of the recent stock prices for the given url (which corresponds to a stock symbol)
"""
try:
html_response = requests.get(url)
except requests.HTTPError as he:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(he))
except requests.URLRequired as ur:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(ur))
except requests.TooManyRedirects as tmr:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(tmr))
except requests.ConnectTimeout as ct:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(ct))
except requests.ConnectionError as ce:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(ce))
except requests.ReadTimeout as rt:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(rt))
except requests.Timeout as t:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(t))
except requests.RequestException as re:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(re))
if html_response.status_code == 404:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg="404 Response: Page Not Found.",
status_code=html_response.status_code)
elif html_response.status_code >= 500:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(html_response.status_code)
+ " Response: Server Error. Returned content: "
+ str(html_response.content),
status_code=html_response.status_code)
elif html_response.status_code >= 400:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(html_response.status_code)
+ " Response: Client Error. Returned content: "
+ str(html_response.content),
status_code=html_response.status_code)
elif html_response.status_code != 200:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str(html_response.status_code)
+ " Response. Returned content: "
+ str(html_response.content),
status_code=html_response.status_code)
html_result = html_response.content
soup = BeautifulSoup(html_result, 'html.parser')
html_datatable = soup.find(class_="W(100%) M(0)") # the name of the table class
if html_datatable is None:
raise YahooWebScrapeException(stock_symbol=self.symbol, msg=str("Symbol does not exist."), status_code=-1)
try:
table_elems = html_datatable.find_all('span') # html element in the table class
table_list = deque()
for te in table_elems:
if te.text != "Stock Split": # Account for cases where stock split is in table (example with TSLA)
table_list.append(str(te.text))
else:
table_list.pop()
cols = list(table_list)[0:7] # First seven entries are the column names
for i in range(7): # remove the first seven entries
table_list.popleft()
footnotes = []
for i in range(3): # remove last three entries (which correspond to some additional footnotes)
footnotes.append(table_list.pop())
footnotes.reverse()
footnotes.pop()
date_list = []
open_list = []
high_list = []
low_list = []
close_list = []
adj_close_list = []
vol_list = []
for i in range(int(len(table_list) / 7)):
date_list.append(table_list.popleft())
open_list.append(table_list.popleft())
high_list.append(table_list.popleft())
low_list.append(table_list.popleft())
close_list.append(table_list.popleft())
adj_close_list.append(table_list.popleft())
vol_list.append(table_list.popleft())
dataframe_table = pd.DataFrame(np.array([date_list, open_list, high_list, low_list, close_list,
adj_close_list, vol_list]).transpose())
dataframe_table.columns = cols
except Exception as e:
raise YahooWebScrapeException(msg="Unexpected Exception: " + str(e))
if len(dataframe_table.index) == 0:
raise YahooWebScrapeException(stock_symbol=self.symbol,
msg="Either invalid stock symbol or no information available",
status_code=-1)
return dataframe_table, "".join(footnotes)
def get_days_back(self, days_back):
"""
Returns the i row of the dataframe for this instance where i = days_back
:param days_back: Number of days back that to retrieve the stock price information for this instance
:return: the stock price information for this instance i market days ago where i = days_back;
"""
if self.dataframe_table is not None:
if len(self.dataframe_table.index) - 1 >= days_back >= 0:
return str(self.dataframe_table.iloc[[days_back]]) + "\n" + str(self.footnotes) + "\n"
else:
raise IndexError
return None
class YahooWebScrapeException(Exception):
"""
Custom exception for this Yahoo WebScraping tool
"""
def __init__(self, stock_symbol=None, msg=None, status_code=None):
if msg is None:
if stock_symbol is None:
self.default_msg = "An error occurred while webscraping."
else:
self.default_msg = "An error occurred while webscraping this symbol: " + str(stock_symbol)
else:
if stock_symbol is None:
self.default_msg = "An error occurred while webscraping. " + str(msg)
else:
self.default_msg = "An error occurred while webscraping this symbol: " + str(stock_symbol) + ". " + \
str(msg)
self.status_code = status_code
|
ac26621b9300c6ae08aabb9d59770dd3cab41b21 | O-Seok/python_basic | /online/section06-1.py | 2,744 | 3.8125 | 4 | # Section06-1
# Python 함수식 및 람다(lamda)
# 함수(function)
# 어떠한 반복적이고 중복되는 프로그래밍을 피할 수 있다.
# 하나의 기능을 하는 함수를 만들어야 좋다.
# 함수 선언 위치 중요
# 함수 정의 방법
# def 함수명(parameter):
# code
# 함수 호출
# 함수명(), 함수(parameter)
# 함수 선언 위치 중요
# 함수를 사용할 위치보다 위에서 선언을 해주고, 선언한 위치보다 아래에서 사용한다.
# 예제 1
print()
print('함수 예제 1')
def hello(word):
print('Hello ', word)
hello('Python!')
hello(7777)
# 예제 2 리턴이 있는 함수
print()
print('함수 예제2 리턴이 있는 함수')
def hello_return(word):
val = "Hello " + str(word)
return val
str = hello_return("python!!!!!!!")
print(str)
# 예제 3 다중리턴
print()
print('예제 3 다중리턴')
def func_mul(x):
y1 = x * 100
y2 = x * 200
y3 = x * 300
return y1, y2, y3
val1, val2, val3 = func_mul(100)
print(type(val1), val2, val3)
# 예제 4 다중리턴(데이터 타입변환)
print()
print('예제 4 다중리턴(데이터 타입변환)')
def func_mul2(x):
y1 = x * 100
y2 = x * 200
y3 = x * 300
return [y1, y2, y3]
lt = func_mul2(100)
print(lt, type(lt))
# 예제 4
# *args 매개변수가 몇개가 넘어갈지 모를때, 매개변수가 넘어오는거에 따라서 함수가 다르게 작동할 때
# 다양한 매개변수 형태를 받아서 함수의 흐름이 바뀌는 기능을 원할 때
# 결과 값이 튜플 형태로 나온다.
print()
print('예제 4 *args')
def args_func(*args):
print(args)
args_func('kim')
args_func('kim','park')
print()
print('예제 5')
def args_func2(*args):
for t in args:
print(t)
args_func2('kim')
args_func2('kim','park')
# 이때 enumerate()함수를 사용하여, 인덱스와 값을 출력해줄 수도 있다.
print()
print('예제 6')
def args_func3(*args):
for i, v in enumerate(args):
print(i, v)
args_func3('kim')
args_func3('kim','park')
# kwargs
# 딕셔너리형태로 인자로 받을 수 있고, 출력을 딕셔너리형태로 반환한다.
print()
print('kwargs')
def kwargs_func(**kwargs):
print(kwargs)
kwargs_func(name1='kim', name2='Park', name3='Lee')
# 예제 7
print()
print('예제 7')
def kwargs_func2(**kwargs):
for k, v in kwargs.items():
print(k, v)
kwargs_func2(name1='kim', name2='Park', name3='Lee')
# 전체 혼합
# example_mul()에서 arg1, arg2는 필수 인자
# *args, **kwargs는 가상 인자라 한다.
print()
print('전체 혼합')
def example_mul(arg1, arg2, *args, **kwargs):
print(arg1, arg2, args, kwargs)
example_mul(10, 20)
example_mul(10, 20, 'park', 'kim', age1=24, age2=34)
|
bcd8360fd83d8895e434609856ff37205d052cb6 | shivanimakam/Dcoder_solution_python | /Easy/Jose learns ingles.py | 176 | 3.515625 | 4 | n=int(input())
letters=list(map(str,input().split()))
sorted_letters=sorted(letters,key=str.casefold)
for i in range(len(sorted_letters)):
print(sorted_letters[i],end=' ')
|
3cef11a7b43e58fefb369f65e9dc79a1aab6c340 | rhedshi/project-euler | /python/problems/026_problem.py | 1,075 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Problem 26 - Reciprocal cycles
==============================
A unit fraction contains 1 in the numerator. The decimal representation of the
unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be
seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in
its decimal fraction part.
"""
from utils.number import decimal_fraction
def len_cycle(fraction: str) -> int:
"""
Returns the length of a recurring cycle in a string decimal fraction
if there are any.
"""
if fraction[-1] != ')':
return 0
else:
return len(fraction) - fraction.find('(') - 1
max_cycle = 0
for d in range(1000):
max_cycle = max(len_cycle(decimal_fraction(1, d)), max_cycle)
print(max_cycle)
# Answer: 983
|
53b941f12d9dd3f66a46e3c88895c3c33fe650b8 | marjcobero/100daysofcode | /GUI/study-timer/main.py | 2,385 | 3.65625 | 4 | from tkinter import *
import time
import math
# CONSTANTS
GRAY = "#716F81"
PURPLE = "#B97A95"
ORANGE = "#F6AE99"
YELLOW = "#F2E1C1"
FONT_NAME = "Courier"
WORK_MIN = 1
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
reps = 0
timer = None
# TIMER RESET
def reset():
window.after_cancel(timer)
canvas.config(timer_text, text="00:00")
title.config(text="Timer")
checkmark.config(text="")
global reps
reps = 0
# TIMER MECHANISM
def start_timer():
global reps
reps += 1
work_sec = WORK_MIN * 60
short_break = SHORT_BREAK_MIN * 60
long_break = LONG_BREAK_MIN * 60
if reps % 8 == 0:
countdown(long_break)
title.config(text="Break", fg=PURPLE)
elif reps % 2 == 0:
countdown(short_break)
title.config(text="Break", fg=ORANGE)
else:
countdown(work_sec)
title.config(text="Work", fg=YELLOW)
# COUNTDOWN MECHANISM
def countdown(count):
count_min = math.floor(count / 60) # this will give us the number of minutes
count_sec = count % 60 # modular will help us get the seconds left
if count_sec < 10:
count_sec = f"0{count_sec}" #this will set the timer in seconds to 2 digits
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
global timer
timer = window.after(1000, countdown, count - 1) # It executes a command after a time delay, this is in mls
else:
start_timer()
check = ""
work_sessions = math.floor(reps/2)
for _ in range(work_sessions):
check += "✔️"
checkmark.config(text=check)
# UI SETUP
window = Tk()
window.title("Study Timer")
window.config(padx=100, pady=50, bg=GRAY)
title = Label(text="Timer", fg=ORANGE, bg=GRAY, font=(FONT_NAME, 45))
title.grid(column=1, row=0)
canvas = Canvas(width=452, height=452, bg=YELLOW, highlightthickness=0)
img = PhotoImage(file="clock.png")
canvas.create_image(226, 228, image=img)
timer_text = canvas.create_text(217, 223, text="00:00", fill="black", font=(FONT_NAME, 60, "bold"))
canvas.grid(column=1, row=1)
start = Button(text="start", highlightthickness=0, command=start_timer)
start.grid(column=0, row=2)
reset = Button(text="reset", highlightthickness=0, command=reset)
reset.grid(column=2, row=2)
checkmark = Label(text="✔️", fg=ORANGE, bg=GRAY)
checkmark.grid(column=1, row=3)
window.mainloop() |
78b46fc078069f8d3ae8592e7cc7280a6208ad5a | tash-had/UofTHacksV | /server/Color.py | 620 | 3.890625 | 4 | """
Library to modify colors.
"""
class Color:
"""
A color class that has a name attribute, and an associated RGB value."
"""
def __init__(self, r, g, b):
"""
Initialize a Color object.
:param r: int
:param g: int
:param b: int
"""
self.r, self.g, self.b = r, g, b
def __str__(self):
"""
Return a string method.
:return: String
"""
return str(self.r) + ' ' + str(self.g) + ' ' + str(self.b)
def __eq__(self, other):
return self.r == other.r and self.g == other.g and self.b == other.b
|
b9185f5f28f02e7825075091e6d48cdb42b046b4 | guohaoyuan/algorithms-for-work | /leetcode/bfs/55. 二叉树的深度/maxDepth.py | 1,869 | 3.8125 | 4 | # -*- coding : utf-8 -*-
class Solution(object):
def maxDepth(self, root):
"""
:param root:
:return:
"""
# 1. 递归结束条件,越过叶子节点
if not root:
return 0
# 2. 递归操作
# 分别看左右子树的深度
depthLeft = self.maxDepth(root.left)
depthRight = self.maxDepth(root.right)
return depthLeft + 1 if depthLeft > depthRight else depthRight + 1
"""
非递归操作
"""
import collections
class Solution1:
def maxDepth(self, root):
if not root:
return 0
queue = collections.deque()
queue.append(root)
depth = 0
while queue:
# print(queue)
size = len(queue)
for i in range(size):
cur = queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
depth += 1
return depth
"""
将深度融入到queue中
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0
# 创建队列,根节点进入队列,何其状态
queue = collections.deque()
queue.append((root, 1))
while queue:
# 记录队列长度
size = len(queue)
for i in range(size):
cur, depth = queue.popleft()
# 将左右孩子入队
if cur.left:
queue.append((cur.left, depth + 1))
if cur.right:
queue.append((cur.right, depth + 1))
return depth |
12cd39fa9983f2d2ce64159614ade6e3483ffa9a | RoboPlusPlus/Div-Python--JW | /PyQt5 div/object_class.py | 1,128 | 3.578125 | 4 | class BaseOject:
object_type = ""
def __init__(self, _object_type):
self.object_type = str(_object_type)
self.di_list = []
self.do_list = []
self.ai_list = []
self.ao_list = []
def get_object_type(self):
return str(self.object_type)
def add_di_entry(self, _input):
self.di_list.append(str(_input))
def add_do_entry(self, _input):
self.do_list.append(_input)
def add_ai_entry(self, _input):
self.ai_list.append(_input)
def add_ao_entry(self, _input):
self.ao_list.append(_input)
def get_di(self):
return str(self.di_list)
def get_do(self):
return self.do_list
def get_ai(self):
return self.ai_list
def get_ao(self):
return self.ao_list
def main():
objectlist = []
for i in range(5):
objectlist.append(BaseOject(str(i)))
hest = BaseOject("Hest")
a=1
for o in objectlist:
o.add_di_entry(str(a))
a= a+1
for ob in objectlist:
print(ob.get_di())
print(hest.get_di())
if __name__ == '__main__':
main() |
0991c45df9e2d240fbe7ddc8778df15169ea1b12 | gitaumoses4/VersionControl | /fibonanci.py | 169 | 3.953125 | 4 | def fib(end):
if end > 2:
fib = [0,1]
for i in range(1,end-1):
fib.append(fib[i]+fib[i-1])
return fib
else:
return "{0} is not greater than 2".format(end)
|
3b42b1c4542957da401bfbd9f53ce1380838825f | prasanna86/fun_with_programming | /hashing/movie_times.py | 2,055 | 3.640625 | 4 | import unittest
import numpy as np
def build_hash_table(movie_times_list):
table = {}
for t in movie_times_list:
if t in table.keys():
table[t] += 1
else:
table[t] = 1
return table
def has_two_movie_times(movie_times_list, flight_length):
table = build_hash_table(movie_times_list)
for t in table.keys():
if flight_length-t in table.keys():
if flight_length-t == (flight_length / 2) and table[flight_length-t] == 1:
return 0
return 1
def has_two_movie_times_sorting(movie_lengths, flight_length):
sorted_movie_lengths = sorted(movie_lengths)
start = 0
end = len(movie_lengths)-1
while(start < end):
if(sorted_movie_lengths[start] + sorted_movie_lengths[end] == flight_length):
return True
elif(sorted_movie_lengths[start] + sorted_movie_lengths[end] > flight_length):
end = end - 1
else:
start = start + 1
return False
class Test(unittest.TestCase):
def test_short_flight(self):
result = has_two_movie_times([2, 4], 1)
self.assertFalse(result)
def test_long_flight(self):
result = has_two_movie_times([2, 4], 6)
self.assertTrue(result)
def test_one_movie_half_flight_length(self):
result = has_two_movie_times([3, 8], 6)
self.assertFalse(result)
def test_two_movies_half_flight_length(self):
result = has_two_movie_times([3, 8, 3], 6)
self.assertTrue(result)
def test_lots_of_possible_pairs(self):
result = has_two_movie_times([1, 2, 3, 4, 5, 6], 7)
self.assertTrue(result)
def test_not_using_first_movie(self):
result = has_two_movie_times([4, 3, 2], 5)
self.assertTrue(result)
def test_only_one_movie(self):
result = has_two_movie_times([6], 6)
self.assertFalse(result)
def test_no_movies(self):
result = has_two_movie_times([], 2)
self.assertFalse(result)
unittest.main(verbosity=2)
|
ddb7de4327f6126a56f46735c3f0ef6189b8ac3c | Brendan-Lucas/CENGC | /ItemInput.py | 1,988 | 3.65625 | 4 | import Validations as validate
import datetime
MAX_VOLUME = 80000
TAX_RATE = 23
def get_name():
while(True):
name = raw_input("Item Name: ")
validation = validate.validate_name(name)
if validation:
print (validation)
else:
return name
def get_volume(remaining_storage):
while (True):
volume = input("Container volume: ")
validation = validate.validate_volume(volume, remaining_storage)
if validation:
print (validation)
else:
return volume
def get_price():
while (True):
price = input("Item price: ")
validation = validate.validate_price(price)
if validation:
print validation
else:
return price
def get_expiration():
while (True):
days = input("Number of days until item expires: ")
validation = validate.validate_expiration(days)
if validation:
print (validation)
else:
return days
def expiration_days_tpatho_date(days):
today = datetime.date.today()
timedelta = datetime.timedelta(days=days)
expiration_date = today + timedelta
return expiration_date
def apply_tax(price):
return price * TAX_RATE * 0.01
def remaining_storage(current_volume):
return MAX_VOLUME - current_volume
def get_item_from_user(current_volume):
item = {"name": "",
"volume": 0,
"price_before_tax": 0,
"price_after_tax": 0,
"expiry_date": None,
"date_added": None}
item["name"] = get_name()
item["volume"] = get_volume(remaining_storage(current_volume))
price = get_price()
item["price_before_tax"] = price
item["price_after_tax"] = apply_tax(price)
expiration_days = get_expiration()
item["expiry_date"] = expiration_days_to_date(expiration_days)
item["date_added"] = datetime.date.today()
return item
print get_item_from_user(40000) |
9c7fd8d64826b65abdd6aa8207483b11b3ac0a32 | thefirstcommonname1/linear_regression | /game_of_9.py | 2,509 | 3.90625 | 4 | #game of 9
import random
board = [[0,0,0],
[0,0,0],
[0,0,0]]
x = []
winning_board = [[1,2,3],
[4,5,6],
[7,8," "]]
print("""Arrange the board in ( 1 2 3
4 5 6
7 8 _ ) layout to win.
Use wasd to move the pieces into the emtpy square.
Good luck!""")
for i in range(len(board)):
for j in range(len(board[i])):
random_board = random.randint(1,9)
while random_board in x:
random_board = random.randint(1,9)
board[i][j] = random_board
x.append(random_board)
def over_engineered():
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 9:
board[i][j] = " "
indexI = i
indexJ = j
return indexI, indexJ
over_engineered()
def print_board():
for i in range(len(board)):
for j in range(len(board[i])):
print(board[i][j]," ",end='')
print()
print_board()
def check_under():
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == " ":
return i, j
def play(indexI, indexJ):
character = board[indexI][indexJ]
direction = input("wasd: ")
if direction == "a":
if not check_illegal(indexI, indexJ+1):
tmp = board[indexI][indexJ + 1]
board[indexI][indexJ + 1] = " "
board[indexI][indexJ] = tmp
if direction == "d":
if not check_illegal(indexI, indexJ-1):
tmp = board[indexI][indexJ - 1]
board[indexI][indexJ - 1] = " "
board[indexI][indexJ] = tmp
if direction == "s":
if not check_illegal(indexI-1, indexJ):
tmp = board[indexI-1][indexJ]
board[indexI-1][indexJ] = " "
board[indexI][indexJ] = tmp
if direction == "w":
if not check_illegal(indexI+1, indexJ):
tmp = board[indexI+1][indexJ]
board[indexI+1][indexJ] = " "
board[indexI][indexJ] = tmp
print_board()
def won():
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] != winning_board[i][j]:
return False
return True
def check_illegal(indexI, indexJ):
return indexI < 0 or indexI > 2 or indexJ < 0 or indexJ > 2
while not won():
i,j = check_under()
play(i, j)
print("\n\n\nCongratulations You have won the game!!!")
|
0c5f3aa661777dc88830fe3fed2af2164b9777b0 | Dharnisingh/Python | /Class/static_method.py | 544 | 3.71875 | 4 | # Static methods are bound to the class not object
# Can not access or modify state of class
# static method can access Class variable
class Emp:
# Class variable
raise_amt = 10
def __init__(self, emp_name):
self.name = emp_name
def get_name(self):
print("My name {}".format(self.name))
# stati method
@staticmethod
def get_raise(var1):
print("Raise amt of {} is {}".format(var1,Emp.raise_amt))
emp1 = Emp("Dr.John")
emp1.get_name()
# Calling static method
Emp.get_raise("My_Name")
|
ed436797a7c061b450d02f11e9121343be880193 | nallagondas/python-1 | /scripts/SphereVolume.py | 299 | 4.34375 | 4 | # 4. Write a Python program to find the volume of a sphere with diameter 12 cm.
# Formula: V=4/3 * π * r 3
# Formula using diameter : V=1/6 * π * d 3
piVar = 3.1415926535897931
diameter = 12
volume = 1.0/6.0 * piVar * diameter ** 3
print('The volume of the sphere with diameter 12 is : ', volume) |
666d024de36139f968f4a229a1c529b7be45a2c2 | lovebet888/fullstack_s9 | /one_chapter/day17课堂笔记/test17.py | 5,104 | 3.796875 | 4 | '''----------------------------------------------作业----------------------------------------------------------'''
# 3.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
'''我的默写
name=['alex','wupeiqi','yuanhao','nezha']
new_name = map(lambda l:l+'_sb',name)
print(list(new_name))
'''
# name=['alex','wupeiqi','yuanhao','nezha']
# def func(item):
# return item+'_sb'
# ret = map(func,name) #ret是迭代器
# for i in ret:
# print(i)
# print(list(ret))
# ret = map(lambda item:item+'_sb',name)
# print(list(ret))
# 4.用filter函数处理数字列表,将列表中所有的偶数筛选出来
'''
num = [1,3,5,6,7,8]
num1 = filter(lambda x:x%2==0,num)
for i in num1:
print(i)
'''
# num = [1,3,5,6,7,8]
# def func(x):
# if x%2 == 0:
# return True
# ret = filter(func,num) #ret是迭代器
# print(list(ret))
#
# ret = filter(lambda x:x%2 == 0,num)
# ret = filter(lambda x:True if x%2 == 0 else False,num)
# print(list(ret))
'''# filter 执行了filter之后的结果集合 <= 执行之前的个数
#filter只管筛选,不会改变原来的值
# map 执行前后元素个数不变
# 值可能发生改变'''
# 5.随意写一个20行以上的文件
# 运行程序,先将内容读到内存中,用列表存储。
# 接收用户输入页码,每页5条,仅输出当页的内容
'''逻辑功能太简单没有用到内置函数
def out_p(num):
with open('log17',encoding='utf-8') as f:
line = f.readline()
# list(line)
print(type(line))
# print(line[5*(num-1):5*num-1])
# for i in line [5*(num-1):5*num-1]:
# print(i.strip())
out_p(3)
'''
# with open('file',encoding='utf-8') as f:
# l = f.readlines()
# page_num = int(input('请输入页码 : '))
# pages,mod = divmod(len(l),5) #求有多少页,有没有剩余的行数
# if mod: # 如果有剩余的行数,那么页数加一
# pages += 1 # 一共有多少页
# if page_num > pages or page_num <= 0: #用户输入的页数大于总数或者小于等于0
# print('输入有误')
# elif page_num == pages and mod !=0: #如果用户输入的页码是最后一页,且之前有过剩余行数
# for i in range(mod):
# print(l[(page_num-1)*5 +i].strip()) #只输出这一页上剩余的行
# else:
# for i in range(5):
# print(l[(page_num-1)*5 +i].strip()) #输出5行
'''---------------------------------二分查找法------------------------------------------'''
'''逻辑需要再次明确
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
def find(l,aim,start=0,end=None):
end = len(l) if end is None else end
#少一个start,没有考虑从整个l出发
mid_index = (end-start)//2+start
#卡住了怎么把开始和结束传到这个函数,定义一个中间变量好想法我没想到,最外层少了一个if else
if start<= end:
if aim > l[mid_index]:
return find(l,aim,start = mid_index+1,end=end)
elif aim<l[mid_index]:
return find(l,aim,start=start,end=mid_index-1)
#这里else返回mid_index
else:
return mid_index
else:
return '找不到'
ret = find(l,44)
print(ret)
'''
#正确的
# def find(l,aim,start = 0,end = None):
# end = len(l) if end is None else end
# mid_index = (end - start)//2 + start
# if start <= end:
# if l[mid_index] < aim:
# return find(l,aim,start =mid_index+1,end=end)
# elif l[mid_index] > aim:
# return find(l, aim, start=start, end=mid_index-1)
# else:
# return mid_index
# else:
# return '找不到这个值'
#
#
# ret= find(l,44)
# print(ret)
'''--------------------------------------------递归函数与三级菜单--------------------------------------'''
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龙观': {},
},
'朝阳': {},
'东城': {},
},
'上海': {
'闵行': {
"人民广场": {
'炸鸡店': {}
}
},
'闸北': {
'火车战': {
'携程': {}
}
},
'浦东': {},
},
'山东': {},
}
def threeLM(dic):
while True:
for k in dic:print(k)
key = input('input>>').strip()
if key == 'b' or key == 'q':return key
elif key in dic.keys() and dic[key]:
ret = threeLM(dic[key])
if ret == 'q': return 'q'
threeLM(menu)
'''逻辑问题''' |
469af7170cdb1953b078ac7cd587f9bf18127d43 | emelynsoria/more_python | /activities/pat_future_past.py | 471 | 3.765625 | 4 | import datetime
no_of_days = [355, 210, 125, 98, 30, 2]
today = datetime.datetime.now()
for days in no_of_days:
future = today + datetime.timedelta(days)
past = today - datetime.timedelta(days)
print(
str(days)
+ "days from now ---"
+ str(datetime.datetime.strftime(future, "%b. %d %Y %H:%M:%S"))
)
print(
str(days)
+ "days ago ---"
+ str(datetime.datetime.strftime(past, "%b. %d %Y %H:%M:%S"))
)
|
7f548b7683eeb683b54c4cb0922a23877a32bb24 | deepikaasharma/depends-on-the-type | /main.py | 414 | 3.609375 | 4 | # define your function here
def depends_on_the_type(x):
if type(x)is bool:
return False
#if str
elif type(x) is str:
return x+x
#if float
elif type(x) is float:
return x*1.5
#if int
elif type(x) is int:
#if obj=0
if x==0:
return "Zero"
elif x%2==0:
return x*x
else:
return x*x*x
else:
return None
print(depends_on_the_type(True))
#none of them |
12f1ecd5e79d80fed778c85a59061c38c233b9ee | JamesBond0014/Euler-Project | /Problem 1 -Multiples of 3 and 5.py | 212 | 3.796875 | 4 | def sum(x):
return (x*(x+1))//2
upper = 1000-1
count3 = upper//3
count5 = upper//5
count15 = upper//15
total3 = sum(count3)
total5 = sum(count5)
total15 = sum(count15)
print(total3*3+total5*5 - total15*15) |
b0baaf3e3c5655b4271be71f53b53f798bcf1022 | reichlj/PythonBsp | /Schulung/py06_ausnahme/ex_06_exception_hierarchie1.py | 303 | 3.640625 | 4 | def f(x):
try:
z = 10/x
return z
except ZeroDivisionError as e:
print('F: Fixing the exception in f:',e)
try:
y = 0
iy = f(y)
except ZeroDivisionError as e:
print('Main: Fixing the exception in main:',e)
print('Main: Program continues')
|
a2cdfbd7001565128ae70e3aaaa0a0ec87ca92af | nerunerunerune/kenkyushitukadai | /07.py | 368 | 4.0625 | 4 | #ITP1_2_C:Sorting Three Numbers
#3つの整数を読み込み、それらを値が小さい順に並べて出力するプログラムを作成
#Write a program which reads three integers, and prints them in ascending order.
l = input().split()
a = int(l[0])
b = int(l[1])
c = int(l[2])
if(1<a,b,c and a,b,c<10000):
a,b,c = sorted(l)
print(a,b,c)
|
2dd91af4124b379b4ed1e85538f329ceb0c3ff25 | Nilsonsantos-s/Python-Studies | /Mundo 3 by Curso em Video/Exercicios/077.py | 421 | 3.890625 | 4 | # tupla com varias palavras, e mostrar quais verbos está dentro de cada um.
palavras = ('palavras','mostrar','verbos','dentro','cada','melhores','nacional','codigo','escrever','jogar','divertir','python','ler','nascer')
for c in range(0,len(palavras)):
print(f' As vogais da palavra {palavras[c]: <10} São : ',end=' ')
for x in palavras[c]:
if x in 'aeiou':
print(x, end=' ')
print('')
|
7993277912b92957f25a5c6b700ddc65506aecd4 | rOY369/Docs | /python_design_patterns/builder_pattern/with_pattern/computer.py | 308 | 3.5 | 4 | class Computer:
def display(self):
print(F"CASE --> {self.case}")
print(F"MAIN BOARD --> {self.mainboard}")
print(F"CPU --> {self.cpu}")
print(F"MEMORY --> {self.memory}")
print(F"HARD DRIVE --> {self.hardDrive}")
print(F"VIDEO CARD --> {self.videoCard}")
|
ca1bfa1ced272766657c4e901da48f312e273f2a | allybrannon/DC_day2 | /try.py | 251 | 3.765625 | 4 | droids = '100'
try:
print(3-droids)
except TypeError:
print("what is wrong with droids...is it a string or a number?")
try:
print(int(droids) / 0)
except ZeroDivisionError:
print("You casted droids into int...but you divided by 0!")
|
066dd131ab02ad0c4b85127f27b95b7e519b1612 | chanish-teramatrix/python-practiceCodes | /python_practice/prac2.py | 1,279 | 4.1875 | 4 | #built in function, methods of list
list1 = ['india','america',1947,1990,'pak','Aus']
rand1 = [54,564,654,4,52,12,85,41,21,841,521,212,1,64,66,72]
rand2 = [54,5,521,1,8,4,12,1,584,854,31313,896,34,66,12,82]
list2 = ['a','b','c','d','e']
tupl = ('x','y','z')
print list1[:-2] #start from 2+1 element from right and prints towards left till the end of list
print list1[-1] #will print right most element of list
print cmp(rand1, rand2) #list comparision
print len(rand1) #will give length of list
print max(rand1) #returns maximum value of list
print min(rand1) #returns minimum value of list
print list(tupl) #tuple to list conversion
#appending is next- appending value -3 to rand1
rand1.append(-3)
print rand1
print rand1.count(1) #will tell how many times 1 has been appeared in list rand1
list1.extend(tupl) #will append values of tupl in list
print list1
print rand1.index(841) # tell the indexing of vlaue in list
rand1.insert(1,55) # will add 55 at poisition in list rand1
print rand1
rand1.remove(55) #removes obj in list
print rand1
rand1.reverse()
print rand1
print max(rand1)
rand1.sort()
print rand1 #provides sorted sequence of elements
rand2.reverse()
print rand2
print max(rand2)
rand2.sort()
print rand2 #provides sorted sequence of elements
|
7fb750b89faddbf8115842e13a2f7da7074604c3 | izharabbasi/OOp-Part-2 | /raise_error2.py | 450 | 3.65625 | 4 | class Mobile:
def __init__(self, name):
self.name = name
class MobStore:
def __init__(self):
self.mobile = []
def add_phone(self, new_mobile):
if isinstance(new_mobile, Mobile):
self.mobile.append(new_mobile)
else:
raise TypeError("you cannot pass ")
phone = Mobile("one plus")
samsung = "s8"
mobile_store = MobStore()
mobile_store.add_phone(phone)
print(mobile_store.mobile)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.