blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
583e0240ea29239e19dff725257fddd772d802b4 | bjmay3/Supervised-Learning-Algorithms | /DecisionTrees_Car.py | 6,635 | 3.59375 | 4 | # Decision Tree classification (Car Evaluation)
# Part A - Data Preparation
# Import the necessary libraries
import numpy as np
import pandas as pd
import os
import graphviz
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn import tree
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import cross_val_score
from sklearn.metrics import confusion_matrix
# Set the working directory (set to directory containing the dataset)
os.chdir('C:\\Users\Brad\Desktop\Briefcase\Personal\GeorgiaTechMasters\CS7641_MachineLearning\Homework\Homework1')
# Import the dataset and collect some high-level information on it
dataset = pd.read_csv('CarRatingDataset.csv')
print ("Dataset Length = ", len(dataset))
print ("Dataset Shape = ", dataset.shape)
print (dataset.head())
# Break up the dataset into X and Y components
X = dataset.iloc[:, :6].values
Y = dataset.iloc[:, 6].values
print(X[:10, :])
print(Y[:10])
# Encode the categorical data
# Encode the Independent variables
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
X[:, 2] = labelencoder_X.fit_transform(X[:, 2])
X[:, 3] = labelencoder_X.fit_transform(X[:, 3])
X[:, 4] = labelencoder_X.fit_transform(X[:, 4])
X[:, 5] = labelencoder_X.fit_transform(X[:, 5])
onehotencoder = OneHotEncoder(categorical_features = [0, 1, 2, 3, 4, 5])
X = onehotencoder.fit_transform(X).toarray()
X_Headers = np.array(['BuyPrice_high', 'BuyPrice_low', 'BuyPrice_med',
'BuyPrice_vhigh', 'MaintPrice_high', 'MaintPrice_low',
'MaintPrice_med', 'MaintPrice_vhigh', '2-door', '3-door',
'4-door', '5more-door', '2-pass', '4-pass', '5more-pass',
'Luggage_big', 'Luggage_med', 'Luggage_small',
'safety_high', 'safety_low', 'safety_med'])
print(X_Headers)
print(X[:10, :])
# Encode the dependent variable
labelencoder_Y = LabelEncoder()
Y = labelencoder_Y.fit_transform(Y)
Y_Results = np.array(['0=acc', '1=good', '2=unacc', '3=vgood'])
print(Y_Results)
print(Y[:10])
# Split the dataset into the Training set and Test set (25% test)
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25,
random_state = 0)
# Part B - Run Decision Tree model without pruning
# Also ran this model with min_impurity_decrease = 0.025 & 0.05
# Determine Decision Tree classifier on the training set & cross-validate
# Classifier can split leaves to lowest level possible
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0,
min_impurity_decrease = 0,
min_samples_split = 2)
scores = cross_val_score(classifier, X_train, y_train, cv=10)
print('Mean = ', np.mean(scores))
# Based on cross-validation, should predict with 97.4% accuracy
# Fit the classifier and display decision tree results in PDF file
classifier.fit(X_train, y_train)
dot_data = tree.export_graphviz(classifier, out_file=None,
feature_names = X_Headers)
graph = graphviz.Source(dot_data)
graph.render('Cars')
# PDF file saves to working directory
# 15 layers from root to lowest-level leaves
# Part C - Run Decision Tree model with pruning
# Also ran this model with min_impurity_decrease = 0.05 and
# min_samples_split = 7.5% and 10% of total records
# Prune the Decision Tree & cross-validate
# Leverage both "Minimum Sample Split" and "Minimum Impurity Decrease"
# Use different entries for these and measure accuracy and tree layers
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0,
min_impurity_decrease = .025,
min_samples_split = 86)
scores = cross_val_score(classifier, X_train, y_train, cv=10)
print('Mean = ', np.mean(scores))
# 0.025 and 5% of data were used for Min Impurity Decrease & Min Sample Split
# These were determined to be optimal based on trial and error
# Based on cross-validation, should predict with 84.2% accuracy
# Fit the classifier and display decision tree results in PDF file
classifier.fit(X_train, y_train)
dot_data = tree.export_graphviz(classifier, out_file=None,
feature_names = X_Headers)
graph = graphviz.Source(dot_data)
graph.render('Cars1')
# PDF file saves to working directory
# 8 layers from root to lowest-level leaves
# Part D - Make predictions on the test data based on training model chosen
# Make predictions on the test data and calculate the Confusion Matrix
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(Y_Results)
print(cm)
print('Accuracy = ', accuracy_score(y_test, y_pred))
# Based on the test data, pruned model predicts with 86.1% accuracy
# Misclassifies 14 as unacceptable that should have been acceptable or better
# Misclassifies 20 as acceptable that should have been unacceptable
# Part E - Determine model performance over several training/test splits
# Measure model accuracy over a variety of test set sizes
train = []
test = []
splits = [0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8]
for split in splits:
# Split the dataset into the Training set and Test set varying test set size
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 1 - split,
random_state = 0)
# Use classifier parameters that have been pre-determined
classifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0,
min_impurity_decrease = .025,
min_samples_split = 86)
classifier.fit(X_train, y_train)
train.append(1 - classifier.score(X_train, y_train))
test.append(1 - classifier.score(X_test, y_test))
# Graph results
plt.plot(splits, train, color='blue', label='Training Set')
plt.plot(splits, test, color='orange', label='Test Set')
plt.legend()
plt.xlabel('Training Size Pct')
plt.ylabel('Error Rate')
plt.title('Error Rate vs Training Size')
plt.grid(True)
plt.show()
# Training error rate varies but is fairly flat across training set sizes
# Test error rate improves with higher training size
|
7e885a9d995a88509f2b11c403bad91fa771331e | jhagstrom/aoc | /2018/day_2.1.py | 438 | 3.65625 | 4 | from collections import Counter
indata_file = open("./2018/input_day2.txt", "r")
indata_txt = indata_file.readlines()
number_of_threes = 0
number_of_twos = 0
for line in indata_txt:
line = line.strip('\n')
characters = list(line)
counts = list(Counter(characters).values())
if(3 in counts):
number_of_threes += 1
if(2 in counts):
number_of_twos += 1
print("Checksum: ", number_of_threes*number_of_twos) |
63756dbda9070dd378118718383a7dbebcc469d9 | haaks1998/Python-Simple | /07. function.py | 1,011 | 4.1875 | 4 | # A function is a set of statements that take inputs, do some specific computation and returns output.
# We can call function any number of times through its name. The inputs of the function are known as parameters or arguments.
# First we have to define function. Then we call it using its name.
# format:
# def func_name(arg1,arg2,..,argN):
# function statements
# return result
def add(a,b): #Function defination
c = a+b
return c
# Indentation shows that which statements are the part of functions.
# The indented statements are considered to be the part of function. Non indented statements are not part of function
# The code which is indented is in the body block and double indented code creates a block within a block
x = int(input("Enter first number "))
y = int(input("Enter second number "))
ans = add(x,y) #Function call
print(ans)
input("\nPress any key to exit")
|
de812af47c00f567c7ad8771d8e182d31f83b2dc | haaks1998/Python-Simple | /08. lambda.py | 3,025 | 4.375 | 4 | # lambda function are single line and single use functions
# often called as throw away functions
# format function_name = lambda arguments: function_expression
print("Square Lambda function\n")
squared = lambda x: x*x
print(squared(int(input("Enter number: "))))
#...............................................use in lists.................................................
list1 = [("Elephant",18),("Tiger",10),("Monkey",50),("Hippo",3)]
print("\nlist sorted based on Animals Names")
list1.sort(key=lambda x: x[0]) #sort the list based on index 0 elements i.e Names of animal
print(list1)
print("\nlist sorted based on numbers")
list1.sort(key=lambda x: x[1]) # sort the list based on index 1 elements i.e Number
print(list1)
#..........................................use in dictionaries......................................
import pprint as pp #to print in proper format
print("\n Dictionary")
dic1 = [{'name':"Hussain",'DOB':1998},{'name':"Husnain",'DOB':2001},{'name':"Mohsin",'DOB':1995},{'name':"Hassan",'DOB':1994}]
dic2 = sorted(dic1, key=lambda x:x['DOB']) #sorting dictionary based on the date of birth
pp.pprint(dic2)
#........................................ list functions ....................................
#......................................... filter function .................................
# give value of the list which fullfills the condition
print("\n Filter function")
list1 = [1,2,3,4,5,6,7,8]
list2 = list(filter(lambda x:x%2==0 , list1)) #filters(condition,list) the even number(lambda condition) from the list and typecast it to list and stores it
print(list2)
#......................................... map function ....................................
# apply some action to all items of the list
print("\n Map function")
list1 = [1,2,3,4,5,6,7,8]
list2 = list(map(lambda x:x**2 , list1)) #map(action,list) the list with their squares from the list and typecast it to list and stores it
print(list2)
#........................................ Conditional Lambda ..............................
#... Format `function_name` = lambda 'argument': 'true_value' if 'condition' else 'false_value'
print("\n Conditional Lambda")
gender = lambda x: "Male" if x=='M' else "Female"
print(gender('M'))
#........................................ Multi argument Lambda ..........................
print("\n Multi Argument Lambda")
status = lambda skill,experience: "Accepted" if skill>3 and experience>1 else "Rejected"
print(status(int(input("Skills: ")),int(input("Experience: "))))
#........................................ Passing function to another function..................
# We can pass lambda function as an argument to normal function
print("\n Function in Function")
def test_func(func,x):
return func(x)
func = lambda x: "Even" if x%2==0 else "Odd"
print(test_func(func,int(input("Enter Value: "))))
input("\nPress any key to exit") |
3dd22a089fd49714b6cd36abbd3e5a6a3c6a4d2b | rakipov/py-base-home-work | /py-home-work/tasks/horoscope.py | 1,961 | 4.1875 | 4 | # Простая задача из первых лекий для определения знака зодиака
day = int(input('Введите день: '))
month = (input('Введите месяц: ')).lower()
if day <= 31:
if (21 <= day <= 31 and month == 'март') or (1 <= day <= 20 and month == 'апрель'):
zodiac = 'Овен'
elif (21 <= day <= 30 and month == 'апрель') or (1 <= day <= 20 and month == 'май'):
zodiac = 'Телец'
elif (21 <= day <= 31 and month == 'май') or (1 <= day <= 21 and month == 'июнь'):
zodiac = 'Блезнецы'
elif (22 <= day <= 30 and month == 'июнь') or (1 <= day <= 22 and month == 'июль'):
zodiac = 'Рак'
elif (23 <= day <= 31 and month == 'июль') or (1 <= day <= 23 and month == 'август'):
zodiac = 'Лев'
elif (24 <= day <= 31 and month == 'август') or (1 <= day <= 23 and month == 'сентябрь'):
zodiac = 'Дева'
elif (24 <= day <= 30 and month == 'сентябрь') or (1 <= day <= 23 and month == 'октябрь'):
zodiac = 'Весы'
elif (24 <= day <= 31 and month == 'октябрь') or (1 <= day <= 22 and month == 'ноябрь'):
zodiac = 'Скорпион'
elif (23 <= day <= 30 and month == 'ноябрь') or (1 <= day <= 21 and month == 'декабрь'):
zodiac = 'Стрелец'
elif (22 <= day <= 31 and month == 'декабрь') or (1 <= day <= 20 and month == 'январь'):
zodiac = 'Козерог'
elif (21 <= day <= 31 and month == 'январь') or (1 <= day <= 18 and month == 'февраль'):
zodiac = 'Водолей'
elif (19 <= day <= 29 and month == 'февраль') or (1 <= day <= 20 and month == 'март'):
zodiac = 'Рыбы'
print(f'Ваш знак зодиака: {zodiac}')
else:
print('Введите корретные дату и месяц!')
|
de0d0d3feca3ee5a4ea7858973c5f9f1e1fb3ebe | anthonypitts2022/Tree_Node_Finder | /Tree_Node_Finder.py | 2,007 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 19:18:03 2019
@author: Anthony Pitts, anthony.pitts@columbia.edu
Description: Searches a tree for a specfified node name
"""
class Node:
#name of Node
Name = None
#list of all child nodes
Children = []
def __init__(self, name = "", children = []):
#initialize the name and children values
self.Name = name
self.Children = children
def get_name(self):
return self.Name;
def set_name(self, new_name):
self.Name = new_name
return self.Name
def get_children(self):
return self.Children;
def set_children(self, new_children):
self.Children = new_children
return self.Children
def main():
#create nodes
Start = Node("Start")
A1 = Node("A1")
D1 = Node("D1")
E1 = Node("E1")
A2 = Node("A2")
B1 = Node("B1")
Find_Me = Node("FindMe")
B2 = Node("B2")
C1 = Node("C1")
#add the children lists to each node
Start.set_children([A1, A2])
A1.set_children([D1])
D1.set_children([E1])
A2.set_children([B1, B2])
B1.set_children([Find_Me])
B2.set_children([C1])
#find the specified node in the tree
#Start is head/top node of tree
found = find_node(Start, "FindMe")
if(not found):
print("This node is not in the tree.")
#recursive method for traversing the tree
#returns boolean of whether or not node was found
def find_node(node, target_name):
node_name = node.get_name()
#print current node
print(node_name)
#if this node is target node
if(node_name == target_name):
return True
#iterate through each child node
for child in node.get_children():
#if node was found, return True and stop searching
if(find_node(child, target_name)):
return True
return False
if __name__ == "__main__":
main()
|
2af0d553a0bc30b0a9ef14b2c5c1232c6fbdf4cd | niaragnorak/python_encryption | /Niaragnorak_Encryption.py | 5,306 | 3.5625 | 4 | import tkinter as tk
import try1
from tkinter import *
from tkinter.filedialog import askopenfilename
root=tk.Tk()
root.configure(background='black')
root.title("Python_Encryption")
root.geometry('1920x1080')
dummy=Label(root,text="",bg='black')
welcome=Label(root,text="WELCOME TO PYTHON ENCRYPTION",bg='black',fg='white',font=('Helvetica', 28, 'bold'))
welcome.pack()
for i in range(50):
dummy.pack()
option1=Label(root,text="1.String encryption",bg='black',fg='yellow',font=('Helvetica', 18, 'bold'))
option1.pack()
string1=Entry(root,width=40,bg="black",fg="white",borderwidth=4)
string1.pack()
string1.insert(0,"Enter string to Encrypt")
key1=Entry(root,width=40,bg="black",fg="white",borderwidth=4)
key1.pack()
key1.insert(0,"Enter the encryption key")
def encrypted():
s1=string1.get()
k1=int(key1.get())
return try1.Encryption(s1,k1)
p=Label(root,text="",bg="black",fg="red",font=('Helvetica', 16, 'bold'))
p.pack()
def encryptres():
#p=Label(root,text=encrypted(),bg="black",fg="red")
#p.pack()
p.config(text=encrypted(),fg="red")
def decryptres():
s1=string1.get()
k1=int(key1.get())
res=try1.decryption(k1,4,s1)
#p=Label(root,text=res,bg="black",fg="blue")
#p.pack()
p.config(text=res,fg="blue")
copied=""
def copy():
global copied
s1=string1.get()
k1=int(key1.get())
copied=try1.Encryption(s1,k1)
print(copied)
p.config(text="Encryption copied...You can use it to decrypt in option 2",fg="yellow")
frame = tk.Frame(root)
frame.pack()
encryptstring=Button(frame,text="Encrypt string",padx=10,pady=5,bg="black",fg="red",font=('Helvetica', 12, 'bold'),command=lambda:encryptres())
encryptstring.pack(side=tk.LEFT)
decryptstring=Button(frame,text="Decrypt string",padx=10,pady=5,bg="black",fg="blue",font=('Helvetica', 12, 'bold'),command=lambda:decryptres())
decryptstring.pack(side=tk.LEFT)
copystring=Button(frame,text="Copy encrypted string",padx=10,pady=5,bg="black",fg="yellow",font=('Helvetica', 12, 'bold'),command=lambda:copy())
copystring.pack(side=tk.LEFT)
dummy1=Label(root,text="",bg='black')
for i in range(30):
dummy1.pack()
option2=Label(root,text="2.String decryption",bg='black',fg='orange',font=('Helvetica', 18, 'bold'))
option2.pack()
string2=Entry(root,width=40,bg="black",fg="white",borderwidth=4)
string2.pack()
string2.insert(0,"Enter string to Decrypt")
key2=Entry(root,width=40,bg="black",fg="white",borderwidth=4)
key2.pack()
key2.insert(0,"Enter the encryption key")
p1=Label(root,text="",bg="black",fg="red",font=('Helvetica', 16, 'bold'))
p1.pack()
def copied1():
print(copied)
string2.delete(0,END)
string2.insert(0,str(copied1))
def result():
s1=copied
k1=int(key2.get())
res=try1.decryption(k1,3,s1)
p1.config(text=res,fg="white")
framed= tk.Frame(root)
framed.pack()
copydecrypt=Button(framed,text="Decrypt copied encrypted string",padx=10,pady=5,bg="black",fg="blue",font=('Helvetica', 12, 'bold'),command=lambda:copied1())
copydecrypt.pack(side=tk.LEFT)
decrypted=Button(framed,text="Decrypt",padx=10,pady=5,bg="black",fg="yellow",font=('Helvetica', 12, 'bold'),command=lambda:result())
decrypted.pack(side=tk.LEFT)
dummy2=Label(root,text="",bg='black')
for i in range(80):
dummy2.pack()
option3=Label(root,text="File Encryption and Decryption",bg='black',fg='green',font=('Helvetica', 22, 'bold'))
option3.pack()
p2=Label(root,text="",bg="black",fg="red",font=('Helvetica', 16, 'bold'))
p2.pack()
fileframe=tk.Frame(root)
fileframe.pack()
fileenc=""
def choose():
global fileenc
fileenc= askopenfilename()
p2.config(text=fileenc,fg="violet")
def encryptfile():
f1=open(fileenc,"r",encoding="utf-8")
file1=f1.read().split('\n')
k=int(key3.get())
f2=open("encrypted.txt","w",encoding="utf-8")
arr=[]
for i in file1:
arr.append(try1.Encryption(i,k))
s=arr.pop()
f2.write(s)
f2.write('\n')
f1.close()
f2.close()
p2.config(text="File encrypted successfully encrypted.txt",fg='orange')
def decryptfile():
k=int(key3.get())
f2=open("encrypted.txt","r",encoding="utf-8")
f3=open("result.txt","w",encoding="utf-8")
file2=f2.read().split('\n')
for i in file2:
x=try1.decryption(k,3,i)
f3.write(x)
f3.write('\n')
f2.close()
f3.close()
p2.config(text="The file has been successfully decrypted in result.txt",fg='white')
key3=Entry(fileframe,width=98,bg="black",fg="white",borderwidth=4)
key3.pack()
key3.insert(0,"Enter the encryption key for the file")
choosefile=Button(fileframe,text="Choose file to encrypt/decrypt",padx=10,pady=5,bg="black",fg="orange",font=('Helvetica', 14, 'bold'),command=lambda:choose())
choosefile.pack(side=tk.LEFT)
encryptionfile=Button(fileframe,text="Encrypt file",padx=10,pady=5,bg="black",fg="green",font=('Helvetica', 14, 'bold'),command=lambda:encryptfile())
encryptionfile.pack(side=tk.LEFT)
decryptionfile=Button(fileframe,text="Decrypt file",padx=10,pady=5,bg="black",fg="blue",font=('Helvetica', 14, 'bold'),command=lambda:decryptfile())
decryptionfile.pack(side=tk.LEFT)
dummy3=Label(root,text="",bg='black')
for i in range(50):
dummy3.pack()
button = tk.Button(root, text='Exit Program', width=50,bg="black",fg="red", command=root.destroy)
button.pack()
root.mainloop()
|
2d95625294be5907d014ea1c2c0a5c7c30640d34 | feixuanwo/py_bulidinfunc | /myreverse_reversed.py | 241 | 4.15625 | 4 | #!:coding:utf-8
#reversed与reverse不同。前者是内置函数,后者是列表、字典的方法。前者返回一个新列表。
i = [x for x in range(-5,6)]
for x in reversed(i):
print x,
print
print i
print i.reverse()
print i
|
f9271bc44ac5da31d176e3186a88220ee0c284e3 | cat-box/2019PythonAssignments | /assignment2/abstract_player.py | 4,969 | 4.03125 | 4 | class AbstractPlayer:
"""AbstractPlayer class
"""
def __init__(self, fname, lname, height, weight, jersey_num, date_birth, year_joined, player_type):
"""Constructor method for AbstractPlayer
Args:
fname (string): First name
lname (string): Last name
height (float): Height
weight (float): Weight
jersey_num (int): Jersey number
date_birth (string): Date of birth
year_joined (string): Year joined
player_type (string): Type of player
"""
self._id = None
self._validate_input(fname, "fname")
self._fname = fname
self._validate_input(lname, "lname")
self._lname = lname
self._validate_input(height, "height")
self._height = height
self._validate_input(weight, "weight")
self._weight = weight
self._validate_input(jersey_num, "jersey_num")
self._jersey_num = jersey_num
self._validate_input(date_birth, "date_birth")
self._date_birth = date_birth
self._validate_input(year_joined, "year_joined")
self._year_joined = year_joined
self._validate_player_type(player_type)
def get_id(self):
"""Gets id of player
Returns:
id (int): Player's id
"""
return self._id
def set_id(self, player_id):
""" sets the player id
Args:
player_id (int): id of a player object
"""
self._validate_input(player_id, "Player ID")
self._id = player_id
return
def get_fname(self):
"""Gets first name of player
Returns:
fname (string): Player's first name
"""
return self._fname
def get_lname(self):
"""Gets last name of player
Returns:
lname (string): Player's last name
"""
return self._lname
def get_full_name(self):
"""Gets full name of player
Returns:
full_name (string): Player's full name (concat of first and last names)
"""
full_name = "%s %s" % (self._fname, self._lname)
return full_name
def get_height(self):
"""Gets height of player
Returns:
height (float): Player's height
"""
return self._height
def get_weight(self):
"""Gets weight of player
Returns:
weight (float): Player's weight
"""
return self._weight
def get_jersey_num(self):
"""Gets jersey number of player
Returns:
jersey_num (int): Player's jersey number
"""
return self._jersey_num
def get_date_birth(self):
"""Gets birth date of player
Returns:
date_birth (string): Birth date of player
"""
return self._date_birth
def get_year_joined(self):
"""Gets join year of player
Returns:
year_joined (string): Join year of player
"""
return self._year_joined
def get_stats(self):
"""Abstract method to be implemented by subclasses
Raises:
NotImplementedError
"""
raise NotImplementedError("Abstract method - must be implemented in subclass")
def get_type(self):
"""Abstract method to be implemented by subclasses
Raises:
NotImplementedError
"""
raise NotImplementedError("Abstract method - must be implemented in subclass")
def to_dict(self):
"""Abstract method to be implemented by subclasses
Raises:
NotImplementedError
"""
raise NotImplementedError("Abstract method - must be implemented in subclass")
@staticmethod
def _validate_input(input, input_display):
"""Private method to validate inputs
Args:
input: Input to be validated
input_display (string): String used in ValueError message
Raises:
ValueError: If input is undefined
ValueError: If input is empty
"""
if input == None:
raise ValueError(input_display + " cannot be undefined")
if input == "":
raise ValueError(input_display + " cannot be empty")
@staticmethod
def _validate_player_type(value):
"""Private method to validate player type
Args:
value (string): Type of player (either "Forward" or "Goalie")
Raises:
ValueError: If value is neither "Forward" or "Goalie"
"""
if (value.lower() == "forward") or (value.lower() == "goalie"):
return
else:
raise ValueError("Player Type must be Forward or Goalie")
|
f4c701f570edd33932bae1c6de032f9608891afc | ibhuiyan17/matplotlib-runtime | /csvTest.py | 872 | 3.609375 | 4 | #csvTest.py
import csv
import time
path = raw_input("enter path of csv file: ")
startTime = time.time()
with open(path, 'rb') as csvfile:
contents = []
file_reader = csv.reader(csvfile, delimiter = ',')
'''
row_num = 1
for row in file_reader:
print 'Row #%d:' % row_num, #Prints Contents in easy to read way
print row
row_num += 1
for row in file_reader:
print row[6] #accessing column index 1 of each row
'''
for row in file_reader:
contents.append(row) #makes list of list (2d array) copy of csv file
print contents, '\n\n'
print contents[9][0] #accessing arr[row][col]
print 'num rows:', len(contents)
print 'num cols:', len(contents[0])
for row in contents:
for val in row:
print val + ',',
print ''
endTime = time.time()
print 'time elapsed: %f seconds' % (endTime - startTime)
|
da085485695bac92fc29df22fe5326f3763050c8 | soulcardz/python | /TestFiles/test.4.py | 231 | 3.71875 | 4 | str = 'python quiz practice code'
def opstr (a):
lis = ""
c = a.split()
b = len(c) - 1
lis = lis + c[b]
while b > 0:
lis = lis + " " + c[b - 1]
b = b - 1
return lis
print (opstr(str))
|
6d0313542bed3a787a8f10b1b840b6534a4818a1 | soulcardz/python | /TestFiles/test.2.py | 338 | 3.578125 | 4 | correctlis = [5,7,12,50]
wronglis = [5,2,3,1,5000]
def orglist (a):
length = len(a)
i = 0
b = 1
flag = True
while i < (length - 1) :
b = i + 1
if a[i] > a[b]:
flag = False
break
i = i+1
return flag
g = orglist(correctlis)
f = orglist(wronglis)
print (g)
print (f) |
1520b9faa5b957da64ea48e158adacc0e5987adf | pixeltk623/python | /Core Python/Datatypes/string.py | 478 | 4.28125 | 4 | # Strings
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
# 'hello' is the same as "hello".
# You can display a string literal with the print() function:
# print("Hello")
# print('Hello')
# a = "hello"
# print(a)
# a = """cdsa
# asdasdas
# asdasdassdasd
# asdasdsa"""
# print(a)
a = 'Hello, World'
# print(a[1])
# for x in a:
# print(x)
# print(len(a))
# print("Hello" in a)
# print("hello" not in a)
print(a[1:2]) |
47452085ef55b59dbc810e986300362cfbe80a36 | pixeltk623/python | /Core Python/List/lecture.py | 6,190 | 4.46875 | 4 | # List
# Lists are used to store multiple items in a single variable.
# List Items
# List items are ordered, changeable, and allow duplicate values.
# List items are indexed, the first item has index [0], the second item has index [1] etc.
# thislist = ["apple", "banana", "cherry"]
# print(thislist[2])
#Allow Duplicates
# thislist = ["apple", "banana", "cherry", "apple", "cherry"]
# print(thislist)
#List Length
# print(len(thislist))
# List Items - Data Types
# list1 = ["apple", "banana", "cherry"]
# list2 = [1, 5, 7, 9, 3]
# list3 = [True, False, False]
# print(type(list1))
# print(type(list2))
# print(type(list3))
# list4 = list(["apple", "banana", "cherry"])
# print(list4)
#List Constructor
# thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
# print(thislist)
# allNumber = [1, 5, 7, 9, 3]
# print(allNumber.count(1))
# Negative Indexing
# Negative indexing means start from the end
# -1 refers to the last item, -2 refers to the second last item etc.
# thislist = ["apple", "banana", "cherry"]
# print(thislist[-3])
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[2:5])
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[:4])
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[2:])
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
# print(thislist[-4:-1])
# thislist = ["apple", "banana", "cherry"]
# if "applek" in thislist:
# print("Hai")
# thislist = ["apple", "banana", "cherry"]
# thislist[1] = "blackcurrant"
# print(thislist)
# thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
# thislist[1:3] = ["blackcurrant", "watermelon"]
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist[1:2] = ["blackcurrant", "watermelon"]
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist[1:3] = ["watermelon"]
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist.insert(1, "asdsa")
# print(thislist)
# Append Items
# To add an item to the end of the list, use the append() method:
# thislist.append("asdadasds")
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# tropical = ["mango", "pineapple", "papaya"]
# thislist.extend(tropical)
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thistuple = ("kiwi", "orange")
# thislist.extend(thistuple)
# print(thislist)
# Remove Specified Item
# The remove() method removes the specified item.
# thislist = ["apple", "banana", "cherry"]
# thislist.remove("banana")
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist.pop(1)
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist.pop()
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# del thislist[0]
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# del thislist
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# thislist.clear()
# print(thislist)
# thislist = ["apple", "banana", "cherry"]
# for x in thislist:
# print(x)
# thislist = ["apple", "banana", "cherry"]
# for i in range(len(thislist)):
# print(thislist[i])
# thislist = ["apple", "banana", "cherry"]
# i = 0
# while i < len(thislist):
# print(thislist[i])
# i = i + 1
# thislist = ["apple", "banana", "cherry"]
# [print(x) for x in thislist]
# List Comprehension
# List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newlist = []
# for x in fruits:
# if "a" in x:
# newlist.append(x)
# print(newlist)
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newlist = [x for x in fruits if "a" in x]
# print(newlist)
# newlist = [expression for item in iterable if condition == True]
# newlist = [x for x in range(10)]
# print(newlist)
# newlist = [x for x in range(10) if x < 5]
# newlist = [x.upper() for x in fruits]
# print(newlist)
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newlist = ['hello' for x in fruits]
# print(newlist)
# fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# newlist = [x if x != "banana" else "orange" for x in fruits]
# print(newlist)
# thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
# thislist = [100, 50, 65, 82, 23]
# # thislist.sort()
# thislist.sort(reverse = True)
# print(thislist)
# print(thislist)
# list1 = ["cc","a","aaa","eeee","dddddd"]
# print(list1)
# list1.sort(key=len)
# print(list1)
# list2 = [[2,9],[1,10],[3,7]]
# list2.sort()
# def sortByFun(element):
# return element[1]
# list2.sort(key=sortByFun)
# print(list2)
# thislist = ["banana", "Orange", "Kiwi", "cherry"]
# thislist.sort(key = str.lower)
# print(thislist)
# thislist = ["banana", "Orange", "Kiwi", "cherry"]
# thislist.reverse()
# print(thislist)
# thislist = ["banana", "Orange", "Kiwi", "cherry"]
# # copyList = thislist.copy()
# copyList = list(thislist)
# print(copyList)
# list1 = ["a", "b", "c"]
# list2 = [1, 2, 3]
# list3 = list1 + list2
# print(list3)
# list1 = ["a", "b" , "c"]
# list2 = [1, 2, 3]
# for x in list2:
# list1.append(x)
# print(list1)
# list1 = ["a", "b" , "c"]
# list2 = [1, 2, 3]
# list1.extend(list2)
# print(list1)
# List Methods
# Python has a set of built-in methods that you can use on lists.
# Method Description
# append() Adds an element at the end of the list
# clear() Removes all the elements from the list
# copy() Returns a copy of the list
# count() Returns the number of elements with the specified value
# extend() Add the elements of a list (or any iterable), to the end of the current list
# index() Returns the index of the first element with the specified value
# insert() Adds an element at the specified position
# pop() Removes the element at the specified position
# remove() Removes the item with the specified value
# reverse() Reverses the order of the list
# sort() Sorts the list
# n_list = ["Happy", [2, 0, 1, 5]]
# print(n_list[1][0])
# print(n_list[0][1])
# print(n_list[1][3]) |
4ee16d790677be1eaeb377db035bbdda72309791 | pixeltk623/python | /MYSQL & Mongo Database/mysqli.py | 5,476 | 4.375 | 4 | # Install MySQL Driver
#python -m pip install mysql-connector-python
import mysql.connector
# Database Connection
# mydb = mysql.connector.connect(
# host="localhost",
# user="root",
# password="",
# database="core_python"
# )
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
print(mydb)
# 2 . To create a database in MySQL, use the "CREATE DATABASE" statement:
mycursor = mydb.cursor()
#mycursor.execute("CREATE DATABASE mydatabase")
# Check if Database Exists
# You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES" statement:
# mycursor.execute("SHOW DATABASES")
# for x in mycursor:
# print(x)
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
# print(mydb)
mycursor = mydb.cursor()
# mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# mycursor.execute("SHOW TABLES")
# for x in mycursor:
# print(x)
# Primary Key
# When creating a table, you should also create a column with a unique key for each record.
# This can be done by defining a PRIMARY KEY.
# We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique number for each record. Starting at 1, and increased by one for each record.
#mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
#If the table already exists, use the ALTER TABLE keyword:
# mycursor.execute("ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY")
# mycursor = mydb.cursor()
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# val = ("John", "Highway 21")
# mycursor.execute(sql, val)
# # sql = "INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')"
# # # val = ("John", "Highway 21")
# # mycursor.execute(sql)
# mydb.commit()
# print(mycursor.rowcount, "record inserted.")
# # Insert Multiple Rows
# # To insert multiple rows into a table, use the executemany() method.
# # The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:
# sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
# val = [
# ('Peter', 'Lowstreet 4'),
# ('Amy', 'Apple st 652'),
# ('Hannah', 'Mountain 21'),
# ('Michael', 'Valley 345'),
# ('Sandy', 'Ocean blvd 2'),
# ('Betty', 'Green Grass 1'),
# ('Richard', 'Sky st 331'),
# ('Susan', 'One way 98'),
# ('Vicky', 'Yellow Garden 2'),
# ('Ben', 'Park Lane 38'),
# ('William', 'Central st 954'),
# ('Chuck', 'Main Road 989'),
# ('Viola', 'Sideway 1633')
# ]
# mycursor.executemany(sql, val)
# mydb.commit()
# print(mycursor.rowcount, "was inserted.")
# #last Id Get
# print("1 record inserted, ID:", mycursor.lastrowid)
# Select From a Table
# To select from a table in MySQL, use the "SELECT" statement:
# mycursor.execute("SELECT * FROM customers")
# mycursor.execute("SELECT name, address FROM customers")
# # myresult = mycursor.fetchall()
# myresult = mycursor.fetchone()
# for x in myresult:
# print(x)
#WHERE
# sql = "SELECT * FROM customers WHERE address = %s"
# adr = ("Yellow Garden 2", )
# mycursor.execute(sql, adr)
# myresult = mycursor.fetchall()
# for x in myresult:
# print(x)
# MySQL Order By
# Sort the Result
# Use the ORDER BY statement to sort the result in ascending or descending order.
# The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.
# sql = "SELECT * FROM customers ORDER BY name"
# # sql = "SELECT * FROM customers ORDER BY name DESC"
# mycursor.execute(sql)
# myresult = mycursor.fetchall()
# for x in myresult:
# print(x)
# Python MySQL Delete From By
# Delete Record
# You can delete records from an existing table by using the "DELETE FROM" statement:
# sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
# mycursor.execute(sql)
# mydb.commit()
# print(mycursor.rowcount, "record(s) deleted")
# Python MySQL Drop Table
# sql = "DROP TABLE customers"
# mycursor.execute(sql)
# sql = "DROP TABLE IF EXISTS customers"
# mycursor.execute(sql)
# Update Table
# You can update existing records in a table by using the "UPDATE" statement:
# sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
# mycursor.execute(sql)
# mydb.commit()
# print(mycursor.rowcount, "record(s) affected")
# sql = "UPDATE customers SET address = %s WHERE address = %s"
# val = ("Valley 345", "Canyon 123")
# mycursor.execute(sql, val)
# mydb.commit()
# print(mycursor.rowcount, "record(s) affected")
# MySQL Limit
# mycursor.execute("SELECT * FROM customers LIMIT 5")
# myresult = mycursor.fetchall()
# for x in myresult:
# print(x)
# Start From Another Position
# If you want to return five records, starting from the third record, you can use the "OFFSET" keyword:
# mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
# Python MySQL Join
# sql = "SELECT \
# users.name AS user, \
# products.name AS favorite \
# FROM users \
# INNER JOIN products ON users.fav = products.id"
# sql = "SELECT \
# users.name AS user, \
# products.name AS favorite \
# FROM users \
# LEFT JOIN products ON users.fav = products.id"
# sql = "SELECT \
# users.name AS user, \
# products.name AS favorite \
# FROM users \
# RIGHT JOIN products ON users.fav = products.id" |
87c9b606584258cebac198989bf60683fde8bfeb | faruqii/Tugas-Alpro | /statistic2.py | 516 | 3.640625 | 4 | # list = [100,80,55,70,25,40,100,20,90,50]
import statistics
import numpy as np
list = []
n = int(input("masukan jumlah data :"))
for i in range(0, n):
nilai = int(input())
list.append(nilai)
list.sort()
average = statistics.mean(list)
median = statistics.median(list)
modus = statistics.mode(list)
print("Nilai Rata-Rata :",average)
print("Median :",median)
print("Modus :",modus)
print("Q1 :", np.quantile(list, .25 ))
print("Q2 :", np.quantile(list, .50))
print("Q3 :", np.quantile(list, .75))
|
66cb206d674005d1177b4bfa5de23c2b92722a27 | daviduarte/deepSearch | /profundidade.py | 2,034 | 3.9375 | 4 | """
Implementation of deep search in a binary tree. In this search approch, we use a stack to organize the elements to be covered.
Therefore, we did not use a explicit stack, instead we use the implict function call stack.
"""
import numpy as np
# When the element is find, this var is set to 1, blocking new iterations and exiting the recursion
find = 0
## Each node is represented by a class
class node():
def __init__(self, value=None):
self.value = value
self.visited = 0
self.left = None
self.right = None
def deepSearch(list, element):
print("oi :)")
# Show the entire tree if 'searched' == None (Walks in Root-Left-Right). If 'searched' != None, the walk stop when the current
# node is equal to searched. The function call stack is the trick for deep seach
def showTree(tree, searched = None):
global find
print("Nodo: " + tree.value)
if searched != None and tree.value == searched:
print("Element finded. Exiting...")
find = 1
if tree.left != None and find == 0:
showTree(tree.left, searched = searched)
if tree.right != None and find == 0:
showTree(tree.right, searched = searched)
# Define our tree as linked objects. Then, put some edges
def makeTree(graph):
nodeA = node("A")
head = nodeA
nodeB = node("B")
nodeI = node("I")
head.left = nodeB
head.right = nodeI
nodeC = node("C")
nodeD = node("D")
nodeB.left = nodeC
nodeB.right = nodeD
nodeE = node("E")
nodeF = node("F")
nodeC.left = nodeE
nodeC.right = nodeF
nodeG = node("G")
nodeH = node("H")
nodeD.left = nodeG
nodeD.right = nodeH
nodeJ = node("J")
nodeK = node("K")
nodeI.left = nodeJ
nodeI.right = nodeK
nodeL = node("L")
nodeM = node("M")
nodeJ.left = nodeL
nodeJ.right = nodeM
nodeN = node("N")
nodeO = node("O")
nodeK.left = nodeN
nodeK.right = nodeO
return head
def main():
graph = 0
# We use a linked list to represent our tree
graph = makeTree(graph)
#showTree(graph)
# Let's search some value
showTree(graph, searched = "D")
if __name__ == "__main__":
main()
|
e32d5812d6eec3eac843f0824caa54547e68df55 | KastyaLimoneSS/Gnom | /discriminant.py | 861 | 3.953125 | 4 | import time
import math
a=0
b=0
c=0
d=0
x1=0
x2=0
def equation():
a = int(input("Введите коэфициент a:"))
b = int(input("Введите коэфициент b:"))
c = int(input("Введите число c:"))
print(a)
d = b**2 - 4*a*c
x1 = (-b + math.sqrt(d))/(a*2)
x2 = (-b - math.sqrt(d))/(a*2)
return " D = {0} \n x1 = {1} \n x2 = {2} \n".format(d,x1,x2)
def demult():
equation()
return "{0}(x{1}{2})(x{3}{4})".format(a,"+"*norm_to_bool(x1),x1,"+"*norm_to_bool(x2),x2)
def norm_to_bool(nmb):
return 1-int(nmb <= 0)
act = {
"1": equation,
"2": demult
}
print(act[input(" 1 - решить квадратное уравнение, \n 2 - разложить на множители, \n Что вы хотите сделать? \n >")]())
|
aefdd7e77b1d657b246c119f7cceabfea2dfd5f7 | S3FA/super-street-fire | /ssf-python/glovetests/src/gestures/client_datatypes.py | 5,667 | 3.515625 | 4 | '''
client_datatypes.py
This file contains the basic data types that hold the various
expected inputs from the Super Street Fire game sensors
@author: Callum Hay
'''
import operator
PLAYER_ONE = 1
PLAYER_TWO = 2
# The GloveData class defines the data type the holds
# the various inputs expected from the 9-DOF glove sensor
# on each hand of the two players of the game.
class GloveData:
# Static data
NUM_GLOVE_DATA = 9
# Enumeration for left and right hand gloves
LEFT_HAND_GLOVE = 0
RIGHT_HAND_GLOVE = 1
def __init__(self, rotation = (0,0,0),
acceleration = (0,0,0), heading = (0,0,0),
player = -1, hand = -1):
# Gyro/rotational data - rotation about the x, y and z axis
self.rotation = rotation
# Acceleration data along the x, y and z axis
self.acceleration = acceleration
# Heading data - the directional vector,
# not necessarily normalized
self.heading = heading
# Store which player this glove data belongs to
assert(player == PLAYER_ONE or player == PLAYER_TWO)
self.player = player
# Store which hand the glove is for...
self.hand = hand
def __str__(self):
return "H: " + str(self.heading) + ", A: " + str(self.acceleration) + ", R: " + str(self.rotation)
# add operator - A GloveData may only be added to another GloveData with the
# same player and hand
def __add__(self, other):
assert(self.player == other.player)
assert(self.hand == other.hand)
rotSum = tuple(map(operator.add, self.rotation, other.rotation))
accelSum = tuple(map(operator.add, self.acceleration, other.acceleration))
headingSum = tuple(map(operator.add, self.heading, other.heading))
return GloveData(rotSum, accelSum, headingSum, self.player, self.hand)
# divide operator - A GloveData may only be divided by a scalar (int or float) value
def __div__(self, other):
rotDiv = tuple(map(operator.div, self.rotation, (other, other, other)))
accelDiv = tuple(map(operator.div, self.acceleration, (other, other, other)))
headingDiv = tuple(map(operator.div, self.heading, (other, other, other)))
return GloveData(rotDiv, accelDiv, headingDiv, self.player, self.hand)
# Class for representing the head-set (EEG) data
class HeadsetData:
NUM_HEADSET_DATA = 11
HEADSET_DATA_REGEX_STR = ""
for i in range(NUM_HEADSET_DATA-1): HEADSET_DATA_REGEX_STR = HEADSET_DATA_REGEX_STR + '(-?\d+\.\d+),'
HEADSET_DATA_REGEX_STR = HEADSET_DATA_REGEX_STR + '(-?\d+\.\d+)'
def __init__(self, link, atten, med,
b1, b2, b3, b4, b5, b6, b7, b8, player):
self.link = link
self.attention = atten
self.meditation = med
self.band1 = b1
self.band2 = b2
self.band3 = b3
self.band4 = b4
self.band5 = b5
self.band6 = b6
self.band7 = b7
self.band8 = b8
# Store which player this head-set data belongs to
assert(player == PLAYER_ONE or player == PLAYER_TWO)
self.player = player
def __str__(self):
result = "Link: " + str(self.link) + ", Attention: " + str(self.attention) + ", Mediation: " + str(self.meditation)
result = result + ", Bands: (" + str(self.band1) + ", " + str(self.band2) + ", " + str(self.band3)
result = result + ", " + str(self.band4) + ", " + str(self.band5) + ", " + str(self.band6)
result = result + ", " + str(self.band7) + ", " + str(self.band8) + ")"
return result
def __add__(self, other):
assert(self.player == other.player)
return HeadsetData(self.link + other.link, self.attention + other.attention, \
self.meditation + other.meditation, self.band1 + other.band1, \
self.band2 + other.band2, self.band3 + other.band3, \
self.band4 + other.band4, self.band5 + other.band5, \
self.band6 + other.band6, self.band7 + other.band7, \
self.band8 + other.band8, self.player)
def __div__(self, other):
return HeadsetData(self.link / other, self.attention / other, self.meditation / other, \
self.band1 / other, self.band2 / other, self.band3 / other, \
self.band4 / other, self.band5 / other, self.band6 / other, \
self.band7 / other, self.band8 / other, self.player)
# I DOUBT WE'LL ACTUALLY USE THE CLASSES BELOW SINCE WE'LL BE REACTING TO DATA
# AS IT COMES IN OVER THE PORT
'''
# High level encapsulation of a single player's input
# data - holds all the incoming data from both gloves
# and their headset
class PlayerData:
def __init__(self):
self.leftGloveData = GloveData()
self.rightGloveData = GloveData()
self.headsetData = HeadsetData()
# The Highest level representation of the input for the entire
# Super Street Fire game - contains all input from all
# relevant player sensors for a given capture of all
# received packets at some instance during game play.
class GameData:
def __init__(self):
self.player1Data = PlayerData()
self.player2Data = PlayerData()
pass
'''
|
1a47812edf03576d3f91bae631942827f6dab948 | Parya1112009/mytest | /cisco1.py | 212 | 3.90625 | 4 | import string
str ='hello world!'
print str
print str*2
list = ["priy",20.3,12,45,"eva"]
list1 = ("priy",20.3,12,45,"eva")
print list[2:5]
print list*3
print "tuple is\n",list1
print list1[1:2]
print list1*3
|
f79758f5f58bc781f32e43333ff7772a0374b8fc | Parya1112009/mytest | /split_join.py | 145 | 3.796875 | 4 | import string
string = " my: name: is: priya:"
#for i in str.split(":"):
result =string.split(":")
result1 = "::".join(result)
print result1
|
2b41ee2fb6ceab1a314c683c689d63e0f0e005da | Parya1112009/mytest | /prime_number.py | 211 | 4.0625 | 4 | n1 =int(raw_input("enter the number"))
is_prime(n1)
def is_prime(n):
for i in range(2,9):
if n % i == 0:
print "is not a prime number",n
break
else:
print "is a prime number",n
|
c731f628ffd7c2367bc6c477e95c22e231b91c60 | Parya1112009/mytest | /lookbehind11.py | 140 | 3.5 | 4 | import re
stri = "priyafooqb"
# the below re matches any b not precedded by foo"
match = re.search(r'(?<!foo)b',stri)
print match.group()
|
de83aa76537a736564caa321640cf244211db0f2 | Parya1112009/mytest | /listoperations2.py | 428 | 4 | 4 | list = [1,2,3,4,5,6,7,7,8]
list1 = [1,2,3,4,5,6,7,8]
x = int(raw_input("enter the number to be searched"))
if x in list1:
print "yes it is present in the list"
else:
print "no it is not present in the list"
min = min(list)
print "minimum number is",min
max = max(list)
print "maximum number is",max
occurence = list.count(7)
print "this number is repeated",occurence
index = list.index(3)
print "the index of 3 is",index
|
e6fa41545d0d1c84b0cf0bca3bdfe1804813e88b | Parya1112009/mytest | /palindrom.py | 272 | 3.90625 | 4 | import string
str = raw_input("entr the number")
k = len(str)/2 -1
print k
count = 0
i=0
while i<=k:
if str[i] ==str[-i-1]:
count = count +1
i= i+1
print count
if count>k:
print "%s string is palindrom"%str
else:
print "%s string is not palindrom"%str
|
4da845a17ab03f16469b3c1f92bcbb65077e8c77 | Parya1112009/mytest | /duplicate.py | 226 | 3.65625 | 4 | list1 = []
l = []
count = 0
with open("dupli.txt","r") as f:
for i in f.read().split():
list1.append(i)
list2 = list(set(list1))
print list1
print list2
for j in list1:
if j not in list2:
l.append(j)
print l
|
f886849532196b81f6ebde575210419ce866b905 | Parya1112009/mytest | /re_cisco.py | 98 | 3.6875 | 4 | import re
str = "abb"
match = re.search(r'(.*)?',str)
print match.group()
#print match.group(2)
|
e50bdc5bc028172772c9b313483905cdcec139d7 | Parya1112009/mytest | /deepshallow.py | 129 | 3.609375 | 4 | import copy
dict1 ={"name":"eva","age":"7","grade":"1"}
dict3 =dict1.copy()
dict1["grade"] = "23"
print dict1
print dict3
|
2dd4276a51e630ab97bd2270ac4f4d1e9a7fa9c5 | Parya1112009/mytest | /ciscowebsite.py | 268 | 3.6875 | 4 | list = [1,2,3,4,5]
list1 = []
number =6
def func():
for i in range(len(list)):
for j in range(len(list)):
sum = list[i] + list[j]
if sum == number:
return (list[i],list[j])
continue
list11 = func()
list1.append(list11)
print list1
|
78cefa8e88b86f3259c7d3725df8e9ca6de4ab53 | Parya1112009/mytest | /flatlist_real.py | 413 | 3.703125 | 4 | list_flattened = []
def flatten_list(list1):
print list1
for i in list1:
print i
if isinstance(i,list):
flatten_list(i)
else:
list_flattened.append(i)
return list_flattened
list1 = [[18,[25,34,48],77],44,45,66,[5,65,17,8],2,4,5,[19,10,11,12]]
for i in list1:
if isinstance(i,list):
flatten_list(i)
else:
list_flattened.append(i)
print list_flattened
|
2a4ce3d7eeb8b6a405afa25f565f04b48e973c51 | Parya1112009/mytest | /string.join.py | 122 | 3.6875 | 4 | import string
str = "i am a gud girl"
str = str.split(" ")
print "-".join(str)
str2 = string.join(str,"$")
print str2
|
ec2148fdc7a10a881f01c13f8216f66d131e60ba | bejohi/TDAForITD | /morphdetect/visualisation.py | 1,062 | 3.640625 | 4 | import matplotlib.pyplot as plt
import morphdetect.loging as log
def visualize_2D_binary_matrix(binary_matrix: list):
"""Visualizes a given 2D Matrix which stores only binary values"""
log.log_info(
str(visualize_2D_binary_matrix.__name__) + ": visualize matrix with height: " + str(len(binary_matrix)))
tuple_list = convert_2d_binary_matrix_to_tuple_list(binary_matrix)
plt.scatter(*zip(*tuple_list))
log.log_info(str(visualize_2D_binary_matrix.__name__) + ": calculations finished. Init show.")
plt.show()
log.log_info(str(visualize_2D_binary_matrix.__name__) + ": init of show finished.")
def convert_2d_binary_matrix_to_tuple_list(binary_matrix: list):
""" Creates a list of tuples (x,y) from a given binary pattern, where only the 1s are part of the tuple list."""
image_tuple = []
height = len(binary_matrix)
width = len(binary_matrix[0])
for y in range(height):
for x in range(width):
if binary_matrix[y][x]:
image_tuple.append((x, y))
return image_tuple
|
876fe60eba8c9760a153d0b10984db32a6214378 | lhleonardo/ufla-atividades-grafos | /exercicios/lista-3/main.py | 2,449 | 3.578125 | 4 | from grafo import Grafo
from vertice import Vertice
def main():
caminho = input("Digite o caminho do arquivo: ")
arquivo = open(caminho, "r")
computadores = {}
tarefas = {}
# cria o grafo
grafo = Grafo()
# adiciona os 10 computadores, de 0 a 9
for i in range(10):
vertice = Vertice(i)
grafo.adiciona_computador(vertice)
# mapeamento de computador para cada IDentificador
computadores[i] = vertice
# percorre as linhas do arquivo
for linha in arquivo:
# remove o ; do final da linha, já que não é essencial para
# diferenciar as entradas, pois o \n já faz esse trabalho...
linha = linha.replace(";", "")
# divide a leitura em
# Atividade:Qtd Pc1Pc2...PcN
leitura = linha.split()
# bloco 1 com a parte Atividade:Qtd
# computadores_usados com Pc1Pc2...PcN
bloco1, computadores_usados = leitura[0], leitura[1]
# descobre a tarefa [A-Z] e a quantidade de máquinas
# que deverão executá-la
tarefa, qtd = bloco1[0], bloco1[1]
# vértice que referencia a tarefa
vertice = Vertice(tarefa)
grafo.adiciona_tarefa(vertice)
# a quantidade de execuções para a tarefa deve ser salva, pois será necessário
# criar uma ligação entre o sorvedouro (s) e esta mesma tarefa, sendo o peso
# da aresta definido pela quantidade de execuções
tarefas[tarefa] = (vertice, int(qtd))
# cria aresta entre a tarefa e todos os computadores que ela pode utilizar
for computador in computadores_usados:
grafo.adiciona_aresta(vertice, computadores[int(computador)], 1)
sorvedouro = Vertice("s", is_sorvedouro = True)
fonte = Vertice("t", is_fonte = True)
grafo.define_sorvedouro(sorvedouro)
grafo.define_fonte(fonte)
# cria arestas do sorvedouro as atividades com os capacidades relativas
# a quantidade de instâncias que deverão ser executadas pela
# determinada tarefa
for chave in tarefas:
(vertice, qtd) = tarefas[chave]
grafo.adiciona_aresta(sorvedouro, vertice, qtd)
# cria arestas dos computadores para a fonte, todas com capacidade 1
for chave in computadores:
grafo.adiciona_aresta(computadores[int(chave)], fonte, 1)
print(grafo.executar_fluxo())
main()
|
62b895bd0d0c58485460b4ee6520fb88e4342214 | a-konyaev/python-tests | /descriptor.py | 1,663 | 3.5625 | 4 | # дескриптор переопределяет поведение при обращении к атрибуту
# получается, это те же гетеры и сетеры
from abc import ABCMeta, abstractclassmethod
class Descriptor:
# instance - сюда будет передан obj
# owner - сюда будет передан Class
def __get__(self, instance, owner):
print(f'get: instance={type(instance)}, owner={type(owner)}')
def __set__(self, instance, value):
print('set')
def __delete__(self, instance):
print('delete')
@property
def test(self):
pass
class BaseClass(metaclass=ABCMeta):
'''
пример применения мета-класса (класс, который создает объекты других классов)
'''
@abstractclassmethod
def abs_method(self):
pass
class Class(BaseClass):
attr = Descriptor()
__slots__ = ['a1']
def __init__(self):
self.a1 = '111'
def abs_method(self):
'''необходимо реализовать абстрактный метод, иначе будет ошибка, правда в рантайме'''
pass
obj = Class()
obj.attr
obj.attr = 10
del obj.attr
print(obj.a1)
del obj.a1
# вызывает исключение, если не закоментировать __slots__, т.к. в нем перечисляем ровно тот набор атрибутов,
# которые есть у класса, и выходить за рамки этого набора (добавлять новые) нельзя
#obj.a2 = 111
|
be7d3dd435ac23ac4295a1ebd2b727706be5e801 | a-konyaev/python-tests | /errors.py | 553 | 3.5625 | 4 | import traceback
while True:
print("...")
try:
s = input(">")
i = int(s)
if i == 0:
raise ValueError("i don't be zero")
assert i > 0, f"{i} less by zero"
except ValueError as err:
print(f"error: {str(err)}: " + err.args[0])
except KeyboardInterrupt as err:
print("buy!" + traceback.print_exc())
break
except AssertionError as err:
print("assert: " + err.args[0])
break
else:
print(f"i = {i}")
finally:
print("finally") |
ab6e7b63b8ca141e8e709e205b4ae8659a224bc4 | aslima/Data-Science-course | /fibonacci.py | 487 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 22:42:20 2017
@author: Alexandre Sales Lima
Cursos de Big Data & Data Science
Trabalho 1 Questão 2
"""
import numpy as np
def fibonacci(n):
if n == 0:
return print( 0)
elif n == 1:
return print( 1 )
f = np.zeros(n,dtype = int)
f[0] = 0
f[1] = 1
for i in range(2,n,1):
f[i] = f[i-1] + f[i-2]
return print(f[i])
fibonacci(11) |
e0b42313ea9348684c43d1d8295d3ebf6213f7ca | ashutoshsinha25/Python-Leetcode-Solution | /55.Jump Game.py | 664 | 3.578125 | 4 | class Solution(object):
def canJump(self, nums):
nums_len = len(nums)
result_arr = [False] * nums_len
result_arr[0] = True
current_true_i = 0
for i in range(nums_len):
# print(result_arr)
if nums[i] >= 1 and result_arr[i]:
if i+nums[i] > current_true_i:
result_arr[current_true_i:i+nums[i]+1] = [True] * (i+nums[i]+1-current_true_i)
current_true_i = i+nums[i]
return result_arr[-1]
if __name__ == '__main__':
# nums = [0]
# nums = [3,2,1,0,4]
nums = [0, 2, 3]
print(Solution().canJump(nums))
|
c2e5a338bc3aa4cf398d4053385b96bf8bb81e78 | undergraver/PythonPresentation | /05_financial/credit.py | 2,254 | 3.9375 | 4 | #!/usr/bin/env python
import math
# user input
moneyAmount=90000
monthsOfCredit=24
# credit details offered by bank
interestRate=8.52 # that is in percent
interestRateIncreaseInMonth=0 # that is in percent - because ROBOR/LIBOR/EURIBOR
monthlyAdministrativeInterestRate=0.04 # that is in percent ( 0.04% )
def GetInterestRate(monthNumber):
increasedInterestRate = interestRate * pow(1.0+interestRateIncreaseInMonth/100.0,monthNumber)
return increasedInterestRate
############### start of the simulation ###############
monthlyRateWithNoInterest=float(moneyAmount)/float(monthsOfCredit)
remainingAmount=moneyAmount
totalInterestRateMoney = 0
totalAdminstrationMoney = 0
yearlyPay = 0
for monthNumber in range(monthsOfCredit):
# since the interest rate is anually we divide by 12
interestRateMoney = float(remainingAmount) * GetInterestRate(monthNumber) / 100.0 / 12.0
# bank administration...
monthlyAdministrativeMoney = float(remainingAmount) * float(monthlyAdministrativeInterestRate) / 100.0
totalInterestRateMoney = totalInterestRateMoney + interestRateMoney
totalAdminstrationMoney = totalAdminstrationMoney + monthlyAdministrativeMoney
totalAmountToPayThiMonth = monthlyRateWithNoInterest + interestRateMoney + monthlyAdministrativeMoney
yearlyPay = yearlyPay + totalAmountToPayThiMonth
remainingAmount = remainingAmount - monthlyRateWithNoInterest
print("%d\t%f\t%f\t%f\t%f\t%f\t(%f)" % (monthNumber+1,remainingAmount,monthlyRateWithNoInterest,interestRateMoney,monthlyAdministrativeMoney, totalAmountToPayThiMonth,GetInterestRate(monthNumber)))
if (monthNumber+1) % 12 == 0:
# print interest per year
extraPay = yearlyPay - 12.0*monthlyRateWithNoInterest
extraPercent = 100.0 * extraPay / (12.0*monthlyRateWithNoInterest)
print ("Interest per year:%f; extra pay:%f\n" % (extraPercent,extraPay))
yearlyPay = 0
totalExtra = totalInterestRateMoney+totalAdminstrationMoney
totalExtraInterestRate = 100.0*float(totalExtra)/float(moneyAmount)
print("Total Interest:%f\nTotal administration:%f\nTotal extra:%f\n" % (totalInterestRateMoney,totalAdminstrationMoney,totalExtra))
print("Total interest rate:%f\n" % (totalExtraInterestRate))
|
86ecc1824f7ede762ddc15743ace1b5457fffc52 | undergraver/PythonPresentation | /07_problem_generators/regula_falsi.py | 3,305 | 3.6875 | 4 | #!/usr/bin/env python
import gettext
import random
import sys
def tr(text):
return gettext.gettext(text)
def pl(text, textpl,count):
return gettext.ngettext(text,textpl,count)
class Animal:
def __init__(self,name, name_plural,number_of_legs):
self.name = name
self.name_plural = name_plural
self.number_of_legs = number_of_legs
def __str__(self):
return self.name
def get_animals():
animals = []
hen = Animal(tr("hen"),tr("hens"),2)
animals.append(hen)
rooster = Animal(tr("rooster"),tr("roosters"),2)
animals.append(rooster)
turkey = Animal(tr("turkey"),tr("turkeys"),2)
animals.append(turkey)
duck = Animal(tr("duck"),tr("ducks"),2)
animals.append(duck)
goose = Animal(tr("goose"),tr("geese"),2)
animals.append(goose)
ostrich = Animal(tr("ostrich"),tr("ostriches"),2)
animals.append(ostrich)
cat = Animal(tr("cat"),tr("cats"),4)
animals.append(cat)
pig = Animal(tr("pig"),tr("pigs"),4)
animals.append(pig)
dog = Animal(tr("dog"),tr("dogs"),4)
animals.append(dog)
sheep = Animal(tr("sheep"),tr("sheep"),4)
animals.append(sheep)
cow = Animal(tr("cow"),tr("cows"),4)
animals.append(cow)
lion = Animal(tr("lion"),tr("lions"),4)
animals.append(lion)
jaguar = Animal(tr("jaguar"),tr("jaguars"),4)
animals.append(jaguar)
return animals
def main():
animals = get_animals()
# split animals into groups depending on their legs
two_legged = []
four_legged = []
for animal in animals:
legs = animal.number_of_legs
if legs == 2:
two_legged.append(animal)
elif legs == 4:
four_legged.append(animal)
#print ("2 legs:")
#for animal in two_legged:
# print(animal)
#print ("4 legs:")
#for animal in four_legged:
# print(animal)
two_legged_animal = two_legged[ random.randint(0,len(two_legged)-1) ]
four_legged_animal = four_legged[ random.randint(0,len(four_legged)-1) ]
how_many_two_legged = random.randint(0,20)
how_many_four_legged = random.randint(0,20)
total_heads = how_many_two_legged + how_many_four_legged
total_legs = 2*how_many_two_legged + 4*how_many_four_legged
heads = pl("%d head","%d heads",total_heads) % (total_heads)
legs = pl("%d leg","%d legs",total_legs) % (total_legs)
print("******************")
print("******************")
print(tr("In a backyard there are %s and %s.") % (two_legged_animal.name_plural,four_legged_animal.name_plural))
print(tr("You have %s and %s") % (heads, legs))
print(tr("How many %s?") % (two_legged_animal.name_plural))
answer = sys.stdin.readline().strip()
if int(answer) == how_many_two_legged:
print(tr("Well done!"))
else:
print(tr("Wrong! There are:"))
two_plural_form = pl(two_legged_animal.name,two_legged_animal.name_plural,how_many_two_legged)
two_legged_str = tr("%d %s") % (how_many_two_legged,two_plural_form)
print(two_legged_str)
four_plural_form = pl(four_legged_animal.name,four_legged_animal.name_plural,how_many_four_legged)
four_legged_str = tr("%d %s") % (how_many_four_legged,four_plural_form)
print(four_legged_str)
if __name__=="__main__":
main()
|
4b3f9e149707817aefa696ce2d336453cd93f34a | undergraver/PythonPresentation | /05_financial/increase.py | 766 | 4.125 | 4 | #!/usr/bin/env python
import sys
# raise in percent
raise_applied=6
raise_desired=40
# we compute:
#
# NOTE: the raise is computed annually
#
# 1. the number of years to reach the desired raise with the applied raise
# 2. money lost if the desired raise is applied instantly and no other raise is done
salary_now=100
desired_salary=salary_now*(1+raise_desired/100.0)
year_count=0
money_lost=0
while salary_now < desired_salary:
year_count+=1
salary_now=salary_now*(1+raise_applied/100.0)
money_lost += (desired_salary-salary_now)*12.0
print("You will reach desired salary in:%d years" % (year_count))
print("By that time you will lose:%f" % (money_lost))
if year_count > 0:
print("Average year loss is:%f" % (money_lost/year_count))
|
ad75ffb88e550905b4d167706ab5491768400878 | undergraver/PythonPresentation | /02_typical/xmlBasic.py | 824 | 3.609375 | 4 | #!/usr/bin/env python
# This code is under BSD 2-clause license
from xml.dom.minidom import parse, parseString
def handleDOM(document):
examples = document.getElementsByTagName("example")
for example in examples:
handleExample(example)
def handleExample(example):
name = example.getAttribute('name')
print 40*'_'
print "going through '%s' example" % (name)
items = example.getElementsByTagName("item")
for item in items:
print item.firstChild.nodeValue
#dom = parse('./test.xml') # parse an XML file by name
contents="""\
<demo>
<example name="hello">
<item>Say hello to xml!</item>
</example>
<example name="bye">
<item>Always have a valid xml in mind!</item>
<item>Good bye!</item>
</example>
</demo>"""
document = parseString(contents)
handleDOM(document)
|
6a293c64aabc496cc4e1669935d1659dc1042c39 | Kjartanl/TestingPython | /TestingPython/Logic/basic_logic.py | 368 | 4.21875 | 4 |
stmt = True
contradiction = False
if(stmt):
print("Indeed!")
if(contradiction):
print("Still true, but shouldn't be! Wtf?")
else:
print("I'm afraid I'm obliged to protest!")
print("------- WHILE LOOP ---------")
number = 0
while(number < 5):
print("Nr is %s" %number)
number = number+1
print("Finally, number is %s" % number) |
fba16cc04bcbe45e3d26247dbfef3ea9fe61dcd0 | matejpiro/Sibenice | /sibenice.py | 2,184 | 3.875 | 4 | def oddelovnik():
print("-"*20)
# získej písmeno a vrať ho kapitálkama
def ziskej_pismeno():
user_guess = input("Hádej po jednom písmenu. Zadej písmeno:")
return user_guess.upper()
# funkce která vezme písmeno, projede list a pokud najde shodu, vloží ono písmeno do "view_listu" na správné místo (dle indexu)
def prepis_pismeno(list_to_iterate,hadane_pismeno,my_list):
for index,letter in enumerate(list_to_iterate):
if hadane_pismeno == letter:
my_list.insert(index,hadane_pismeno)
del my_list[index+1]
return my_list
def main():
import random
# náhodně vygeneruj slovo z listu
list_of_possibilities = ["KRAVA","TULEN","LVOUN","PSTROS","GEPARD","GAZELA","STONOZKA","SOVA","PIZMON","PAPOUSEK","KOCKA","ZELVA","VOLAVKA",
"ANTILOPA","ANAKONDA","KRTEK","CHVOSTOSKOK","VELBLOUD","BARAKUDA","OVCE","VLK","PTAKOPYSK","HOVNIVAL"]
word_to_guess = random.choice(list_of_possibilities)
list_of_letters = list(word_to_guess)
# hoď do hádacího listu tolik znaků "_", kolik má písmen slovo, které hádáš
view_list = []
for letter in list_of_letters: # "letter" je zašeděný a nemělo by být
view_list.append("_")
print("Hádané slovo je nějaké zvíře. Obsahuje", len(view_list), "písmen. Máte", len(view_list) +5, "pokusů. Hrajeme bez diakritiky.") # počet pokusů je délka slova + 5
pocitadlo_pokusu = []
while len(pocitadlo_pokusu) < len(view_list)+6:
prepis_pismeno(list_of_letters, ziskej_pismeno(),view_list)
pocitadlo_pokusu.append("X")
for letter in view_list: # hezčí zobrazovadlo (nestiskne se list)
print(letter," ",end="")
print("\n","Zbývá: ",len(view_list) - len(pocitadlo_pokusu) +5, "pokus")
if list_of_letters == view_list:
print("SPRÁVNĚ!",word_to_guess,"! VYHRÁL JSI!")
break
elif len(pocitadlo_pokusu) > len(view_list)+4:
print("PROHRÁL SI SALÁTE!")
print("Hledané slovo bylo: ",word_to_guess)
break
oddelovnik()
if __name__ == "__main__":
main()
|
b774d1f5782804f6e7eafc6acbcecf73db687fea | zwwangoo/tkfordrowseal | /test.py | 5,170 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
# from Tkinter import TracebackType
win = tk.Tk()
win.title("Python GUI") # 添加标题
# 创建一个容器,
monty = tk.LabelFrame(win, text=" Monty Python ") # 创建一个容器,其父容器为win
monty.grid(column=0, row=0, padx=10, pady=10) # padx pady 该容器外围需要留出的空余空间
aLabel = tk.Label(monty, text="A Label")
tk.Label(monty, text="Chooes a number").grid(column=1, row=0) # 添加一个标签,并将其列设置为1,行设置为0
tk.Label(monty, text="Enter a name:").grid(column=0, row=0, sticky='W') # 设置其在界面中出现的位置 column代表列 row 代表行
# button被点击之后会被执行
def clickMe(): # 当acction被点击时,该函数则生效
action.configure(text='Hello ' + name.get() + ' ' + numberChosen.get()) # 设置button显示的内容
print('check3 is %s %s' % (type(chvarEn.get()), chvarEn.get()))
# 按钮
action = tk.Button(monty, text="Click Me!", command=clickMe) # 创建一个按钮, text:显示按钮上面显示的文字, command:当这个按钮被点击之后会调用command函数
action.grid(column=2, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行
# 文本框
name = tk.StringVar() # StringVar是Tk库内部定义的字符串变量类型,在这里用于管理部件上面的字符;不过一般用在按钮button上。改变StringVar,按钮上的文字也随之改变。
nameEntered = tk.Entry(monty, width=12, textvariable=name) # 创建一个文本框,定义长度为12个字符长度,并且将文本框中的内容绑定到上一句定义的name变量上,方便clickMe调用
nameEntered.grid(column=0, row=1, sticky=tk.W) # 设置其在界面中出现的位置 column代表列 row 代表行
nameEntered.focus() # 当程序运行时,光标默认会出现在该文本框中
# 创建一个下拉列表
# number = tk.StringVar()
# numberChosen = tk.Combobox(monty, width=12, textvariable=number, state='readonly')
# numberChosen['values'] = (1, 2, 4, 42, 100) # 设置下拉列表的值
# numberChosen.grid(column=1, row=1) # 设置其在界面中出现的位置 column代表列 row 代表行
# numberChosen.current(0) # 设置下拉列表默认显示的值,0为 numberChosen['values'] 的下标值
# 复选框
chVarDis = tk.IntVar() # 用来获取复选框是否被勾选,通过chVarDis.get()来获取其的状态,其状态值为int类型 勾选为1 未勾选为0
check1 = tk.Checkbutton(monty, text="Disabled", variable=chVarDis, state='disabled') # text为该复选框后面显示的名称, variable将该复选框的状态赋值给一个变量,当state='disabled'时,该复选框为灰色,不能点的状态
check1.select() # 该复选框是否勾选,select为勾选, deselect为不勾选
check1.grid(column=0, row=4, sticky=tk.W) # sticky=tk.W 当该列中其他行或该行中的其他列的某一个功能拉长这列的宽度或高度时,设定该值可以保证本行保持左对齐,N:北/上对齐 S:南/下对齐 W:西/左对齐 E:东/右对齐
chvarUn = tk.IntVar()
check2 = tk.Checkbutton(monty, text="UnChecked", variable=chvarUn)
check2.deselect()
check2.grid(column=1, row=4, sticky=tk.W)
chvarEn = tk.IntVar()
check3 = tk.Checkbutton(monty, text="Enabled", variable=chvarEn)
check3.select()
check3.grid(column=2, row=4, sticky=tk.W)
# 单选按钮
# 定义几个颜色的全局变量
colors = ["Blue", "Gold", "Red"]
# 单选按钮回调函数,就是当单选按钮被点击会执行该函数
def radCall():
radSel = radVar.get()
if radSel == 0:
win.configure(background=colors[0]) # 设置整个界面的背景颜色
print(radVar.get())
elif radSel == 1:
win.configure(background=colors[1])
elif radSel == 2:
win.configure(background=colors[2])
radVar = tk.IntVar() # 通过tk.IntVar() 获取单选按钮value参数对应的值
radVar.set(99)
for col in range(3):
# curRad = 'rad' + str(col)
curRad = tk.Radiobutton(monty, text=colors[col], variable=radVar, value=col, command=radCall) # 当该单选按钮被点击时,会触发参数command对应的函数
curRad.grid(column=col, row=5, sticky=tk.W) # 参数sticky对应的值参考复选框的解释
# 滚动文本框
scrolW = 30 # 设置文本框的长度
scrolH = 3 # 设置文本框的高度
# scr = tk.ScrolledText(monty, width=scrolW, height=scrolH, wrap=tk.WORD) # wrap=tk.WORD 这个值表示在行的末尾如果有一个单词跨行,会将该单词放到下一行显示,比如输入hello,he在第一行的行尾,llo在第二行的行首, 这时如果wrap=tk.WORD,则表示会将 hello 这个单词挪到下一行行首显示, wrap默认的值为tk.CHAR
# scr.grid(column=0, columnspan=3) # columnspan 个人理解是将3列合并成一列 也可以通过 sticky=tk.W 来控制该文本框的对齐方式
win.mainloop() # 当调用mainloop()时,窗口才会显示出来 |
92fd438e6f2abbca8a70deb8ec717762dbf31ddc | T7galaxy/ArcadeMachine | /controller_test/main.py | 2,368 | 3.5625 | 4 | import sys
# April was here
import pygame
from pygame.locals import *
# initializes pygame
pygame.init()
# sets window text (top left corner text)
pygame.display.set_caption('game base')
# creates screen of size 500 pixels by 500 pixels
screen = pygame.display.set_mode((500, 500), 0, 32)
# creates clock for the game that determines speed at which it runs
clock = pygame.time.Clock()
# initialize pygame.joystick
pygame.joystick.init()
# create an array holding all joysticks
joysticks = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]
for joystick in joysticks:
print(joystick.get_name())
# create a square at (50, 50) with width and height of 50 pixels
my_square = pygame.Rect(50, 50, 50, 50)
# set square color to 0 (red)
my_square_color = 0
# creates list of colors (red, blue, green)
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
# creates a list for motion [horizontal, vertical]
motion = [0, 0]
while True:
# fill the screen with black
screen.fill((0, 0, 0))
# draw a black rectangle on the screen
pygame.draw.rect(screen, colors[my_square_color], my_square)
# sets a buffer for joystick so it's not too sensitive
if abs(motion[0]) < 0.1:
motion[0] = 0
if abs(motion[1]) < 0.1:
motion[1] = 0
# adjusts motion of square according to changes in motion list
my_square.x += motion[0] * 10
my_square.y += motion[1] * 10
# checks all events that are occurring
for event in pygame.event.get():
# if a button is pressed on the joystick, change the color of the square
if event.type == JOYBUTTONDOWN:
print(event)
if event.button == 0:
my_square_color = (my_square_color + 1) % len(colors)
# if the joystick is moved, set either horizontal or vertical movement to value of movement (based on tilt of joystick)
if event.type == JOYAXISMOTION:
print(event)
if event.axis < 2:
motion[event.axis] = event.value
# if there was a quit event, quit the program
if event.type == QUIT:
pygame.quit()
sys.exit()
# all the changes above were only behind the scenes. this updates all changes to window that game is running in
pygame.display.update()
# set the game to run at 60 fps
clock.tick(60) |
87749b59b4d77a0a04eb5d8d3b65332c48e4a7b1 | Gusstr/Uppgifter | /uppgift3.py | 129 | 3.671875 | 4 |
T = int(input("tal: "))
def delfem(a):
if a % 5 == 0:
return True
else:
return False
print(delfem(T))
|
f4f9ba1982577f908487115093736c315f4a2c8c | aanantt/Sorting-Algorithms | /InsertionSort.py | 253 | 4.21875 | 4 | def insertionSort(array):
for i in range(len(array)):
j=i-1
while array[j] > array[j+1] and j >=0:
array[j], array[j+1] = array[j+1], array[j]
j -= 1
return array
print(insertionSort([1,5,8,2,9,0])) |
ddc51a5a16177413cef993ea77fb604f7dace875 | Amfeat/Python_learning | /lesson_003/00_bubbles.py | 1,677 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import random
import simple_draw as sd
sd.resolution = (1200, 600)
sd.background_color = (21, 23, 60)
detalization = 5
bubble_width = 2
# Нарисовать пузырек - три вложенных окружностей с шагом 5 пикселей
# Написать функцию рисования пузырька, принммающую 2 (или более) параметра: точка рисовании и шаг
def bubble(point, step, radius, color=(255, 255, 0)):
x, y = point
center = sd.get_point(x, y)
for _ in range(detalization):
radius -= step
sd.circle(center, radius=radius, color=color, width=bubble_width)
color = full_gradient(color)
def full_gradient(color):
channels = list(color)
for i, channel in enumerate(channels):
channels[i] -= int(channel / detalization)
if channels[i] < 0:
channels[i] = 0
return tuple(channels)
# Нарисовать 10 пузырьков в ряд
# for x in range(100, 1001, 100):
# bubble((x, 200), 5, 70)
# Нарисовать три ряда по 10 пузырьков
# for y in range(200, 501, 100):
# for x in range(100, 1001, 100):
# bubble((x, y), 5, 70)
# Нарисовать 100 пузырьков в произвольных местах экрана случайными цветами
for _ in range(100):
x = random.randint(0, 1200)
y = random.randint(0, 600)
rand_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
radius = random.randint(30, 50)
bubble((x, y), bubble_width, radius, rand_color)
sd.pause()
|
92b441f501d7fe687efd1a5f839bb5fb3fee60f0 | Amfeat/Python_learning | /lesson_003/07_wall.py | 622 | 3.625 | 4 | # -*- coding: utf-8 -*-
# (цикл for)
import simple_draw as sd
sd.resolution = (1200, 600)
# Нарисовать стену из кирпичей. Размер кирпича - 100х50
# Использовать вложенные циклы for
def brick(x, y):
# def rectangle(left_bottom, right_top, color=COLOR_YELLOW, width=0):
left_bottom = sd.get_point(x, y)
right_top = sd.get_point(x + 100, y + 50)
sd.rectangle(left_bottom, right_top, width=5)
start_x = -25
for y in range(0, 600, 50):
for x in range(start_x-25, 1200, 100):
brick(x, y)
start_x = -start_x
sd.pause()
|
d026e223e892d33512d51b4e212360b234601a61 | Logirdus/py_lessons | /restore_countofsymbols.py | 502 | 3.609375 | 4 | numbers = ['0','1','2','3','4','5','6','7','8','9']
with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:
for line in input_file:
count = ''
symbol = line[0]
for i in range(1, len(line)):
if line[i] not in numbers:
output_file.write(symbol * int(count))
symbol = line[i]
count = ''
else:
count += str(line[i])
output_file.write(symbol * int(count)) |
7383d76e3be7a0b1982e4e0b12736185f5bebd22 | rameshnataru1224/bookproject12 | /book_rental_program.py | 5,093 | 3.6875 | 4 | """
Author: Ramesh
Task: Book rental system
"""
from tkinter import Label, Entry, W, E, Button, END, Tk
class BookSystem(object):
"""Renting the books"""
def __init__(self, book):
self.book_charges = {"regular": 1.5, "fiction": 3, "novels": 1.5}
self.min_book_charges = {"regular": 2, "fiction": 0, "novels": 4.5}
self.min_rent_days = {"regular": 2, "fiction": 0, "novels": 3}
book.title("Bill for the Books")
# Defines the width and height of the window
book.geometry("500x200")
# Define the Rent attributes
Label(book, text="books type", fg="white", bg='black').\
grid(row=0, column=0, sticky=W, padx=4)
Label(book, text="Number of books rented", fg="white", bg='black').\
grid(row=0, column=1, sticky=W, padx=4)
Label(book, text="time period", fg="white", bg='black').\
grid(row=0, column=2, sticky=W, padx=50)
# fields for regular book
Label(book, text="Regular:", fg="blue", bg='green').\
grid(row=1, sticky=W, padx=4)
self.num_regbooksrented = Entry(book)
self.num_regbooksrented.insert(0, "0")
self.num_regbooksrented.grid(row=1, column=1, sticky=E, pady=4)
self.reg_booksystemduration = Entry(book)
self.reg_booksystemduration.insert(0, "0")
self.reg_booksystemduration.grid(row=1, column=2, sticky=E, pady=4)
# fields for fiction book
Label(book, text="Fiction:", fg="blue", bg='green').grid(row=2, sticky=W, padx=4)
self.num_ficbooksrented = Entry(book)
self.num_ficbooksrented.insert(0, "0")
self.num_ficbooksrented.grid(row=2, column=1, sticky=E, pady=10)
self.fic_booksystemduration = Entry(book)
self.fic_booksystemduration.insert(0, "0")
self.fic_booksystemduration.grid(row=2, column=2, sticky=E, pady=4)
# fields for novels book
Label(book, text="Novels:", fg="blue", bg='green').grid(row=3, sticky=W, padx=4)
self.num_novbooksrented = Entry(book)
self.num_novbooksrented.insert(0, "0")
self.num_novbooksrented.grid(row=3, column=1, sticky=E, pady=4)
self.nov_booksystemduration = Entry(book)
self.nov_booksystemduration.insert(0, "0")
self.nov_booksystemduration.grid(row=3, column=2, sticky=E, pady=4)
# fields for total rent
Label(book, text="Total Rent").grid(row=4, column=1, sticky=W, padx=40)
self.total_rent_field = Entry(book)
self.total_rent_field.grid(row=4, column=2, sticky=E, pady=4)
# fields for submit, quit and clear buttons
self.submit_button = Button(
book,
text="Submit",
command=(lambda: self.calculating_rent()),
bg='dark green').\
grid(row=5, column=1, sticky=E, pady=10, padx=0)
self.quit_button = Button(book, text="Quit", command=book.quit, bg='red').\
grid(row=5, column=2, pady=10)
def fetch_data(self):
"""
:return: gives the cost assigned for the person
"""
rented_books_data = []
try:
rented_books_data.append(
("regular", int(self.num_regbooksrented.get()),
int(self.reg_booksystemduration.get())))
rented_books_data.append(
("fiction", int(self.num_ficbooksrented.get()),
int(self.fic_booksystemduration.get())))
rented_books_data.append(
("novels", int(self.num_novbooksrented.get()),
int(self.nov_booksystemduration.get())))
except ValueError:
print("Please enter Valid data")
# print(rented_books_data)
return rented_books_data
def calculating_rent(self):
"""
:return: calculates the rent for the books of the person
"""
rented_books_data = self.fetch_data()
total_rent = 0
for row in rented_books_data:
if row[0] in self.book_charges:
if row[2] < self.min_rent_days[row[0]]:
partial_rent = row[1] * self.min_book_charges[row[0]]
total_rent = total_rent + partial_rent
else:
if row[0] == "regular":
partial_rent = row[1] * 2 + row[1] * (row[2] - 2) \
* self.book_charges[row[0]]
total_rent = total_rent + partial_rent
else:
partial_rent = row[1] * row[2] \
* self.book_charges[row[0]]
total_rent = total_rent + partial_rent
# print(total_rent)
self.total_rent_field.delete(0, END)
self.total_rent_field.insert(0, total_rent)
def main():
"""
:return: initialize the data
"""
# Get the book window object
book = Tk()
# Create the BookSystem
# calc = BookSystem(book)
BookSystem(book)
# Run the app until exited
book.mainloop()
main()
|
67ee3a01622adecc944da7b9a4f4269ac9d3f94d | RodrigoSperandio/LearnPython | /AulaPython/exercicio1.py | 261 | 3.96875 | 4 | print("Calcule a area de um retangulo")
base = input("Qual o tamanho da base do seu retangulo? ")
altura = input("Qual o tamanho da altura do seu retangulo? ")
area = float(base) * float(altura)
print(f'O seu retangulo possui area: {area} unidades de metida') |
7863e76546d81e46b2bd86a376bc85c03ec81b11 | q2044757581/leetcode | /19. 删除链表的倒数第N个节点/code.py | 886 | 3.59375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length = 0
p = head
# 先用一次遍历求长度
while p:
length += 1
p = p.next
del_index = length - n
cnt = -1
p = head
if del_index == 0:
if length == 1:
head = None
else:
head = head.next
else:
while p:
cnt += 1
if cnt == del_index - 1:
if cnt != length - 2:
p.next = p.next.next
else:
p.next = None
p = p.next
return head
t = Solution()
result = t.removeNthFromEnd(ListNode(1), 1)
print(result)
|
7b61ba45e3abb3e9c760e4ea603a5d9309b20815 | q2044757581/leetcode | /2、两数相加/code.py | 998 | 3.546875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
sum_val = l1.val + l2.val
p = l3 = ListNode(int(sum_val % 10))
left = int(sum_val / 10)
l1 = l1.next
l2 = l2.next
while l1 and l2:
sum_val = left + l1.val + l2.val
l3.next = ListNode(int(sum_val % 10))
left = int(sum_val / 10)
l1 = l1.next
l2 = l2.next
l3 = l3.next
while l1:
sum_val = l1.val + left
l3.next = ListNode(int(sum_val % 10))
left = int(sum_val / 10)
l1 = l1.next
l3 = l3.next
while l2:
sum_val = l2.val + left
l3.next = ListNode(int(sum_val % 10))
left = int(sum_val / 10)
l2 = l2.next
l3 = l3.next
if int(left) != 0:
l3.next = ListNode(int(left))
return p
|
f5abc15c235f93e461187b1c5b4373cf3c7b18d8 | Cary19900111/G7Cary | /Learn/crclosure/main.py | 984 | 3.984375 | 4 | '''
闭包的作用:1.保存上次的运行结果。2.类似配置的作用
'''
def add_step1(number1):
'''如果在一个内部函数里,对在外部作用域(但不是在全局作用域)
的变量进行引用,那么内部函数就被认为是闭包(closure)'''
def add_step2(number2):
result = number1+number2
return result
return add_step2
def nonlocal_cr():
'''不能修改外部作用域的局部变量的'''
foo = 10
def add(number2):
'''python规则指定所有在赋值语句左面的变量都是局部变量,
add()中,变量foo在"="的左面,foo被认为是局部变量,
查找foo的赋值语句,没找到,所以报错referenced before assignment
不报错:加上nonlocal foo,修改外层的foo
'''
nonlocal foo
foo = foo+number2
return foo
return add
if __name__ == '__main__':
nc = nonlocal_cr()
print(nc(10))
print(nc(100))
|
db4b2589fced75a64c6b55331dd7bbec12836441 | Cary19900111/G7Cary | /Learn/crdataStrcuture/Array/dict/copycr.py | 1,696 | 4.15625 | 4 | from copy import copy,deepcopy
def copy_tutorial():
'''
第一层的id不一样,但是第二层的id是一样的,指向的是同一块地址
修改copy1,就会修改copy2
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = copy(dict_in)
dict_copy2 = copy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Before copy2:{}".format(dict_copy2))
print(f"dict_in id is {id(dict_in)}")
print("dict_copy1 id is %d" %id(dict_copy1))
print("dict_copy2 id is %d" %id(dict_copy2))
dict_copy1["favor"].append("footb")
print("After copy1:{}".format(dict_copy1))
print("After copy2:{}".format(dict_copy2))
print("dict_copy1.favor id is %d" %id(dict_copy1["favor"]))
print("dict_copy2.favor id is %d" %id(dict_copy2["favor"]))
def deepcopy_tutorial():
'''
第一层的id不一样,并且第二层的id也是不一样的,所以一般我们的复制都用deepcopy
返回一个完全独立变量
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = deepcopy(dict_in)
dict_copy2 = deepcopy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Before copy2:{}".format(dict_copy2))
print(f"dict_in id is {id(dict_in)}")
print("dict_copy1 id is %d" %id(dict_copy1))
print("dict_copy2 id is %d" %id(dict_copy2))
dict_copy1["favor"].append("footb")
print("After copy1:{}".format(dict_copy1))
print("After copy2:{}".format(dict_copy2))
print("dict_copy1.favor id is %d" %id(dict_copy1["favor"]))
print("dict_copy2.favor id is %d" %id(dict_copy2["favor"]))
if __name__=="__main__":
deepcopy_tutorial()
|
8e14c5e23cccdd6b3db117ab9c4322efc57c700d | arul2810/Facebook-Hacker-Cup | /Airport_Problem.py | 932 | 3.6875 | 4 | test_cases=int(input("Enter Number of Test Cases:"))
def split(word):
return [char for char in word]
for i in range (0,test_cases,1):
N = int(input())
if N%2 == 0:
print("Input is incorrect")
in_string_temp = str(input())
in_string = split(in_string_temp)
a_value = 0
b_value = 0
k=0
while k <= N:
if in_string[k] == "A":
a_value=a_value+1
print("Value of A is incremented and its value is",a_value)
k=k+1
elif in_string[k]=="B":
b_value=b_value+1
print("Value of B is incremented and its value is",b_value)
k=k+1
else:
print("Input is incorrect")
k=k+1
if a_value-b_value == 1:
print("Case #",i+1)
print("Y")
elif b_value-a_value ==1:
print("Case #",i+1)
print("Y")
else:
print("Case #",i+1)
print("N") |
bb1404efadc58c6568c109d0cad0f763c2742d57 | yxs314159/demo-code | /pylearn/assignment/calculator/01.py | 857 | 4 | 4 | #! /user/bin/env python
# _*_ coding: utf-8 _*_
# __author__ = "王顶"
# Email: 408542507@qq.com
"""
四则运算
"""
def show_nenu():
cmd_menu = ("\n"
"[1] Add\n"
"[2] Subtract\n"
"[3] Multiply\n"
"[4] Divide\n")
print(cmd_menu)
return
def calc(num1, num2, opt):
if opt == 1:
return num1 + num2
elif opt == 2:
return num1 - num2
elif opt == 3:
return num1 * num2
elif opt == 4:
return num1 / num2
else:
return 0
show_nenu()
choice = int(input("Enter your choice:"))
f1 = int(input("First Number:"))
f2 = int(input("Second Number:"))
# opt = ['+', '-', '*', '/']
opt = ('+', '-', '*', '/') # opt 改成了只读的元组这样更好一些
print("{0} {1} {2} = {3}".format(f1, opt[choice - 1], f2, calc(f1, f2, choice))) |
ff8d49216bb5d554a9ab67380b356b5609343498 | Grayidea-bit/Arrow-keys | /main.py | 609 | 3.765625 | 4 | ##需要先安裝pygame (pip install pygame)
import pygame,sys
from pygame.locals import *
pygame.init();
windows_surface = pygame.display.set_mode((10,10), pygame.NOFRAME);
x,y =0,0;
while True:
for event in pygame.event.get():
if event.type==KEYDOWN:
if event.key==K_LEFT:
x-=1
print(x,y)
if event.key==K_RIGHT:
x+=1
print(x,y)
if event.key==K_UP:
y+=1
print(x,y)
if event.key==K_DOWN:
y-=1
print(x,y)
if event.key==K_SPACE:
pygame.quit()
sys.exit()
|
a2f754044b5a3d626bbbd0db61ae411e39f143fe | aike-s/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 254 | 3.53125 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
new_list = my_list.copy()
if idx < 0:
return new_list
i = 0
for x in new_list:
if i == idx:
new_list[idx] = element
i += 1
return new_list
|
cf5c40538ab942b02626a95277dd65778eb5a5f4 | aike-s/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-add_item.py | 581 | 3.734375 | 4 | #!/usr/bin/python3
"""
In this file a main for add arguments to a Python list and save them in a file
"""
from sys import argv
load_from_json_file = __import__('6-load_from_json_file').load_from_json_file
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
if __name__ == "__main__":
filename = "add_item.json"
try:
object_from_json = load_from_json_file(filename)
except(FileExistsError):
object_from_json = []
for to_add in argv[1:]:
object_from_json.append(to_add)
save_to_json_file(object_from_json, filename)
|
bfcc8ffcbcdacb92815ae184f7c42e196fd9c23d | kjklug/class-work | /temperature-conversion.py | 155 | 4.09375 | 4 | celsius=input('Enter a temperature in degrees Celsius: ')
fahrenheit=9/5*(float(celsius))+32
print('The temperature in degrees Fahrenheit is ', fahrenheit) |
65c57c302b3d1a34c6da45b8b0f3a2f1f348917e | kjklug/class-work | /traversal.py | 118 | 3.71875 | 4 | inp=input('Enter a string:\n')
index=len(inp)-1
while index >=0:
letter=inp[index]
print(letter)
index=index-1 |
5d9f29e7940ba04a1b0e152c54571d1bb01cfaff | kjklug/class-work | /spam-confidence.py | 352 | 3.6875 | 4 | fname=input('Enter the file name: ')
try:
fhand=open(fname)
except:
print('File cannot be opened:', fname)
exit()
count=0
total=0
for line in fhand:
if line.startswith('X-DSPAM-Confidence:'):
count=count+1
atpos=line.find(':')
num=float(line[atpos+1:-1])
total=total+num
average=total/count
print('Average spam confidence:', average) |
0544ffecb22c776cff16a0024d8f7c7f9caac870 | Aluriak/GBI | /workingfile_correction.py | 4,647 | 3.671875 | 4 | """
This file is dedicated to the practical session.
Functions and routines have to be completed, according to the subject provided by
the standing guys.
By default, useful functions defined in local library (libtp) are imported,
as many __future__ features that allows user to code in Python 3 style,
even if dinopython is used.
For all functions of libtp, don't hesitate to use the help() function for
get the documentation about it.
example: help(plot_stats)
Moreover, example functions are defined in the examples.py file.
Maybe one of them will help you.
If the subject or the standing guys are not clear enough, please take a look
to the following webpages:
- http://python-igraph.readthedocs.org/en/latest/tutorial.html
- http://stackoverflow.com/questions/tagged/igraph
- https://en.wikipedia.org/wiki/Centrality
"""
# Anti dinosaur import
from __future__ import print_function
import igraph as ig
from libtp import (phyper, plot_phyper, plot_stats,
compute_biological_data, read_essentials)
def five_vertices():
"""
Function for the section 1.
Reproduce the graph in the subject.
"""
g = ig.Graph()
# TODO
ig.plot(g)
def centrality_degree(g):
"""
Return a list of 2-tuple (vertex, degree), for each vertex of given graph.
g: graph
"""
result = []
for vertex in g.vs:
# result.append((vertex, ?)) # TODO
result.append((vertex, vertex.degree())) # TODO
return tuple(result)
def pipeline_degree(g, essential_proteins, centrality, thresholds):
# thresholds = (1, 2, 5, 8, 12, 20) # TODO
# thresholds = range(1, 20) # TODO
protein_count_total = [] # number of proteins with a degree >= threshold
protein_count_essential = [] # same for essential proteins
# degrees = centrality_degree(g)
degrees = [(v, centrality(v)) for v in g.vs]
for threshold in thresholds:
protein_count_total.append(0)
protein_count_essential.append(0)
for vertex, degree in degrees:
if degree >= threshold:
if vertex.attributes()['name'] in essential_proteins:
protein_count_essential[-1] += 1
protein_count_total[-1] += 1
# plotting proportions
plot_stats(
protein_count_total,
protein_count_essential,
thresholds,
)
# hypergeometric test
pvalues = []
for index, threshold in enumerate(thresholds):
protein_count = len(g.vs)
# total number of protein: protein_count,
# subset of proteins: protein_count_total[index]
# total number of essential proteins: len(essential_proteins)
# number of essential proteins in subset: protein_count_essential[index]
pvalues.append(phyper(
protein_count, len(essential_proteins),
protein_count_total[index],
protein_count_essential[index]
))
# plotting p-value evolution
plot_phyper(pvalues, thresholds)
if __name__ == '__main__':
# five_vertices() # comment that when section 2 is reached
# SECTION 2
# TODO: create a graph with the igraph API, and test centrality measures on it.
# TODO: read graph from the gml file
# TODO: read the essential proteins
# TODO: call the pipeline
files = (
'biological_data_0016887.gml',
'biological_data_0016020.gml',
'biological_data_0005935.gml',
'biological_data_0006811.gml',
'biological_data_0005525.gml',
'biological_data_0003824.gml',
'biological_data_0005774.gml',
'biological_data_0005524.gml',
'biological_data_0003677.gml',
'biological_data_0016491.gml',
'biological_data_0005886.gml',
)
for filename in ('data/graph/' + f for f in files):
# for filename in ('biological_data_0005730.gml',):
print('FILENAME:', filename)
g = ig.Graph.Read(filename, format='gml')
try:
print('degree...')
pipeline_degree(g, read_essentials(g), lambda v: v.degree(), range(1, 45))
except KeyboardInterrupt, e:
print('INTERRUPT:DEGREE:', filename)
try:
print('between...')
pipeline_degree(g, read_essentials(g), lambda v: v.betweenness(), range(1, 55))
except KeyboardInterrupt, e:
print('INTERRUPT:BETWEEN:', filename)
try:
print('close...')
pipeline_degree(g, read_essentials(g), lambda v: v.closeness(), tuple(x/100. for x in range(100)))
except KeyboardInterrupt, e:
print('INTERRUPT:CLOSE:', filename)
|
fc2e497f6a4df5ed6002bb92dbcf4c5b3af8b393 | 2292527883/Learn-python-3-to-hard-way | /ex39/ex39.py | 1,962 | 4.1875 | 4 | # 字典
# create a mapping of state to abbreviation
statse = { # 定义字典
'Oregon': 'OR',
'Floida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some citise in them
cites = {
'CA': 'san Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more citise
cites['NY'] = 'New york' # 向字典cites 添加 'NY'对应'New york'
cites['OR'] = 'Oregon'
# 打印元素的对应元素
print('-' * 10 * 10)
print("Michigan's abbreviation is :", statse["Michigan"])
print("Floida's abbreviation is :", statse["Floida"])
# do it by using the state then cities dick
print('-' * 100)
# 查找states字典中的michigan对应的元素'MI' 来对应cites 的'Detroit'
print("Michigan has :", cites[statse['Michigan']])
print("Floida's abbreviation is :", cites[statse['Floida']])
# print ever state abbreviation
print('-' * 100)
for state, abbrev in list(statse.items()):
"""
在该循环中
state接受 key (密匙/键盘?)的值
abbrev接受 value(值)的值
字典(key:value)
item遍历字典用法:
for key , value in list#list(dic.items())
"""
print(f"{state} is abbrevuated {abbrev}")
# print every city in states
print('-' * 100)
for key, value in list(cites.items()):
print(f"{key} has the city {value}")
# now do both an the same time
print('-' * 100)
for key, value in list(statse.items()):
print(f"{key} state is abbreviated {value}")
print('-' * 100)
print(f"and has city {cites[value]}")
print("-" * 100)
# safely get a abbreviation by state that might not be thers
# get() 函数返回指定键的值,如果值不在字典中返回默认值None。
# 格式:get(指定值,返回值)
statse = statse.get('Texas')
if not statse: # statse为空值
print("sorry , no Texas")
# get a citu with a default value
city = cites.get('TX', 'Dose NOt Exist')
print(f"The city for the state 'TX' is {city}")
|
134bf3bc84a1f0b67781d6f27656f24b81eef683 | simonvantulder/Python_OOP | /python_Fundamentals/numberTwo.py | 979 | 4.28125 | 4 |
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
#iterateDictionary(students)
# should output: (it's okay if each key-value pair ends up on 2 separate lines;
# bonus to get them to appear exactly as below!)
# first_name - Michael, last_name - Jordan
# first_name - John, last_name - Rosales
# first_name - Mark, last_name - Guillen
# first_name - KB, last_name - Tonel
def iterate_dictionary(some_list):
for x in some_list:
#print("%s and %s" %(key,value))
print("first_name - {}, last_name - {} ".format(first_name[x], last_name[x]))
# for x in range(len(some_list)):
# print(students[x])
iterate_dictionary(students)
first_name="Simon"
last_name="van Tulder"
age=24
print("My name is {} {} and I am {} years old.".format(first_name, last_name, age))
|
b7e9b5cc9b462dcafffe8d8640878ee025453a0a | PramodSuthar/pythonSnippets | /passByArgs.py | 531 | 4.09375 | 4 |
### pass by Value: all immutable obj are passed by value
def changeVal(x):
x += 100
n = 10
print(n)
changeVal(n)
print(n)
### Pass by reference: all mutable obj are passed by reference
print("Example 1")
def changeList_1(l):
l.append(50)
myList_1 = [10,20,30,40]
print(myList_1)
changeList_1(myList_1)
print(myList_1)
print("Example 2")
def changeList_2(l):
l = []
l.append(50)
print(l)
myList_2 = [10,20,30,40]
print(myList_2)
changeList_2(myList_2)
print(myList_2)
|
f6cc9110831cf63cbcac77d35988cf8e2bf76ceb | PramodSuthar/pythonSnippets | /listComprehension.py | 649 | 4.0625 | 4 |
### first Example
print("******** first Example")
grades = [95.5, 98.5, 86, 79, 65]
modifiedGrades = []
for grade in grades:
modifiedGrades.append(grade + 1.5)
print(grades)
print(modifiedGrades)
modifyGrades = [grade + 2.5 for grade in grades]
print(modifyGrades)
### second Example
print("******** second Example")
nums = [1,2,3,4,5,6,7,8,9,10]
squerdEvenNumbers = []
for num in nums:
if(num ** 2)%2 == 0:
squerdEvenNumbers.append(num ** 2)
print(nums)
print(squerdEvenNumbers)
seqEvenNums = [num ** 2 for num in nums if(num ** 2)%2 == 0]
print(seqEvenNums)
|
dd9dca4f015cb790227af5eb427850a1c8823202 | PramodSuthar/pythonSnippets | /generator.py | 670 | 4.15625 | 4 | """
def squence_num(nums):
result = []
for i in nums:
result.append(i*i)
return result
squared_list = squence_num([1,2,3,4,5])
print(squared_list)
"""
def squence_num(nums):
for i in nums:
yield(i*i)
##squared_list = squence_num([1,2,3,4,5])
"""
print(squared_list)
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
print(next(squared_list))
"""
## list comprehension
##squared_list = [x*x for x in [1,2,3,4,5]]
## generator
squared_list = (x*x for x in [1,2,3,4,5])
for num in squared_list:
print(num)
|
baf8ea1ca723cf6de19571e649c605ced72a8e2a | JanusGeiri/MathStuff | /ttt.py | 1,805 | 3.703125 | 4 | class TicTacToe:
def __init__(self, inp_board=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]):
self.board = inp_board
def getDiag(self):
board = self.board
diag1 = []
diag2 = []
for i in range(3):
for j in range(3):
diag1.append(board[i][j])
diag2.append(board[2-i][j])
return [diag1, diag2]
def getCols(self):
return [[self.board[i][j] for i in range(3)] for j in range(3)]
def wincheck_1(self):
for row in self.board:
if sum(row) == 3:
return True
for diag in self.getDiag():
if sum(diag) == 3:
return True
for col in self.getCols():
if sum(col) == 3:
return True
return False
def wincheck_2(self):
for row in self.board:
if sum(row) == -3:
return True
for diag in self.getDiag():
if sum(diag) == -3:
return True
for col in self.getCols():
if sum(col) == -3:
return True
return False
def printBoard(self):
dummy_board = self.board
for i in range(3):
for j in range(3):
if self.board[i][j] == 1:
dummy_board[i][j] = 'X'
elif self.board[i][j] == -1:
dummy_board[i][j] = 'O'
elif self.board[i][j] == 0:
dummy_board[i][j] = '-'
for row in dummy_board:
print('|', end='')
for item in row:
print(item+'|', end='')
print('')
def play(self):
print('Game Started')
board = TicTacToe([[1, 0, 1], [-1, 0, -1], [0, 0, 0]])
board.printBoard()
board.play()
|
c5ec0674bf289a0386f7bbba1198643fff3eb1b7 | EECS388-F19/lab-ryanlieu | /helloworld.py | 249 | 3.515625 | 4 | import random
name = 'Ryan'
rand_one = random.randint(0,100)
rand_two = random.randint(0,100)
rand_sum = rand_one + rand_two
print(name)
print(rand_one)
print(rand_two)
print('Sum = {}'.format(rand_sum))
print('Average = {}'.format(rand_sum / 2.0)) |
1347eee1bcf53e10949bf3af41e175d14064780a | thiter/python-work | /bytecode.py | 401 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "thiter"
def testcode():
a = 'hello,中国'
b = u'Hello,中国'
print type(a), len(a), a
print type(b), len(b), b
def testcode1():
str1 = u"你好"
print type(str1), str1
str2 = str1.encode("utf-8")
print type(str2), str2
if __name__ == '__main__':
testcode1()
print "------"
testcode1()
|
97f2231fc25288bc899f36a645b097ca78c24390 | kth4540/Script_Language | /Regular_expression/Reg_quiz.py | 297 | 3.828125 | 4 | import re
numberRegex=re.compile(r'''((\d\d)(\d)*)* #AREA CODE
(-)?( )? #SEPARATOR
(\d\d\d)(\d)? # 3 OR 4 DIGITS
(-)?( )? #SEPARATOR
(\d\d\d\d) # 4 DIGITS
''',re.VERBOSE)
phoneNum=numberRegex.search('010-2622-4540')
if phoneNum==None:
print('wrong number')
else:
print(phoneNum.group()) |
32a67c8b343cf010143c393baedb7e203928027b | kth4540/Script_Language | /control_flow/control_flow.py | 754 | 3.65625 | 4 | import random
#spam=0
#while spam<5:
# print('hello world')
# spam=spam+1
#input()
#while(True):
# print('please type your name')
# name=input()
# if name=='your name':
# break
#print('thank you')
#while True:
# print('who are you?')
# name=input()
# if name!='joe':
# continue
# print('hello, joe. what is the password')
# password=input()
# if password=='swordfish':
# break
#print('access granted')
#name=''
#while not name:
# name=input()
#print('how many guests will you have')
#NumOfGuests=int(input())
#if NumOfGuests:
# print('be sure to have enough room')
# sum=0
# for i in range(1,100+1):
# sum=sum+i
#
# print(sum)
for i in range(5):
print(random.randint(1,10))
|
41d588b31626842bf048b64f7cbe60e51783917e | berbusatto/algoritmos_facul | /lista_for.py | 12,591 | 3.9375 | 4 | # EXERCÍCIO 1
# Escreva um algoritmo para calcular e escrever o valor da soma S:
# S = (1/1) + (2/4) + (3/9) + (4/16) + (5/25) + (6/36) + .... (10/100)
# soma = 0
# for x in range(11):
# if x > 0:
# soma = soma + (x / (x * x))
#
# print(soma)
# EXERCÍCIO 2
# Escreva um algoritmo que leia o código e o salário de 100 funcionários de uma empresa.
# Ao final, o algoritmo deve determinar o total da folha de pagamento da empresa e sua
# média salarial.
#
# media = 0
# soma = 0
# for x in range(3):
# salario = float(input('Salário '))
# codigo = int(input('Código ')) # NÃO SEI POR QUE ESTÁ AQUI SENDO QUE NÃO FOI UTILIZADO
# soma = salario + soma
# media = soma / (x + 1)
# print(f'O total da folha de pagamento é de {soma:.2f}')
# print(f'A média salarial é de {media} reais')
# EXERCÍCIO 3
# Criar um algoritmo para ler o nome e a idade de um grupo de pessoas, sendo o número
# desse grupo determinado pelo cliente.
# Ao final, o programa deverá imprimir o nome e a idade da pessoa mais idosa e o nome e a
# idade da pessoa mais jovem.
# nome = []
# idade = []
# selec = int(input('Quantas pessoas? '))
# for x in range(selec):
# nome.insert(x, input('Nome: '))
# idade.insert(x, int(input('Idade: ')))
# # print(nome, idade)
# indice_maior = idade.index(max(idade))
# indice_menor = idade.index(min(idade))
# print(f'A pessoa com maior idade é: {nome[indice_maior]}.')
# print(f'A pessoa com menor idade é: {nome[indice_menor]}.')
# RESOLUÇÃO DO KIKO
# pessoas = []
# n_pessoas = int(input('Quantas pessoas? '))
# for x in range(n_pessoas):
# nome = input('Nome: ')
# idade = int(input('Idade: '))
# pessoa = (nome, idade)
# pessoas.append(pessoa)
#
# pessoas = sorted(pessoas, key=lambda p: p[1]) # orderna a lista por idade, p[1] é a idade na tupla (nome, idade)
# nome_mais_velha = pessoas[-1][0] # o indice [-1] retorna o ultimo elemento da lista, o [0] extrai o nome da tupla (nome, idade)
# nome_mais_nova = pessoas[0][0]
#
# print(f'A pessoa com maior idade é: {nome_mais_velha}.')
# print(f'A pessoa com menor idade é: {nome_mais_nova}.')
# EXERCÍCIO 4
# Crie um programa que efetue o cálculo da fatorial de um número. Por exemplo, o
# fatorial de 5 é 120.
# Desta forma 5 ! = 5 * 4 * 3 * 2 * 1 ou 1 * 2 * 3 * 4 * 5
# num = int(input('Digite um número para descobrir o seu fatorial: '))
# res = 1
# for i in range(num + 1):
# if i > 0:
# res = res * i
# print(res)
# EXERCÍCIO 5
# Uma máquina comprada por R$ 28.000,00 se deprecia com uma taxa de R$ 4.000,00
# por ano em sete anos. Escreva um algoritmo que calcula e mostre a tabela de depreciação
# para esses sete anos. A tabela deve ter a forma abaixo.
# valor_maquina = 28000.00
# taxa = 4000.00
# dep_acum = 0.00
# for i in range(8):
# if i == 0:
# print(f'Ano', 'Depreciação', 'Valor no final do Ano', 'Depreciação Acumulada')
# else:
# valor_maquina -= taxa
# dep_acum += taxa
# linha = [i, taxa, valor_maquina, dep_acum]
# print(linha)
# OU
# from prettytable import PrettyTable
#
# lista = PrettyTable(['Ano', 'Depreciação', 'Valor final do ano', 'Depreciação acumulada'])
# lista.align["Ano"] = "c" # c para centralizar, r pra direita, l pra esquerda
# lista.align['Depreciação'] = "c"
# lista.align['Valor final do ano'] = 'c'
# lista.align['Depreciação acumulada'] = 'c'
# lista.padding_width = 1
# lista.float_format = '.2'
#
# valor_maquina = 28000.00
# taxa = 4000.00
# dep_acum = 0.00
# for i in range(8):
# if i > 0:
# valor_maquina -= taxa
# dep_acum += taxa
# lista.add_row([i, taxa, valor_maquina, dep_acum])
# print(lista)
# EXERCÍCIO 6
# Para realizar a totalização dos votos de uma eleição para um cargo majoritário com 3
# candidatos (Antonio, Pedro e José), leia os votos da 10 seções que compõem o colégio
# eleitoras. Para cada seção, são informados: o número de votos de cada candidato, o número
# de votos brancos e o número de votos nulos. A partir dessas informações determine:
# a. o número de votantes;
# b. o total de voto de cada candidato;
# c. o total de votos brancos e nulos;
# d. o total de votos válidos;
# e. O candidato com maior votação;
# f. Se a eleição for válida. Para isso, o total de votos brancos mais votos nulos deve ser
# menor que o total de votos válidos
# antonio = 0
# pedro = 0
# jose = 0
# brancos = 0
# nulos = 0
# for i in range(2):
# antonio += int(input('Votos Antonio: '))
# pedro += int(input('Votos Pedro: '))
# jose += int(input('Votos Jose: '))
# brancos += int(input('Brancos: '))
# nulos += int(input('Nulos: '))
#
# total = antonio + pedro + jose + brancos + nulos
# invalidos = brancos + nulos
# validos = antonio + pedro + jose
# valida = (antonio + pedro + jose) > (brancos + nulos)
#
# print(f'O total de votos foi de: {total}')
# print(f'O total de brancos e nulos foi de: {invalidos}')
# print(f'O total de votos válidos foi de: {validos}')
#
# if valida:
# if pedro > antonio and pedro > jose:
# print(f'Pedro foi eleito com {pedro} votos')
# elif antonio > pedro and antonio > jose:
# print(f'Antonio foi eleito com {antonio} votos')
# else:
# print(f'Jose foi eleito com {jose} votos')
# print(f'Eleição válida? {valida}')
# EXERCÍCIO 7
# Faça um algoritmo que leia o nome, a idade e o sexo (‘M’ para masculino e ‘F’ para
# feminino) de um grupo de 200 estudantes e determine?
# a) quantos são do sexo feminino e maior de 21 anos;
# b) quantos são do sexo masculino e maio de 18 anos
# c) qual a média de idade de pessoas do sexo masculino;
# d) qual a média de idade de pessoas do sexo feminino;
# PRIMEIRAS TENTATIVAS, LEVEI O DIA INTEIRO PARA TENTAR RESOLVER COM LISTAS E
# TUPLAS MAS NÃO CONSEGUI.
# DEPOIS DE UMA BOA NOITE DE SONO RESOLVI EM MEIA HORA HEHEHEH
# mulheres = []
# homens = []
# qtd_pessoas = 5
# cont_mul21 = 0
# cont_hom18 = 0
# idade_hom = 0
# idade_mul = 0
# cont_m = 0
# cont_h = 0
#
# for x in range(qtd_pessoas):
# nome = input('nome: ')
# idade = int(input('idade: '))
# sexo = input('sexo: ').lower()
# pessoa = (nome, idade, sexo)
# if sexo == 'f':
# # mulheres.append(pessoa)
# idade_mul = idade_mul + idade
# cont_m = cont_m + 1
# if idade > 21:
# cont_mul21 = cont_mul21 + 1
# elif sexo == 'm':
# # homens.append(pessoa)
# idade_hom = idade_hom + idade
# cont_h = cont_h + 1
# if idade > 18:
# cont_hom18 = cont_hom18 + 1
# else:
# print('sexo inválido')
#
# print(cont_mul21)
# print(cont_hom18)
# if cont_m > 0:
# media_mul = idade_mul / cont_m
# print(media_mul)
# if cont_h > 0:
# media_hom = idade_hom / cont_h
# print(media_hom)
# SEGUNDA TENTATIVA
# pessoas = []
# sum_h = []
# sum_m = []
# idade_m = []
# idade_h = []
# for x in range(2):
# nome = (input('nome: '))
# idade = (int(input('idade: ')))
# sexo = (input('sexo: ').lower())
# pessoa = (nome, idade, sexo)
# pessoas.append(pessoa)
#
# if sexo == 'f':
# # mulheres.append(pessoa)
# idade_m.append(idade_m + idade)
# sum_m.append(sum_m + 1)
#
# elif sexo == 'm':
# # homens.append(pessoa)
# idade_h = idade_h + idade
# cont_h = cont_h + 1
# if idade > 18:
# cont_hom18 = cont_hom18 + 1
#
#
# media_h = sum(sum_h) / len(sum_h)
# print(media)
# EXERCÍCIO 8
# Faça um algoritmo que apresente na tela as tabuadas de 2 à 8, como mostrado abaixo
#
# modo n00b
# num = 2
# res = 0
# for x in range(11):
# res = num * x
# print(f'{x} X {num} = {res}')
# if x >= 10:
# num = num + 1
# for y in range(11):
# res = num * y
# print(f'{y} X {num} = {res}')
# if y >= 10:
# num = num + 1
# for z in range(11):
# res = num * z
# print(f'{z} X {num} = {res}')
# if z >= 10:
# num = num + 1
# for a in range(11):
# res = num * a
# print(f'{a} X {num} = {res}')
# if a >= 10:
# num = num + 1
# for b in range(11):
# res = num * b
# print(f'{b} X {num} = {res}')
# if b >= 10:
# num = num + 1
# for c in range(11):
# res = num * c
# print(f'{c} X {num} = {res}')
# if c >= 10:
# num = num + 1
# for d in range(11):
# res = num * d
# print(f'{d} X {num} = {res}')
# MODO PRO
# for x in range(2, 9):
# for y in range(11):
# res = x * y
# print(f'{x} X {y} = {res}')
# EXERCÍCIO 9
# Código Especificação Preço
# 100 Cachorro quente 1.20
# 101 Bauru Simples 1.30
# 102 Bauru com ovo 1.50
# 103 Hambúrguer 1.70
# 201 Refrigerante 1.00
# 202 Suco 1.50
# 203 Água Mineral 0.70
# Escreva um algoritmo que leia o código de um sanduíche e de uma bebida de 100 pedidos
# e imprima o valor arrecadado com lanches, bebidas e o total arrecadado. Assuma entradas
# corretas.
#
# lanches = []
# bebidas = []
# for x in range(100):
# cod_lanche = int(input('Digite o código do lanche: '))
# cod_bebidas = int(input('Digite o código da bebida: '))
# if cod_lanche == 100:
# lanches.append(1.20)
# elif cod_lanche == 101:
# lanches.append(1.30)
# elif cod_lanche == 102:
# lanches.append(1.50)
# elif cod_lanche == 103:
# lanches.append(1.70)
# else:
# print('Código inválido')
#
# if cod_bebidas == 201:
# bebidas.append(1.00)
# elif cod_bebidas == 202:
# bebidas.append(1.50)
# elif cod_bebidas == 203:
# bebidas.append(0.70)
# else:
# print('Código inválido')
#
# total_lanches = sum(lanches)
# total_bebidas = sum(bebidas)
# total = total_lanches + total_bebidas
#
# print(f'O total arrecadado com lanches foi de: {total_lanches:.2f}')
# print(f'O total arrecadado com bebidas foi de: {total_bebidas:.2f}')
# print(f'O valor total arrecadado foi de: {total:.2f}')
# EXERCÍCIO 10
# Escreva um algoritmo que leia o número de identificação e as 3 notas obtidas por uma
# turma de 30 alunos nas 3 avaliações. Calcule a média de cada aluno. A atribuição dos
# conceitos obedece a tabela abaixo. O algoritmo deve escrever o número do aluno, suas
# notas, a média, o conceito correspondente e a mensagem ‘Aprovado’ se o conceito for A,
# B ou C e ‘Reprovado’ se o conceito for D ou E.
# Posteriormente, informar quantos alunos alcançaram o Conceito A, B, C, D e o E
# Média de aproveitamento Conceito
# >= 90 A
# >= 75 e < 90 B
# >= 60 e < 75 C
# >= 40 e < 60 D
# < 40 E
alunos = []
nota1 = []
nota2 = []
nota3 = []
media = []
conceito = []
resultado = []
for x in range(30):
alunos.append(input('Digite o código do aluno: '))
nota1.append(int(input('Digite a primeira nota: ')))
nota2.append(int(input('Digite a segunda nota: ')))
nota3.append(int(input('Digite a terceira nota: ')))
media.append(float(nota1[x] + nota2[x] + nota3[x]) / 3)
if media[x] >= 90:
conceito.append('A')
elif media[x] >= 75:
conceito.append('B')
elif media[x] >= 60:
conceito.append('C')
elif media[x] >= 40:
conceito.append('D')
else:
conceito.append('E')
if conceito[x] == 'A' or conceito[x] == 'B' or conceito[x] == 'C':
resultado.append('Aprovado!')
else:
resultado.append('Reprovado!')
for x in range(30):
print(f'O aluno de código {alunos[x]}, tem como primeira nota {nota1[x]}, como segunda nota {nota2[x]}, '
f'e como terceira nota {nota3[x]}. Sua média é {media[x]}, o conceito alcançado foi {conceito[x]}, '
f'e o resultado final é {resultado[x]}')
|
2a748a692f254f0f24f7dc98f9d65bccb3f10278 | berbusatto/algoritmos_facul | /trabalho for.py | 2,372 | 3.765625 | 4 | # SENAC PORTÃO
# ADS PRIMEIRO PERÍODO
# BERNARDO SAAD GEBRAN BUSATTO
# TRABALHO COMANDO PARA
# Calcule o imposto de renda a ser pago por cada um dos 10 contribuintes informados
# pelo cliente, considerando que os dados de cada contribuinte são: número do CPF e renda mensal.
# Faça o cálculo do imposto com base na tabela abaixo:
#
# Base de Cálculo Mensal Alíquota Parcela a deduzir
# Até 1.903,98 Isento -
# De 1.903,99 até 2.826,65 7,5 % R$ 142,80
# De 2.826,66 até 3.751,05 15 % R$ 354,80
# De 3.751,06 até 4.664,68 22,5 % R$ 636,13
# Acima de 4.664,68 27,5 % R$ 869,36
#
# Além do imposto, mostre também o salário liquido a ser recebido pelo contribuinte.
# Ao final da leitura dos 10 contribuintes, informar a quantidade TOTAL de impostos pago e a
# média do imposto pago pelos contribuintes.
imposto = []
for x in range(3):
cpf = input('Digite o CPF: ')
renda = float(input('Renda mensal: '))
if renda >= 4664.68:
pago = renda * 0.275
print(f'O imposto pago pelo CPF {cpf} foi de R${pago:.2f}')
imposto.append(pago)
liquido = renda - 869.36
print(f'Seu salário líquido é de R${liquido:.2f}')
elif renda >= 3751.06:
pago = renda * 0.225
imposto.append(pago)
print(f'O imposto pago pelo CPF {cpf} foi de R${pago:.2f}')
liquido = renda - 636.13
print(f'Seu salário líquido é de R${liquido:.2f}')
elif renda >= 2826.66:
pago = renda * 0.15
imposto.append(pago)
print(f'O imposto pago pelo CPF {cpf} foi de R${pago:.2f}')
liquido = renda - 354.80
print(f'Seu salário líquido é de R${liquido:.2f}')
elif renda >= 1903.99:
pago = renda * 0.075
imposto.append(pago)
print(f'O imposto pago pelo CPF {cpf} foi de R${pago:.2f}')
liquido = renda - 142.80
print(f'Seu salário líquido é de R${liquido:.2f}')
else:
pago = 0
imposto.append(0)
print(f'O CPF {cpf} é isento de pagar imposto')
liquido = renda - 0
print(f'Seu salário líquido é de R${liquido:.2f}')
print('---------------------------------')
totalimpostos = sum(imposto)
mediaimpostos = sum(imposto) / len(imposto)
print(f'O total de impostos pagos foi de R${totalimpostos:.2f}')
print(f'A média dos impostos pagos foi de R${mediaimpostos:.2f}')
print(imposto)
|
24f9a18fb45c897194fda0e73b82e9cb9fb842e1 | sravanrekandar/akademize-grofers-python | /33_printing_lines.py | 232 | 3.515625 | 4 | def print_line():
for i in range(10):
print("_", end="")
print()
for i in range(10):
print_line()
"""
\n - new line character
\t - tab
https://www.w3schools.com/python/gloss_python_escape_characters.asp
"""
|
7b7281c6e932fc4eeee3fcf3579fcf9a09555892 | sravanrekandar/akademize-grofers-python | /05_strings_vs_integers.py | 77 | 3.6875 | 4 | first = "10"
second = "10"
print(first + second)
a = 10
b = 10
print(a + b) |
edea772079188bf3a4d9cf7f13dd14f11c843d19 | sravanrekandar/akademize-grofers-python | /84_sorting.py | 296 | 3.984375 | 4 | numbers = [33, 55, 6, 77, 8, 9]
print(numbers)
numbers.sort()
print(numbers)
cities = ["Hyderabad", "Chennai", "Bengaluru", "Mumbai"]
cities.sort()
print(cities)
"""
Sorting Techniques, suggested reads
bubble sort
selection sort
insertion sort
merge sort
quick sort
radix sort
....
......
"""
|
e6ef7ccc9523abe2c6994aa48af2d977fa378526 | sravanrekandar/akademize-grofers-python | /37_sum_of_naturals.py | 179 | 4.03125 | 4 | def print_sum(num):
sum = (num * (num+1)) / 2
print(f"Sum of first {num} Natural numbers = {sum}")
def main():
n = int(input("Enter n: "))
print_sum(n)
main()
|
0ab1f3e6911d61e7973a202bd544251b18470359 | ringoshogo/study_python4 | /pos-system.py | 5,313 | 3.609375 | 4 | import pandas as pd
from datetime import datetime as dt
### 商品クラス
class Item:
def __init__(self,item_code,item_name,price):
self.item_code=item_code
self.item_name=item_name
self.price=price
def get_price(self):
return self.price
### オーダークラス
class Order:
def __init__(self,item_master):
self.item_order_list=[]
self.item_master=item_master
self.order_total_price=0
self.order_total_amount=0
self.receipt = ""
def add_item_order(self,item_code, item_count):
# 課題4 オーダー時に個数も登録する
self.item_order_list.append((item_code,item_count))
def view_item_list(self):
result = 0
total_amount = 0
index = 0
# 返却用の文字列
text = ""
for item_code, item_count in self.item_order_list:
index += 1
try:
item = list(filter(lambda item: item.item_code == item_code, self.item_master))[0]
# 返却用の文字列に格納する
text += f"===============================\n"
text += f"商品コード:{item_code}\n"
# 課題1 商品の一覧を表示する
text += f"商品名:{item.item_name}\n"
text += f"価格:{item.price}\n"
text += f"数量:{item_count}\n"
text += f"===============================\n"
# 課題5 合計金額、個数を表示する
result += int(item.price) * int(item_count)
total_amount += int(item_count)
# レシートの作成
except:
print(f"アイテムコード:{item_code} が存在しません")
text += f"合計{total_amount}個、金額は{result}円です。\n"
self.order_total_price = result
self.order_total_amount = total_amount
return text
def __get_master() -> list:
"""マスタをオーダーに登録する"""
item_master = []
try:
# 課題3 商品マスタをcsvファイルから読み込む
# header = 0: 1行目をヘッダとして認識する
# dtype = str: データタイプを文字列と認識してくれる:0埋めなど
item_master_csv = pd.read_csv("item_master.csv", header=0, dtype=str).values.tolist()
print(item_master_csv)
# csvマスタをアイテムに登録する
for item in item_master_csv:
item_master.append(Item(item[0], item[1], item[2]))
except pd.errors.EmptyDataError:
print("No columns to parse from file")
return []
return item_master
### メイン処理
def main():
# マスタ登録
# item_master=[]
# item_master.append(Item("001","りんご",100))
# item_master.append(Item("002","なし",120))
# item_master.append(Item("003","みかん",150))
# オーダーにアイテムマスタを登録する
order=Order(__get_master())
# オーダー登録
while True:
# 課題2 オーダーをコンソールから登録する
item_order = input("登録する商品コードを入力してください。>>")
# 課題4 オーダー時に個数も登録する
item_order_count = input("登録する個数を入力してください。>>")
# アイテムマスタに存在しない場合はオーダーに登録しない
if item_order in list(map(lambda x: x.item_code, order.item_master)):
order.add_item_order(item_order, item_order_count)
else:
print("アイテムマスタに存在しません。")
hasNext = input("追加で入力しますか?>> y/n :")
if hasNext != "y" and hasNext != "Y":
break
# オーダー表示
text = order.view_item_list()
# お客様から金額を貰い、おつりを計算する
text += __calculate_customer_payment(order)
__output_receipt(text)
def __output_receipt(text: str):
"""レシートをテキストファイルに出力する"""
filename = dt.now().strftime('%Y%m%d%H%M%S')
with open(f"../receipt/{filename}.txt", encoding="utf-8_sig", mode="w") as f:
f.write(text)
def __calculate_customer_payment(order: Order):
"""お客様からのお預かり金額を計算する"""
# お客様からお預かりを貰う
pay_amount = input("お預かり金額を入力してください(円)>>")
# 返却用の文字列
text = ""
# 課題6 お客様からお預かり金額を入力しおつりを計算
if pay_amount.isdigit():
# 不足している場合
if int(pay_amount) < order.order_total_price:
text += "お預かり金額が不足しております。\n"
elif int(pay_amount) == order.order_total_price:
text += "ちょうどお預かり致します。\n"
else:
rest_amount =int(pay_amount) - order.order_total_price
text += f"おつりは{rest_amount}円です。\n"
return text
else:
print("数字を入力してください。")
return ""
if __name__ == "__main__":
main() |
a8eb495f0fea08409ac73a3279bb07b537216dd5 | jeffyoon/python_tutorial | /formatted_output.py | 4,415 | 4.0625 | 4 | # The easiest way, but not the most elagant one
q = 459
p = 0.098
print(q, p, p * q)
print(q, p, p * q, sep=",")
print(q, p, p * q, sep=":")
# Alternatively, we can construe out of the values a new string by using the string concatenation operator:
print(str(q) + " " + str(p) + " " + str(p * q))
# The second method is inferior to the first one in this example.
# The Old Way or the non-existing printf and sprintf
# '%' operator : string modulo operator
print("Art: %5d, Price per Unit: %8.2f" % (453, 59.058))
# ---- Format String ----
# % : String Modulo operator
# - Tuple with values -
# Output : Art 453, Price per Unit: 59.06
print('I am using %s %d.%d' % ('Python', 3, 2))
# Output : 'I am using Pyhon 3.2'
'''
Format specification
b : Binary format. Outputs the number in base 2.
c : Character.
d : Decimal integer. Outputs the number in base 10.
e, E : Exponent nation.
f, F : Fixed point.
g : General format.
n : Number.
o : Octal format.
s : String format.
x,X : Hex format. Outputs the number in base 16.
% : Percentage.
'''
# The general syntax for a format placeholder is
# %[flags][width][.precision]type
# (e.g.) %6.2f ---> ###.## --> 6 (Total Width) , 2 ( . following width )
# 23.789 ==> #23.79 , 0.039 ==> ##0.04 , 199.8 ==> 199.80 , 23 ==> #23.00
# d : signed integer decimal. , i : signed integer decimal, o : unsigned octal , u : unsigned decimal
# x : unsigned hexadecimal (lowercase) , X : unsigned hexadecimal (uppercase) , e : floating point exponential (lowercase)
# E : floating point exponential (uppercase)
n = 6789
a = "...%d...%-6d...%06d" % (n, n, n)
print(a)
# Output : '...6789...6789 ...006789'
# (-) : left justification and zero (0) fills. %-6d, %06d
m = 9.876543210
'%e | %E | %f | %g' % (m, m, m, m)
# Output : '9.876543e+00 | 9.876543E+00 | 9.876543 | 9.87654'
# Formatting dictionary strings
'''
Targets on the left can refer to the keys in a dictionary on the right so that they can fetch the
corresponding values. In the example below, the (m) and (w) in the format string refers to the keys
in the dictionary on the right abd fectch their corresponding values.
'''
'%(m)d %(w)s' % {'m': 101, 'w': 'Freeway'}
# Output : '101 Freeway'
'''
We can build a dictionary of values and substitue them all at once with a sing formatting expression
that uses key-based references. This technique can be used to generate text:
'''
greetings = '''
Hello %(name)s!
Merry Christmas.
I hope %(year)d will be a good year.
'''
replace = {'name': 'Jeff', 'year': 2017}
print(greeting % replace)
'''
* String formatting by method calls.
Unlike formatting using expression which is based on C's printf, string formatting using method call
is regared as more Python-specific.
* Template basics
This new string object's format method uses the subject string as a template and takes any number of
arguments that represent values to the substitued accroding to the template.
Within the subject string, curly braces designate substitution targets and arguments to be inserted
either by position such s {1} or keyward such as language.
'''
#By position
t = '{0}, {1}, {2}'
t.format('Dec', '29', '2016')
# --> 'Dec, 29, 2016'
#By keyword
t = '{Month}, {Day}, {Year}'
t.format(Month='Dec', Day='29', Year='2016')
# --> 'Dec, 29, 2016'
#Mixed
t = '{Year}, {Month}, {0}'
t.format('29', Year='2016', Month='Dec')
# --> '2016, Dec, 29'
# Arbitrary object type can be substitued from a temporary string
'{Month}, {Year}, {0}'.format('29', Month=['Nov', 'Dec'], Year='2016')
# --> "['Nov', 'Dec'], 2016, 29"
# The Pythonic Way : The string method "format"
# "Art: {0:5d}, Price per Unit: {1:8.2f}".format(453, 59.058)
# 0 : argument0 (453) 1 : argument1 (59.058)
print("Art: {0:5d}, Price per Unit: {1:8.2f}".format(453, 59.058))
# In the following example we demonstrate how keyword parameters can be used with the format method:
# "Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058)
print("Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058))
# It's possible to left or right justify data with the format method.
# To this end, we can precede the formatting with a "<" (left justify) or ">" (right justify).
# We demonstrate this with the following examples:
print("{0:<20s} {1:6.2f}".format('Spam & Eggs:', 6.99))
print("{0:>20s} {1:6.2f}".format('Spam & Eggs:', 6.99))
|
d8a8c491a550a578fb54b463fe8ed2de1f6b67ec | LeitengH/CSCIB351 | /test.py | 616 | 3.8125 | 4 | HEIGHT = 15
WIDTH = 15
board = [[[] for y in range(HEIGHT)] for x in range(WIDTH)]
for i in range (0, HEIGHT):
for j in range (0, WIDTH):
board[i][j] = 0 # fill 0 in it
def printBoard(WIDTH,HEIGHT):
print("")
print("+" + "---+" * WIDTH)
for rowNum in range(HEIGHT - 1, -1, -1):
row = "|"
for colNum in range(WIDTH):
if len(board[colNum]) > rowNum:
row += " " + ('X' if board[colNum][rowNum] else 'O') + " |"
else:
row += " |"
print(row)
print("+" + "---+" * WIDTH)
print(printBoard(15, 15))
|
e732f667ac9b2639556756b625ba3649fbcc70a5 | FreVanBuynderKDGIoT/Make1.2.1 | /Les/Demo7_23112020.py | 558 | 4.0625 | 4 | #!/usr/bin/env python
"""
info about our project
"""
# import
__author__ = "Fre Van Buynder"
__email__ = "fre.vanbuynder@student.kdg.be"
__status__ = "Development"
def main():
list_of_words = ["hi", "I", "am", "Fre", "how", "are", "You"]
searching_word = input("Which word do you want to find?: ")
i = 0
while i < len(list_of_words):
if list_of_words[i] == searching_word:
print("Found it!!!")
break
else:
print("Your word is not in this list right now.")
i += 1
if __name__ == '__main__':
main()
|
ea9586937f73cfb408e1d632cfbc2106409d8f60 | FreVanBuynderKDGIoT/Make1.2.1 | /oefening5.py | 325 | 3.640625 | 4 | #!/usr/bin/env python
"""
info about project
"""
# imports
__author__ = "Fre Van Buynder"
__email__ = "fre.vanbuynder@student.kdg.be"
__status__ = "Development"
# functions
def main():
word = input("Give me a random word (the more random the better): ")
print("the word exist of", len(word), "letters")
if __name__ == '__main__':
main()
|
5608fcc34a45df22a95d7a7e2b4e0ff3b67adfcd | ggg05158/Baekjoon_py | /10808.py | 179 | 3.546875 | 4 | word=input()
w_len=len(word)
list=[]
for j in range(26):
list.append(0)
for i in range(w_len):
list[ord(word[i])-97]+=1
for k in range(26):
print(f"{list[k]} ",end='') |
ddcc13f5c8162130af1532c156686f967e1e94cc | ggg05158/Baekjoon_py | /2609.py | 385 | 3.640625 | 4 | def max(n1,n2):
div=0
for i in range(1,(n2 if n1>n2 else n1)+1):
if(n1%i==0 and n2%i==0):
div=i
return div
def min(n1,n2):
n1d=n1/max(n1,n2)
n2d=n2/max(n1,n2)
return max(n1,n2)*n1d*n2d
def main():
num1, num2=input().split( )
num1=eval(num1)
num2=eval(num2)
print(f"{max(num1,num2)}")
print(f"{min(num1,num2):.0f}")
main() |
eb458a86ddee9aa197d3c57650dc4a8d625782c6 | cojok/trainings_fun | /multiplication_table.py | 365 | 3.515625 | 4 | # https://www.codewars.com/kata/5432fd1c913a65b28f000342
def multiplication_table(row,col):
results = []
for i in range(1, row + 1):
tmp = []
for j in range(1, col + 1):
if i != 1:
tmp.append((results[0][j - 1] * i ))
else:
tmp.append(j)
results.append(tmp)
return results
|
0e07914cfa997c6ee2bef28123972e089f49b454 | montaro/algorithms-course | /P0/Task4.py | 1,234 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
callers = set()
non_telemarketers = set()
telemarketers = set()
for call in calls:
caller = call[0]
callee = call[1]
callers.add(caller)
non_telemarketers.add(callee)
for text in texts:
sender = text[0]
receiver = text[1]
non_telemarketers.add(sender)
non_telemarketers.add(receiver)
telemarketers = callers.difference(non_telemarketers)
sorted_telemarketers = sorted(telemarketers)
print('These numbers could be telemarketers: ')
for telemarketer in sorted_telemarketers:
print(telemarketer)
|
ef2a8723dfb2eb6dfc8946e80a9fc8ab49798b86 | LA200/HW1_ADM | /code.py | 17,496 | 4.25 | 4 | # ===== PROBLEM1 =====
# Exercise 1 - Introduction - Say "Hello, World!" With Python
print("Hello, World!")
# Exercise 2 - Introduction - Python If-Else
def isOdd(n):
if n%2!=0:
print('Weird')
else:
if 2<=n and n<=5:
print('Not Weird')
else:
if 6<=n and n<=20:
print('Weird')
else:
if 20<n:
print('Not Weird')
isOdd(n)
# Exercise 3 - Introduction - Arithmetic Operators
if __name__ == '__main__':
a = int(input())
b = int(input())
def Funzione(a,b):
print((a+b))
print((a-b))
print((a*b))
Funzione(a,b)
# Exercise 4 - Introduction - Python: Division
if __name__ == '__main__':
a = int(input())
b = int(input())
def Divi(a,b):
print(int(a/b))
print(a/b)
Divi(a,b)
# Exercise 5 - Introduction - Loops
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i*i)
i+=1
# Exercise 6 - Introduction - Write a function
def is_leap(year):
leap = False
return(year%400==0 or year%4==0 and year%100!=0)
year = int(input())
print(is_leap(year))
# Exercise 7 - Introduction - Print Function
if __name__ == '__main__':
n = int(input())
l=[]
for i in range(1,n+1):
l.append(str(i))
print("".join(l))
# Exercise 8 - Basic data types - List Comprehensions
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ])
# Exercise 9 - Basic data types - Find the Runner-Up Score!
if __name__ == '__main__':
n = int(input())
lista = list(map(int, input().split()))
print(sorted(list(set(lista)))[-2])
# Exercise 10 - Basic data types - Nested Lists
if __name__ == '__main__':
marksheet = []
score=[]
for i in range(int(input())):
marksheet.append([input(), float(input())])
score.append(marksheet[i][1])
second_low=sorted(set(score))[1]
names=[]
for i in range(len(marksheet)):
if marksheet[i][1]==second_low:
names.append(marksheet[i][0])
names.sort()
for i in names:
print(i)
# Exercise 11 - Basic data types - Finding the percentage
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print(format(sum(student_marks.get(query_name))/len(scores),'.2f'))
# Exercise 12 - Basic data types - Lists
if __name__ == '__main__':
N = int(input())
a=[]
for i in range(N):
lista=(input().split())
if lista[0]=='insert':
a.insert(int(lista[1]),int(lista[2]))
if lista[0]=='print':
print(a)
if lista[0]=='remove':
a.remove(int(lista[1]))
if lista[0]=='append':
a.append(int(lista[1]))
if lista[0]=='sort':
a.sort()
if lista[0]=='pop':
a.pop()
if lista[0]=='reverse':
a.reverse()
# Exercise 13 - Basic data types - Tuples
if __name__ == '__main__':
n = int(input())
integer_list = tuple(map(int, input().split()))
print(hash(integer_list))
# Exercise 14 - Strings - sWAP cASE
def swap_case(s):
return(s.swapcase())
# Exercise 15 - Strings - String Split and Join
def split_and_join(line):
return("-".join(line.split()))
# Exercise 16 - Strings - What's Your Name?
def print_full_name(a, b):
print("Hello "+a+' '+b+"! You just delved into python.")
# Exercise 17 - Strings - Mutations
def mutate_string(string, position, character):
fine = string[:(position)] + character + string[position+1:]
return(fine)
# Exercise 18 - Strings - Find a string
def count_substring(string, sub_string):
return(sum([1 for i in range(0, len(string) - len(sub_string) + 1) if (string[i:(len(sub_string)+i)] == sub_string)]))
# Exercise 19 - Strings - String Validators
if __name__ == '__main__':
s = input()
print(any(i.isalnum() for i in s))
print(any(i.isalpha() for i in s))
print(any(i.isdigit() for i in s))
print(any(i.islower() for i in s))
print(any(i.isupper() for i in s))
# Exercise 20 - Strings - Text Alignment
# Exercise 21 - Strings - Text Wrap
def wrap(string, max_width):
a=textwrap.wrap(string,max_width)
print(*a, sep = "\n")
return ''
# Exercise 22 - Strings - Designer Door Mat
n, m = map(int,input().split())
rombo = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(rombo + ['WELCOME'.center(m, '-')] + rombo[::-1]))
# Exercise 23 - Strings - String Formatting
# Exercise 24 - Strings - Alphabet Rangoli
# Exercise 25 - Strings - Capitalize!
# Exercise 26 - Strings - The Minion Game
def minion_game(string):
vocali=['A','E','I','O','U']
Kevin=0
Stuart=0
for i in range(len(string)):
if vocali.count(s[i])!=0:
Kevin += len(string)-i
else:
Stuart += len(string)-i
if Kevin > Stuart:
print('Kevin',Kevin)
elif Kevin == Stuart:
print("Draw")
elif Kevin<Stuart:
print('Stuart',Stuart)
# Exercise 27 - Strings - Merge the Tools!
import textwrap
def merge_the_tools(string, k):
s1= textwrap.wrap(string, width=k)
for i in s1:
print("".join(list(dict.fromkeys(i))))
# Exercise 28 - Sets - Introduction to Sets
def average(array):
return(sum(set(arr))/len(set(arr)))
# Exercise 29 - Sets - No Idea!
n, m = map(int,input().split())
s = map(int, input().split())
A = set(map(int, input().split()))
B = set(map(int, input().split()))
print(sum([(i in A) - (i in B) for i in s]))
# Exercise 30 - Sets - Symmetric Difference
M= int(input())
A=list(map(int, input().split()))
A1=set(A)
N=int(input())
B=list(map(int, input().split()))
B1=set(B)
sd=sorted(list(A1.symmetric_difference(B1)))
print(*sd, sep = "\n")
# Exercise 31 - Sets - Set .add()
n=int(input())
try:
my_list = []
while True:
my_list.append(input())
except:
print(len(list(set(my_list))))
# if input is not-integer, just print the list
# Exercise 32 - Sets - Set .discard(), .remove() & .pop()
n = int(input())
s = set(map(int, input().split()))
N = int(input())
for i in range(N):
lista=(input().split())
if lista[0]=='pop':
s.pop()
if lista[0]=='discard':
s.discard(int(lista[1]))
if lista[0]=='remove':
s.remove(int(lista[1]))
print(sum(s))
# Exercise 33 - Sets - Set .union() Operation
N=int(input())
s = set(map(int, input().split()))
M=int(input())
t = set(map(int, input().split()))
print(len(s.union(t)))
# Exercise 34 - Sets - Set .intersection() Operation
N=int(input())
s = set(map(int, input().split()))
M=int(input())
t = set(map(int, input().split()))
print(len(s.intersection(t)))
# Exercise 35 - Sets - Set .difference() Operation
N=int(input())
s = set(map(int, input().split()))
M=int(input())
t = set(map(int, input().split()))
print(len(s.difference(t)))
# Exercise 36 - Sets - Set .symmetric_difference() Operation
N=int(input())
s = set(map(int, input().split()))
M=int(input())
t = set(map(int, input().split()))
print(len(s.symmetric_difference(t)))
# Exercise 37 - Sets - Set Mutations
# Exercise 38 - Sets - The Captain's Room
K= int(input())
lista = sorted(list(map(int,input().strip().split())))
a=[]
for i in range(len(lista)):
if lista[i]==lista[i-1]:
a.append(lista[i])
a=set(a)
lista=set(lista)
r=lista.difference(a)
r=list(r)
print(r[0])
# Exercise 39 - Sets - Check Subset
for _ in range(int(input())):
x, a, z, b = input(), set(input().split()), input(), set(input().split())
print(a.issubset(b))
# Exercise 40 - Sets - Check Strict Superset
A=set(map(int, input().split()))
n=int(input())
B=set(map(int, input().split()))
C=set(map(int, input().split()))
print(len(C.difference(A))==0 & len(B.difference(A))==0)
# Exercise 41 - Collections - collections.Counter()
from collections import Counter #it's like a disctionary
n=int(input())
lista= Counter(list(map(int,input().split())))
numero = int(input())
income = 0
#the income variable will be increased if the customer
#buys a pair of shoes
for i in range(numero):
size, price = map(int, input().split())
if lista[size]:
income = income + price
lista[size] -= 1
print(income)
# Exercise 42 - Collections - DefaultDict Tutorial
from collections import defaultdict
n, m = map(int, input().split())
d = defaultdict(lambda: -1)
for i in range(1, n+1):
word = input()
d[word] = d[word] + ' ' + str(i) if word in d else str(i)
for _ in range(m):
print(d[input()])
# Exercise 43 - Collections - Collections.namedtuple()
# Exercise 44 - Collections - Collections.OrderedDict()
# Exercise 45 - Collections - Word Order
# Exercise 46 - Collections - Collections.deque()
# Exercise 47 - Collections - Company Logo
# Exercise 48 - Collections - Piling Up!
# Exercise 49 - Date time - Calendar Module
import calendar
m,d,y=map(int,input().split())
print(list(calendar.day_name)[calendar.weekday(y, m, d)].upper())
#for this exercise i whatched the solution
# Exercise 50 - Date time - Time Delta
# Exercise 51 - Exceptions -
n=int(input())
for i in range(n):
try:
a,b = map(int,input().split())
except ValueError as e:
print('Error Code:',e)
continue
try:
print(a//b)
except ZeroDivisionError as e:
print('Error Code:',e)
# Exercise 52 - Built-ins - Zipped!
import itertools
m,n=map(int,input().split())
X=[]
for i in range(n):
X.append(list(map(float,input().strip().split())))
for x in zip(*X):
print(format(sum(list(x))/n, '.1f'))
# Exercise 53 - Built-ins - Athlete Sort
# Exercise 54 - Built-ins - Ginorts
# Exercise 55 - Map and lambda function
cube = lambda x:x**3
def fibonacci(n):
if n==0:
return []
if n==1:
return [0]
lis=[0,1]
for i in range(2,n):
lis.append((lis[i-2]+lis[i-1]))
return lis
#this piece of code produce a list with the cube
#of the firsts n numbers of Fibonacci's succession
#Regex
#for this kind of exercises
#I searched more or less everything online
# Exercise 56 - Regex - Detect Floating Point Number
import re
n=int(input())
for i in range(n):
s=input()
print(bool(re.match(r'[+-]?\d*[.]\d+$',s)))
# Exercise 57 - Regex - Re.split()
regex_pattern = r"[.,]"
# Exercise 58 - Regex - Group(), Groups() & Groupdict()
import re
S = input()
alphanumeric = re.search(r'([a-zA-Z0-9])\1', S)
if alphanumeric:
print(alphanumeric.group(1))
else:
print(-1)
# Exercise 59 - Regex - Re.findall() & Re.finditer()
import re
v = "aeiou"
c = "qwrtypsdfghjklzxcvbnm"
m = re.findall(r"(?<=[%s])([%s]{2,})[%s]" % (c, v, c), input(), flags = re.I)
print('\n'.join(m or ['-1']))
# Exercise 60 - Regex - Re.start() & Re.end()
# Exercise 61 - Regex - Regex Substitution
# Exercise 62 - Regex - Validating Roman Numerals
regex_pattern = r"M{0,3}(C{1,3}[M,D]|D?C{0,3}L?)(X{1,3}[CL]|X{0,3}V?)(I{1,3}[XV]|V?I{0,3})$" # Do not delete 'r'.
import re
print(str(bool(re.match(regex_pattern, input()))))
# Exercise 63 - Regex - Validating phone numbers
# Exercise 64 - Regex - Validating and Parsing Email Addresses
# Exercise 65 - Regex - Hex Color Code
# Exercise 66 - Regex - HTML Parser - Part 1
# Exercise 67 - Regex - HTML Parser - Part 2
# Exercise 68 - Regex - Detect HTML Tags, Attributes and Attribute Values
# Exercise 69 - Regex - Validating UID
# Exercise 70 - Regex - Validating Credit Card Numbers
# Exercise 71 - Regex - Validating Postal Codes
# Exercise 72 - Regex - Matrix Script
# Exercise 73 - Xml - XML 1 - Find the Score
# Exercise 74 - Xml - XML 2 - Find the Maximum Depth
# Exercise 75 - Closures and decorators - Standardize Mobile Number Using Decorators
# Exercise 76 - Closures and decorators - Decorators 2 - Name Directory
# Exercise 77 - Numpy - Arrays
def arrays(arr):
arr.reverse()
b = numpy.array(arr,float)
return b
# Exercise 78 - Numpy - Shape and Reshape
import numpy
arr = list(map(int, input().split()))
my_array = numpy.array(arr)
print(numpy.reshape(my_array,(3,3)))
# Exercise 79 - Numpy - Transpose and Flatten
import numpy
n, m = map(int, input().split())
array = numpy.array([input().strip().split() for _ in range(n)], int)
print (array.transpose())
print (array.flatten())
# Exercise 80 - Numpy - Concatenate
import numpy as np
a, b, c = map(int,input().split())
arrA = np.array([input().split() for _ in range(a)],int)
arrB = np.array([input().split() for _ in range(b)],int)
print(np.concatenate((arrA, arrB), axis = 0))
# Exercise 81 - Numpy - Zeros and Ones
import numpy
mat = tuple(map(int, input().split()))
print (numpy.zeros(mat, dtype = numpy.int))
print (numpy.ones(mat, dtype = numpy.int))
# Exercise 82 - Numpy - Eye and Identity
import numpy
print(str(numpy.eye(*map(int,input().split()))).replace('1',' 1').replace('0',' 0'))
# Exercise 83 - Numpy - Array Mathematics
import numpy as np
n, m = map(int, input().split())
a, b = (np.array([input().split() for _ in range(n)], dtype=int) for _ in range(2))
print(a+b, a-b, a*b, a//b, a%b, a**b, sep='\n')
# Exercise 84 - Numpy - Floor, Ceil and Rint
import numpy
numpy.set_printoptions(sign=' ')
a = numpy.array(input().split(),float)
print(numpy.floor(a))
print(numpy.ceil(a))
print(numpy.rint(a))
# Exercise 85 - Numpy - Sum and Prod
import numpy
N, M = map(int, input().split())
A = numpy.array([input().split() for _ in range(N)],int)
print(numpy.prod(numpy.sum(A, axis=0), axis=0))
# Exercise 86 - Numpy - Min and Max
import numpy
N, M = map(int, input().split())
A = numpy.array([input().split() for _ in range(N)],int)
print(numpy.max(numpy.min(A, axis=1), axis=0))
# Exercise 87 - Numpy - Mean, Var, and Std
import numpy
numpy.set_printoptions(legacy = '1.13')
NM = list(map(int, input().split()))
arr = []
for i in range(NM[0]):
arr.append(list(map(int, input().split())))
arr = numpy.array(arr)
print(numpy.mean(arr, axis = 1))
print(numpy.var(arr, axis = 0))
print(numpy.std(arr))
# Exercise 88 - Numpy - Dot and Cross
import numpy
a=int(input())
arr1=numpy.array([list(map(int,input().split())) for _ in range(a)])
arr2=numpy.array([list(map(int,input().split())) for _ in range(a)])
print(numpy.dot(arr1,arr2))
# Exercise 89 - Numpy - Inner and Outer
import numpy as np
A = np.array(input().split(), int)
B = np.array(input().split(), int)
print(np.inner(A,B), np.outer(A,B), sep='\n')
# Exercise 90 - Numpy - Polynomials
import numpy
n = list(map(float,input().split()))
m = input()
print(numpy.polyval(n,int(m)))
# Exercise 91 - Numpy - Linear Algebra
import numpy
n=int(input())
a=numpy.array([input().split() for _ in range(n)],float)
numpy.set_printoptions(legacy='1.13')
print(numpy.linalg.det(a))
# ===== PROBLEM2 =====
# Exercise 92 - Challenges - Birthday Cake Candles
def birthdayCakeCandles(ar):
return(ar.count(max(ar)))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(ar)
fptr.write(str(result) + '\n')
fptr.close()
# Exercise 93 - Challenges - Kangaroo
#I tried this exercise many many times
#I spoke with other guys about this exercies and I know
#that they solved it in another way
#My solution fail in 3 tests because I had to set
#a range that if is bigger involves an error
#At the same time I think that could be a good solution
s = list(input().split())
x1=int(s[0])
v1=int(s[1])
x2=int(s[2])
v2=int(s[3])
seq1=list(range(x1,3000000,v1))
seq2=list(range(x2,3000000,v2))
a='NO'
b=len(seq1)
c=len(seq2)
d=min(b,c)
s1d=seq1[:d]
s2d=seq2[:d]
diff=[s1d - s2d for s1d, s2d in zip(s1d, s2d)]
if x1!=x2 and v1==v2:
a='NO'
else:
for i in range(d):
if diff[i]==0:
a='YES'
break
print(a)
# Exercise 94 - Challenges - Viral Advertising
n=int(input())
pop=2
tot = []
for i in range(n-1):
add=pop*3//2
pop=add
tot.append(pop)
print(sum(tot)+2)
#I add 2 at the print because at the start we have 2 person
#the loop calculates how many people are reached by the advertising
# Exercise 95 - Challenges - Recursive Digit Sum
nk = input().split()
n = nk[0]
k = int(nk[1])
if k==100000:
k=1
#this if reduce the value of k because if k is a multiple
#of 10 the sum of the digits doesn't change
#i tried to make a for-loop to reduce the value of key
#but there were code's problem
somma=(n*k)
tot1=sum(list(map(int, list(n))))*k
for i in range(1,1000):
somma=list(map(int, list(somma)))
tot1=sum(somma)
somma=str(tot1)
if tot1<10:
print(tot1)
break
# Exercise 96 - Challenges - Insertion Sort - Part 1
# Exercise 97 - Challenges - Insertion Sort - Part 2
n = int(input())
arr = list(input().rstrip().split())
for i in range(1,n):
if int(arr[i])<int(arr[i-1]):
a=arr[i]
arr.pop(i)
for j in range(0,n):
if int(a)<int(arr[j]):
arr.insert(j,a)
break
print(' '.join(arr))
#in the first loop the code check if the list is sorted
#if the list is not sorted, the code takes the value that gives problem
#puts it into a variable and removes it
#in the second loop the code searches the right position to insert the value
|
6bcf83defad22296e598716ea5799563eb42598b | gh102003/CipherChallenge2020 | /transposition_row_row.py | 247 | 3.734375 | 4 | # Fill in rows, reorder columns then read off rows
ciphertext = input("Enter ciphertext: ")
# key = RDF
plaintext = ""
for a, b, c in zip(ciphertext[0::3], ciphertext[1::3], ciphertext[2::3]):
plaintext += c + a + b
print()
print(plaintext) |
7bbacbc333866ca9e4c6d23d0bba4793808dda4b | webfun-sept2017/BradWalasek-webfun-sept2017 | /Python/ScoresandGrades/ScoresandGrades.py | 401 | 3.875 | 4 | import random
def grade(score):
if score >=60 and score < 70:
grade = "D"
if score >=70 and score < 80:
grade = "C"
if score >=80 and score < 90:
grade = "B"
if score >=90 and score <= 100:
grade = "A"
ret = "Score: "+ str(score) + "; Your grade is " + grade
return ret
for counter in range(1,10):
print grade(random.randint(60,100))
|
0499369101509985cd9144cd28f0d1392c5944fb | Lepajewski/PythonStudia | /Medium/01.py | 141 | 3.75 | 4 | text = list(input().split())
for i in range(len(text)):
text[i] = int(text[i], 2)
text[i] = chr(text[i])
print(text[i], end='')
|
d473354b602dfb92f1a3ce03459bbf9a500b6a1c | Lepajewski/PythonStudia | /Medium/properbracketing.py | 1,078 | 3.796875 | 4 | brackets = input()
opening = '([{'
closing = ')]}'
flag = True
if brackets[0] == closing[0] or brackets[0] == closing[1] or brackets[0] == closing[2] or brackets[-1] == opening[0] or brackets[-1] == opening[1] or brackets[-1] == opening[2]:
flag = False
elif len(brackets) % 2 != 0:
flag = False
else:
op, cl = 0, 0
for j in range(3):
for i in range(len(brackets)):
if brackets[i] == closing[j]:
cl += 1
if brackets[i] == opening[j]:
op += 1
if op != cl:
flag = False
op, cl = 0, 0
else:
for i in range(len(brackets)-1, 1, -1):
for j in range(3):
if brackets[i] == closing[j] and brackets[i-1] != opening[j] and brackets[i-1] != closing[0] and brackets[i-1] != closing[1] and brackets[i-1] != closing[2]:
flag = False
if len(brackets) == 2:
for j in range(3):
if brackets[1] == closing[j] and brackets[0] != opening[j]:
flag = False
print(flag)
|
7dd04fd5f61b9823ad79c762ef14c2b91e618a17 | merzme/My-Python-EXperiments | /positve.py | 250 | 4.03125 | 4 |
def main():
num = float(input('enter a number:'))
if num > 0:
print('the num is positive')
elif num == 0:
print('the num is zero')
else:
print('the num is negative')
if __name__ == "__main__":
main()
|
3cd5ee91b3fad659fa09ea70a2cc4f920aee3275 | wangbqian/python_work | /pay3.py | 241 | 3.609375 | 4 | def computepay(h,r):
if (h<=40):
return h*10.5
else:
return (40*10.5+(h-40)*10.5*1.5)
hrs = raw_input("Enter Hours: ")
hrs = float(hrs)
rts = raw_input("Enter Rate: ")
rts = float(rts)
p = computepay(hrs,rts)
print p |
7b9e11f648348c3d1ad4cd69a916a942e8778839 | wangbqian/python_work | /5.2.py | 382 | 3.96875 | 4 | largest = None
smallest = 10000
while True:
num = raw_input("Enter a integer number: ")
if num == "done" :
break
else:
try:
num = int(num)
except:
print "Invalid input"
continue
smallest = min(num,smallest)
largest = max(num,largest)
print "Maximum is ", largest
print "Minimum is ", smallest |
3a54379dd20a03bd361e6a63bf2cb5426ef62ea2 | avihebbar/learning | /test.py | 528 | 3.625 | 4 | class node(object):
"""docstring for node"""
def __init__(self, value):
super(node, self).__init__()
self.value = value
self.next = None
t = node(3)
s = node(4)
t.next = s
r = node(5)
curr = t
nextNode = t.next
while nextNode is not None:
print "Node value",curr.value
curr = curr.next
nextNode = nextNode.next
curr.next = r
curr = t
while curr is not None:
print curr.value
curr = curr.next
# # Prints 5
# nextNode = r
# print nextNode.value
# # Prints 4
# nextNode = r
# print t.next.value
|
c75cdba527683ebdfb26a8419d467cd06b618b51 | sunjiyun26/pythonstep | /Advancedfeatures/section.py | 472 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'sunjiyun'
print '切片'
_list = range(0,100,1)
r = []
n = 3
for i in range(n):
r.append(_list[i])
print r
print('1:3',_list[1:3])
print(_list[-9:])
print 'range(0,100):',range(1,99,2)
print _list[:2]
print _list[:10]
print _list[-20:-10]
print(_list[10:20])
print(_list[::5])
print(">>>>>"*10)
print("tuple")
print((1,2,3,4,5,6,7,8,9)[:3])
print(">>>>>"*10)
print("string")
print('abcdefghijk'[:3])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.