text stringlengths 37 1.41M |
|---|
class Clients:
def __init__(self, name, surname, balance=0):
self.name = name
self.surname = surname
self.balance = balance
def get_balance(self):
return f'Клиент "{self.name} {self.surname}". Баланс: {self.balance} руб.'
def add_money(self, money):
self.balance += money
print(f'На баланс {self.name} {self.surname} внесено {money}')
def pay(self, money):
self.balance -= money
print(f'С баланса {self.name} {self.surname} потрачено {money}')
|
def print_max(a, b):
if a > b:
print (a, 'is maxnumber')
elif a == b:
print (a, 'is equal to', b)
else:
print (b, 'is maxnumber')
#直接传递字面值
print_max(3, 4)
x = 8
y = 8
#已参数的形式传递变量
print_max(x, y) |
scores = input().split()
C_count = 0
I_count = 0
for ans in scores:
C_count += 1 if ans == "C" else 0
I_count += 1 if ans == "I" else 0
if I_count == 3:
print("Game over", C_count, sep="\n")
break
else:
print("You won", C_count, sep="\n")
|
# pynumber: 2
# create a numpy array of 8x2 as having number
# in each cell between 100 and 200
# such that difference between each element is 5
import numpy as np
mylist=np.arange(100,200,5)
print(mylist)
mylist = mylist[0:16].reshape(8,2)
print(mylist) |
# create 2D numpy based array with given conditions:
# i) take input from user in terms of dimension like (3x2 or 6x7)
# ii) fill this numpy array with random number
# iii) store this array in a file
import numpy as np
mylist = np.random.randint(10,size=(3,2))
print(mylist)
fhand = open('randomArray.txt','w+')
fhand.write(str(mylist))
|
from Crypto.Cipher import AES
import os
key = os.urandom(16)
def encrypt(key):
msg1 = "{\"id:\"19\", some_other_thing:12, user_entered_thing:\""
msg2 = "\", is_admin: \"no\"}"
message = msg1+raw_input("Enter some stuff to encrypt: ")+msg2
while (len(message) % 16) != 0:
message = message+'\x00'
aes = AES.new(key, AES.MODE_ECB)
return aes.encrypt(message).encode('hex')
def decrypt(message, key):
aes = AES.new(key, AES.MODE_ECB)
return aes.decrypt(message.decode('hex'))
#~~~~~~~~~~~~~~~~~~~~DO NOT EDIT ABOVE THIS LINE~~~~~~~~~~~~~~~~~~~
ui = ""
while ui != "!q" :
enc = encrypt(key)
spaced = [enc[i:i+32] for i in range(0,len(enc),32)]
print "Encrypted spaced version: ", spaced, '\n'
print "Encrypted version: ", enc, '\n'
print "Length of ciphertext: ", len(enc)/2
ui = raw_input("Enter some hex to decrypt: ")
if ui == "!q":
exit
try:
print "Decrypted version: ", decrypt(ui, key)
except:
print "Error in decryption, make sure your ciphertext is in hex, and is valid"
ui = raw_input("Type !q to quit: ")
|
# !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
卡拉兹(Callatz)猜想:
对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到 n=1。
卡拉兹在 1950 年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,
一心只证 (3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过 1000 的正整数 n,简单地数一下,需要多少步(砍几下)才能得到 n=1?
输入格式:
每个测试输入包含 1 个测试用例,即给出正整数 n 的值。
输出格式:
输出从 n 计算到 1 需要的步数。
输入样例:
3
输出样例:
5
"""
def callatz(n):
t = 0
while n != 1:
t += 1
if n % 2 == 0:
n = n//2
else:
n = (3*n+1)/2
print(n)
return t
print(callatz(6)) |
# !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
1033 旧键盘打字 (20 分)
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字会是怎样?
输入格式:
输入在 2 行中分别给出坏掉的那些键、以及应该输入的文字。其中对应英文字母的坏键以大写给出;每段文字是不超过 10**5个字符的串。
可用的字符包括字母 [a-z, A-Z]、数字 0-9、以及下划线 _(代表空格)、,、.、-、+(代表上档键)。题目保证第 2 行输入的文字串非空。
注意:如果上档键坏掉了,那么大写的英文字母无法被打出。
输出格式:
在一行中输出能够被打出的结果文字。如果没有一个字符能被打出,则输出空行。
输入样例:
7+IE.
7_This_is_a_test.
输出样例:
_hs_s_a_tst
"""
a = input()
b = input()
char = ''
for i in b:
if i.upper() not in a and not ('A' <= i <= 'Z' and '+' in a):
char += i
print(char) |
def binom(n, k):
"""
Parameters:
n - Number of elements of the entire set
k - Number of elements in the subset
It should hold that 0 <= k <= n
Returns - The binomial coefficient n choose k that represents the number of ways of picking k unordered outcomes from n possibilities
"""
answer = 1
for i in range(1, min(k, n - k) + 1):
answer = answer * (n + 1 - i) / i
return int(answer)
def multivariate_hypgeom(deck, needed):
"""
Parameters:
deck - A dictionary of cardname : number of copies
needed - A dictionary of cardname : number of copies
It should hold that the cardname keys of deck and needed are identical
Returns - the multivariate hypergeometric probability of drawing exactly the cards in 'needed' from 'deck' when drawing without replacement
"""
answer = 1
sum_deck = 0
sum_needed = 0
for card in deck.keys():
answer *= binom(deck[card], needed.get(card, 0))
sum_deck += deck[card]
sum_needed += needed.get(card, 0)
return answer / binom(sum_deck, sum_needed)
|
import re
from dataclasses import dataclass
from datetime import datetime
# Return a datetime.datetime formatted date, or None if the string is not a date
def parse_date(str: str) -> datetime:
try:
return datetime.strptime(str, '%Y-%m-%d')
except:
return None
# Take a datetime.datetime and return a string in the appropriate format
def date_to_string(datetime: datetime) -> str:
if datetime is None:
return None
return datetime.strftime('%Y-%m-%d')
@dataclass
class ParsedDate:
expiry_date: str # Looks like: 2019-12-31
on_weekends: bool
warning_date: str # Looks like: 2019-12-31
def __str__(self) -> str:
if self.on_weekends:
result = 'On Weekends'
elif self.expiry_date is not None:
result = self.expiry_date
else:
result = '';
if self.warning_date is not None:
result += ' (Nagbot: Warned on ' + self.warning_date + ')'
return result
def parse_date_tag(date_tag: str) -> ParsedDate:
parsed_date = ParsedDate(None, False, None)
match = re.match(r'^(\d{4}-\d{2}-\d{2})', date_tag)
if match:
expiry_date = datetime.strptime(match.group(1), '%Y-%m-%d')
parsed_date.expiry_date = date_to_string(expiry_date)
match = re.match(r'^On Weekends', date_tag, re.IGNORECASE)
if match:
parsed_date.on_weekends = True
match = re.match(r'.*\(Nagbot: Warned on (\d{4}-\d{2}-\d{2})\)$', date_tag)
if match:
warning_date = datetime.strptime(match.group(1), '%Y-%m-%d')
parsed_date.warning_date = date_to_string(warning_date)
return parsed_date
def add_warning_to_tag(old_date_tag: str, warning_date: str, replace=False) -> str:
parsed_date = parse_date_tag(old_date_tag)
if parsed_date.warning_date is None or replace:
parsed_date.warning_date = warning_date
return str(parsed_date) |
import torch.nn.functional as F
'''
Network with 784 input units, a hidden layer with 128 units and a ReLU activation,
then a hidden layer with 64 units and a ReLU activation, and finally an output layer with a softmax activation as shown above.
You can use a ReLU activation with the nn.ReLU module or F.relu function.
'''
class Network(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(784, 128)
self.fc2 = nn.Linear(128, 64)
self.output = nn.Linear(64, 10)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.softmax(self.output(x), dim=1)
return x
|
f_name = input('What is your first name? ')
l_name = input('What is your last name? ')
print('Your name is: ' + f_name +' '+ l_name)
|
# 가능한 팀 조합
def Div_Team(pizzaCount, Team):
teamList = []
for z in range(pizzaCount//4 + 1):
rest_z = pizzaCount - z * 4
for y in range(rest_z//3 + 1):
rest_y = rest_z - y * 3
x = rest_y//2
teamList.append([x,y,z])
# print("가능한 팀 배열: ", teamList)
return teamList |
import numpy as np
## Associative property
# create random vectors
n = 10
a = np.random.randn(n)
b = np.random.randn(n)
c = np.random.randn(n)
# the two results
res1 = np.dot(a, np.dot(b, c))
res2 = np.dot(np.dot(a, b), c)
# compare them
# print(res1)
# print(res2)
print([res1, res2])
### special cases where associative property works!
# 1) one vector is the zeros vector
# 2) a==b==c
|
#!/usr/bin/python3
# Description: game where you guess a number between 0 and 100 (play's itself)
# Author: Paul hivert
# Date: 15/10/2018
import random
secret = random.randint(0, 100)
count = 0
throw = random.randint(0, 100)
while secret != throw:
throw = random.randint(0, 100)
count += 1
with open("2b-write.txt", "w") as f:
f.write("try number: ")
f.write(str(count)+"\n")
f.write("number that was guessed: ")
f.write(str(secret)+"") |
# Problem Statement : https://www.codechef.com/CCSTART2/problems/BUYPLSE
# cook your dish here
def buy_please(a, b, x, y) -> int:
if a != 0 or x != 0:
pens_cost = a * x
else:
pens_cost = 0
if b != 0 or y != 0:
pencils_cost = b * y
else:
pencils_cost = 0
total_cost = pens_cost + pencils_cost
print(total_cost)
if __name__ == '__main__':
a, b, x, y = input().split()
a = int(a)
b = int(b)
x = int(x)
y = int(y)
buy_please(a, b, x, y)
#buy_please(1,1,4,8)
|
"""
Completed by Ritu Melroy, January 2020
Cesnsors the list of words from the given emails. The word length is kept but each word is replaced by "X".
Censor One: Censors a phrase out.
Censor Two: Censors a list of words out.
Censor Three: Censors any occurance of a word from the “negative words” list after any “negative” word has occurred twice, as well as censoring everything from the list from the previous step as well and use it to censor email_three.
Censor Four: Censors not only all of the words from the negative_words and proprietary_terms lists, but also censor any words in email_four that come before AND after a term from those two lists.
Project prompt and input emails provided by Codecademy (this is a challenge project not a step-by-step one).
"""
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three = open("email_three.txt", "r").read()
email_four = open("email_four.txt", "r").read()
def censor_one(email, phrase):
x = email.replace(phrase, "XXXXX")
return x
def censor_two(email, list_of_words):
new_list = [word.title() for word in list_of_words]
final = list_of_words + new_list
new_email = []
list_email = email.split("\n")
for para in list_email:
para_words = para.split()
#print(para_words)
#print()
#new_para = []
for bad_word in final:
for i in range(0, len(para_words)):
if para_words[i] == bad_word:
new_word =""
for char in bad_word:
new_word+="X"
para_words.remove(bad_word)
para_words.insert(i, new_word)
para = " ".join(para_words)
new_email.append(para)
final_email = "\n".join(new_email)
for word in final:
if " " in word :
if word in final_email:
new_word =""
for char in word:
new_word+="X"
final_email = final_email.replace(word, new_word)
return final_email
def censor_three(email, proprietary_terms, negative_words):
n_email = censor_two(email, proprietary_terms)
list_email = n_email.split("\n")
list_all_words =[]
for para in list_email:
para_words = para.split()
list_all_words += para_words
cnt =0
index =0
for i in range(0, len(list_all_words)):
if list_all_words[i] in negative_words:
cnt+=1
if cnt>2:
index = i
break
rest_list = list_all_words[i:]
list_all_words = list_all_words[:i]
rest_str = " ".join(rest_list)
x = censor_two(rest_str, negative_words)
rest_list = x.split()
list_all_words.extend(rest_list)
return " ".join(list_all_words)
def censor_four(email, proprietary_terms, negative_words):
n_email = censor_three(email, proprietary_terms, negative_words)
list_all_words = n_email.split()
all_ind = []
for i in range(0, len(list_all_words)):
if "XX" in list_all_words[i]:
all_ind+= [i]
for idx in all_ind:
#before
before_word = list_all_words[idx-1]
n_word = ""
for i in before_word:
n_word += "X"
del list_all_words[idx-1]
list_all_words.insert(idx-1, n_word)
#after
after_word = list_all_words[idx+1]
n2_word = ""
for i in after_word:
n2_word += "X"
del list_all_words[idx+1]
list_all_words.insert(idx+1, n2_word)
return " ".join(list_all_words)
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable" ]
print()
x = censor_four(email_four, proprietary_terms, negative_words) #or change to test other three emails.
print(x) |
# good comment about recursion by Sarah: my understanding is that the pow() inside each pow()
# is waiting for a return value. once we hit the last pow() return 1,
# then each pending pow() get its return value and terminates. I think the key idea is that
# once pow() gets a return value, it terminates, and becomes a value
def sum_list(l):
# this is our base case
if len(l) <= 0:
# by returning 0 we will not effect the result we will get the same number because we are adding 0
return 0
current_val = l.pop()
current_val += current_val
return current_val
sum_list([1, 2, 3, 4, 5])
# this stops when you reach the global scope of current_value 5 |
# must define mph_input to accept raw_input string to avoid ValueError
count = 0
x = 0
y = 0
year_input = (raw_input("How many years into the future would you like to predict?: "))
pop_current = x
x == float(307357870)
yearly_pop_change = y
y == float(2980325.2747252)
val_1 = float(year_input * yearly_pop_change) - float(pop_current)
val_2 = float(val_1 - pop_current)
# if user input is not a number or user input is a #number and it's value is <= 0
# then we continue to the if statement conditions
while year_input.isalpha() or (year_input.isalpha() and (year_input()) <= 0):
if year_input.isdigit() and str(year_input) <= 0:
print "You cannot enter 0, please enter a number"
year_input = raw_input("How many years into the future would you like to predict?: ")
elif not year_input.isdigit():
print "You must enter a number please"
year_input = raw_input("How many years into the future would you like to predict?: ")
while yearly_pop_change == 2980325.2747252:
yearly_pop_change = x + 1
# after while loop must redefine gall_input from raw_input string to convert to a float
year_input = int(year_input)
val_1 = str(val_1)
val_2 = str(val_2)
new_pop1 = " The new population in " + (year_input + 1) + " years will change by " + val_1 + " to be " + val_2
new_pop2 = " The new population in " + year_input + " years will change by " + val_1 + " to be " + val_2
new_pop3 = " The new population in " + str(year_input) + " years will change by " + str(val_1) + " to be " + str(val_2)
new_pop4 = " The new population in " + str(year_input) + " years will change by " + str(val_1) + " to be " + str(val_2)
print year_input + new_pop1
print str(year_input) + str(new_pop2)
print str(year_input) + str(new_pop3)
print str(year_input) + str(new_pop4) |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 23 18:38:47 2018
@author: AKSPAN12
"""
#import library
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#import the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values
#spliting dataset in training and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train,y_test = train_test_split(X,y,test_size=1/3,random_state = 0)
#feature scaling
"""from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)"""
#Fitting simple linear regression on the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
#Predict the test set result
y_pred = regressor.predict(X_test)
#visualising the training set result
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience(Training set)')
plt.xlabel('Years of experience')
plt.ylabel('Salary')
plt.show()
#visualising the test set
plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience(Test set)')
plt.xlabel('Years of experience')
plt.ylabel('Salary')
plt.show()
|
counter = 0 #установим счетчик - это начальное значение переменной для дальнейших вычислений
while counter != 10: #это заголовок цикла, указываем до наступления какого события будет работать цикл.
#В данном случае цикл будет запускаться, пока счетчик не достигнет значения 9, потому что это числоо макисмально
#близко к значению "не равно 10".
print(counter * 4) #выводим значения умножения каждого числа из диапазона 0-9 на три
counter = counter + 1 #указываем, что каждое следующее значение для цикла больше исходного счетчика на 1
print("Цикл завершен") #финальное сообщение системы после завершения цикла.
|
# Cчитаем возраст
BirthYear = input("Введите год Вашего рождения: ") #запрашивает год рождения пользователя.
DesiredYear = input("Введите год, для вычисления возраста: ") #запрашивает год, для которого пользователь хочет вычислить свой возраст.
Age = int(DesiredYear) - int(BirthYear) #переменная для подсчёта разницы между интересующим пользователя годом и годом его рождения.
print ("В" , DesiredYear , "году Вам исполнится" , Age , "лет.") #выводит итог вычислений
|
deepa1=int(input())
Sum=0
dig=0
while(deepa1>0):
dig=deepa1%10
Sum+=dig*dig
deepa1=deepa1//10
print(Sum)
|
from tkinter import *
root = Tk()
def label_function():
label = Label(root, text="Your text here", fg="blue")
label.pack()
STATUS = Label(root, text="the actual thing starts from here....", bd=1, relief=SUNKEN, anchor="e")
bu = Button(STATUS, text="button", command=label_function)
bu.pack(side="left")
STATUS.pack(side="bottom", fill="x")
root.mainloop()
|
#app.py
from flask import Flask, render_template
app= Flask("demoApp")
@app.route("/")
def say_hello():
return "Hello Code First Girls people!"
"""To show instead of page no found "hello and loquepongasaqui" what you
add after the localhost:5000/loquepongasaqui """
@app.route("/<name>")
def say_hello_with_name(name):
return f"Hello {name}"
"""MISMA FUNCION QUE LA ANTERIOR PERO CON VIEJO FORMATO
@app.route("/old/<name>")
def say_helllo_the_old_way_with_name(name):
return "Hello {}".format(name)
"""
"""It shows hello and the name you put after the /
in localhost:5000/loquepongasaqui"""
@app.route("/hello/<name>")
def say_helllo_the_old_way_with_name(name):
return render_template("index.html",name=name)
app.run(debug=True)
|
#!/usr/bin/python
"""
Usage: fasta_capitals.py fastafile.fasta [C/L] > result.fasta
"""
from sys import argv
from string import maketrans
filename = argv[1]
action = argv[2]
def capitals(fil):
transfrom = "abcdefghijklmnopqrstuvxyz"
transto = "ABCDEFGHIJKLMNOPQRSTUVXYZ"
transtab = maketrans(transfrom, transto)
with open(fil) as inputfile:
for line in inputfile:
if line.startswith(">"):
print(line.rstrip())
else:
print(line.translate(transtab).rstrip())
def lowercase(fil):
transfrom = "ABCDEFGHIJKLMNOPQRSTUVXYZ"
transto = "abcdefghijklmnopqrstuvxyz"
transtab = maketrans(transfrom, transto)
with open(fil) as inputfile:
for line in inputfile:
if line.startswith(">"):
print(line.rstrip())
else:
print(line.translate(transtab).rstrip())
if str(action) == "c" or str(action) == "C":
capitals(filename)
elif str(action) == "l" or str(action) == "L":
lowercase(filename)
else:
print("Please input 'C' or 'L' as argument 2 in order to make all nt/aa into capitals or lowercase, respectively ") |
for n in range(50):
if n%15==0:
print("FizzBuzz",end=",")
elif n%3==0:
print("Fizz",end=",")
elif n%5==0:
print("Buzz",end=",")
else:
print(n,end=",")
|
list1 = [11, 5, 17, 18, 23]
total = sum(list1)
print("Sum of all elements in given list: ", total) |
a = ["fizz", "buzz", "baz"]
while a:
print(a.pop(-1))
b = ["---", "==="]
while b:
print(b.pop(-1)) |
# Basic usage of fstrings
# Make sure you're using Python 3.5+!
function_name = "format"
demo_string = f"This is a demonstration of the {function_name} function"
# Expected output: 'This is a demonstration of the format function'
# print(demo_string)
fruits = ["apples", "bananas", "oranges"]
# You can use indices to access lists in f-strings
fruit_demo_string = f"My favorite fruits are {fruits[1]}"
# Expected output: 'My favorite fruits are bananas'
# print(fruit_demo_string)
# With f-strings, you can easily add some random choice!
import random
fruit_demo_string = f"My favorite fruits are (Randomized) {random.choice(fruits)}"
# Expected output: 'My favorite fruits are (Randomized) ??'
# print(fruit_demo_string)
vegetables = {
'carrots': 5,
'tomatoes': 3,
'brussel sprouts': 7,
}
# Dictionary keys work too! (Note the use of quotes in the dict key as compared to with .format())
vegetable_demo_string = f"Carrots are tasty, and they only cost ${vegetables['carrots']} per pound!"
# Expected output: 'Carrots are tasty, and they only cost $5 per pound!'
# print(vegetable_demo_string)
# With f-strings, it's even easier to do arbitrary computations within a string
time_demo_string = f"There are {1000 * 60 * 60 * 24} milliseconds in a day!"
# print(time_demo_string)
# And you have a host of formatting options available to you, just like with format strings. |
# Real Python Vide Course: Python Booleans
# by Cesar Aguilar
# Based on the article https://realpython.com/python-boolean/
# by Moshe Zadka
#%% Lesson 3
from itertools import product
for x, y in product([True, False], repeat=2):
print(f"\t{x} and {y} = {x and y}")
def print_and_return(x):
print(f"\tI am returning {x}")
return x
True and print_and_return(False)
True and print_and_return(True)
True and print_and_return(2/3)
#True and print_and_return(1/0)
False and print_and_return(True)
False and print_and_return(1/0)
|
# iterators with dict.
>>> a = {'foo': 1, 'bar': 2, 'baz': 3}
# here, iterator will have the key values from the dict.
>>> for k in a:
... print(k)
...
...
foo
bar
baz
# iterator will have only dict values.
>>> for k in a.values():
... print(k)
...
...
# returns values of the dict.
1
2
3
# here, iterator will have both key/values from the dict.
>>> for k in a.items():
... print(k)
...
...
# returns dict key/values as tuples.
('foo', 1)
('bar', 2)
('baz', 3)
>>>
>>> for k in a.items():
...
... print(k)
...
...
('foo', 1)
('bar', 2)
('baz', 3)
>>>
>>> for k, v in a.items():
... print(f"k={k} v={v}")
...
...
k=foo v=1
k=bar v=2
k=baz v=3
>>> for k, v in a.items():
... print(f"k={k}\tv={v}")
...
...
k=foo v=1
k=bar v=2
k=baz v=3
>>>
>>>
>>> for k, v in a.items():
... print(f"k={k}, v={v}")
...
...
k=foo, v=1
k=bar, v=2
k=baz, v=3
>>> |
# empty dict
# a = {}
a = dict()
# store some key value pairs
a['name'] = 'praveen'
a['age'] = 27
print(a)
print(a['name'])
# This will introiduce a KeyError
# print(a['country'])
# safer method: using get method to avoid KeyError
print(a.get('name'))
print(a.get('country')) |
# Real Python Vide Course: Python Booleans
# by Cesar Aguilar
# Based on the article https://realpython.com/python-boolean/
# by Moshe Zadka
#%% Lesson 5
print(1 == 1)
print(True == 1)
print(1.0 == 1)
print(1 + 0j == 1)
print(4/2 == 2)
print('1' == 1)
print(2 == [1, 2, 3])
print([1, 2, 3] == [1, 2, 3])
print({1, 2, 3} == {3, 1, 2})
print(0.25 + 0.25 == 0.5)
print(0.2 + 0.1 == 0.3)
x = 0.1
print(f"{x:.50f}")
print(1.0 < 3)
print([4, 0] >= [3, 2000000, 5000000])
print([4, 0] >= [4.1, 2000000, 5000000])
# returns TypeError
#print([1, 2, 3] < {4, 5, 6})
print(1.0 < 3)
a = {"x": 1, "y": 2}
b = {"x": 3, "y": 4}
# returns TypeError
# print(a < b)
print({1, 2, 3} < {4, 5, 6})
print({4, 5, 6} < {1, 2, 3})
print({4, 5, 6} == {1, 2, 3})
print({4, 5, 6} >= {1, 2, 3})
print({4, 5, 6} != {1, 2, 3})
x, y = [1, 2, 3], [1, 2, 3]
print(x == y)
id(x)
id(y)
print(x is y)
z = x
print(x == z)
id(z)
id(x)
print(x is z)
print(z is x)
print(1 in [1, 2, 3])
print("luigi" in {"luigi", "mario", "yoshi"})
print("luigi" in "luigi mario yoshi")
print("bowser" in "luigi mario yoshi")
d = {"a": 1, "b": 3}
print("c" in d)
print("b" in d)
print("b" not in d)
|
# 在Python程序中,分别使用未定义变量、访问列表不存在的索引、访问字典不存在的关键字观察系统提示的错误信息
# 通过Python程序产生IndexError,并用try捕获异常处理
# list1 = [1,2,3,4]
# # print(list1[4])
#
# dict1 = {'a':1,'b':2}
# # print(dict1['c'])
#
# try:
# a = [1,2,3,4]
# print(list1[4])
# print(dict1['c'])
# except:
# print('索引错误')
#
#
# try:
# print(1/0)
# except:
# print('错误')
#定义一个错误信息
# try:
# raise NameError('helloError')
# except:
# print('my custom error')
try:
a = open('name.text')
except Exception as e:
print(e)
finally:
a.close()
|
'''
25 计算1 - 1/2 + 1/3 - 1/4 + … + 1/99 - 1/100 + …直到最后一项的绝对值小于10的-5次幂为止
'''
# import math
# def print_Calculation():
# sum = 1
# a = 1
# while True:
# a += 1
# if abs(1/a) < pow(10,-5):
# break
# elif a %2 == 0:
# sum -= 1/a
# else:
# sum += 1/a
# print(sum)
# print_Calculation()
# def print_fivemi():
# result = 0.0
# n = 1
# while True:
# if abs(1/n) < pow(10,-5):
# break
# else:
# if n%2 ==1:
# result += 1/n
# n += 1
# else:
# result -= 1/n
# n += 1
# print(result)
# print_fivemi()
'''
26 编程将类似“China”这样的明文译成密文,
密码规律是:用字母表中原来
的字母后面第4个字母代替原来的字母,不能改变其大小写,如果超出了字母
表最后一个字母则回退到字母表中第一个字母
'''
# import sys
# def print_mingwen_miwen(s):
# result = ''
# if not isinstance(s,str):
# sys.exit(1) #正常结束~
# for i in s:
# if (i >= 'a' and i<='v') or (i >= 'A' and i<='V'):
# result += chr(ord(i)+4)
# else:
# result += chr(ord(i)-22)
# return result
# print(print_mingwen_miwen('china'))
'''
27 输出以下如下规律的矩阵
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
思路:先用一条for语句控制行数,再用一条for控制列数,规律是行和列相乘
'''
# def print_juzhenguilv():
#
# for i in range(1,5):
# for j in range(1,6):
# print(i*j,end=' ')
# print()
#
# print_juzhenguilv()
'''
28 对一个列表求和,如列表是[4, 3, 6],求和结果是 [4, 7, 13],每一项的值都等与该项的值加上前一项的值
'''
# def liebiao_qiuhe(n):
# li = []
# sum = 0
# for i in range(len(n)):
# sum += n[i]
# li.append(sum)
# return li
# print(liebiao_qiuhe([4,3,6]))
'''
29 一个字符串 list,每个元素是 1 个 ip,输出出现次数最多的 ip
'''
# def print_listip(list):
# for i in list:
#
# print(id(i))
#
# print_listip([1,2,3,3])
# def print_ip():
# num_list = ["168.1.1.1","168.1.1.1","168.1.1.2","168.1.1.3"]
# num_dict = {}
# for i in num_list:
# if i not in num_dict.keys():
# num_dict[i] = 1
# else:
# num_dict[i] += 1
# #一句可以搞定
# #num_dict[i] = num_list.count(i)
# for k,v in num_dict.items():
# if v == max(num_dict.values()):
# print("出现次数最多的IP:",k)
#
# print_ip()
'''
30 实现一个简易版的计算器,功能要求:加、减、乘、除,支持多数同时进行计算
'''
# def jianyi_jisuanqi():
#
#
#
# jianyi_jisuanqi()
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root:TreeNode) -> bool:
if root:
res = validsubBST(root)
else:
res = True
return res
def validsubBST(t):
if not t:
return True
elif not (t.left or t.right):
res = True
elif isinstance(t.right, TreeNode):
if isinstance(t.left, TreeNode):
if t.left.val < t.val and t.right.val > t.val:
res = validsubBST(t.right)
else:
res = False
else:
if t.right.val > t.val:
res = validsubBST(t.right)
else:
res = False
else:
if isinstance(t.left, TreeNode):
if t.left.val < t.val:
res = validsubBST(t.right)
else:
res = False
else:
res = False
return res |
'''
# Version1
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# i,j is the row col location of start point
i = 1
j = 1
N = paths(i, j, m, n)
return N
def paths(i, j, m, n):
if i == m or j == n:
# only one path, add from the outer loop
return 1
else:
return paths(i+1, j, m, n) + paths(i, j+1, m, n)
'''
|
# Python program to print prime numbers in an interval
def print_primes(lower_limit: int, upper_limit: int) -> None:
while lower_limit < upper_limit + 1:
if lower_limit > 1:
interval = 2
while interval < lower_limit:
if lower_limit % interval == 0:
break
interval += 1
else:
print(lower_limit)
lower_limit += 1
# Taking inputs
lower = int(input("Lower Limit: "))
upper = int(input("Upper Limit: "))
print_primes(lower, upper)
|
def LongestRun(line): # get longest run of a character that occurs
longest = 1
index = 1
for i in range(1, len(line)):
if line[i] == line[i-1]:
index += 1
else:
if index > longest:
longest = index
index = 1
if index > longest:
longest = index
return longest
def ChunkLen(List): # set length of "chunk" representing each char
maxLen = 0
for line in List:
if LongestRun(line) > maxLen:
maxLen = LongestRun(line)
return len(str(maxLen)) + 1
def EncodeLine(line, chunkLen):
encoded = ""
run = 1
char = ""
for i in range(1, len(line)):
char = line[i]
if line[i] == line[i-1]:
run += 1
else:
zeros = ""
for j in range(1, chunkLen-len(str(run))):
zeros = zeros + "0"
encoded = encoded + zeros + str(run) + line[i-1]
run = 1
zeros = ""
for j in range(1, chunkLen-len(str(run))):
zeros = zeros + "0"
encoded = encoded + zeros + str(run) + char
return encoded
def EncodeFile(List):
chunkLen = ChunkLen(List)
lineBreak = ""
for i in range(0,chunkLen):
lineBreak = lineBreak + "b"
emptyLine = ""
for i in range(0,chunkLen):
emptyLine = emptyLine + "a"
encoded = str(chunkLen) + "c" # indicate length of chunk at start
for line in List:
if line == "":
encoded = encoded + emptyLine + lineBreak
else:
encoded = encoded + EncodeLine(line, chunkLen) + lineBreak
return encoded
def DecodeFile(string):
chunkLen = int(string[slice(0,string.index("c"))])
index = string.index("c") + 1
line = ""
lineList = []
while index <= len(string) - chunkLen:
Slice = string[slice(index, index + chunkLen)] # whole chunk, not just number
if Slice[0] == "b": # line break
lineList.append(line)
line = ""
elif Slice[0] == "a": # empty line
line = ""
else:
char = Slice[chunkLen-1]
num = int(Slice[slice(0,chunkLen-1)]) # gets number of chars
i = 0
while i < num:
line = line + char
i += 1
index += chunkLen
if not line == "":
lineList.append(line)
return lineList
def EncodeInterface():
print("Enter the file path to encode your ASCII text.")
valid = False
while not valid:
filePath = input(">>> ")
try:
file = open(filePath, "r")
fileLines = file.read().splitlines()
file.close()
valid = True
print(EncodeFile(fileLines))
Menu()
except:
print("Invalid file path. Please retry.")
def DecodeInterface():
print("Enter the run length encoded string to decode.")
valid = False
while not valid:
string = input(">>> ")
try:
List = DecodeFile(string)
for line in List:
print(line)
valid = True
Menu()
except:
print("Invalid input. Please retry.")
def Menu():
print("\n")
print("Run Length Encoding")
print("Press 1 to encode and press 2 to decode.")
valid = False
while not valid:
Input = input(">>> ")
if Input == "1":
valid = True
EncodeInterface()
elif Input == "2":
valid = True
DecodeInterface()
else:
print("Invalid input.")
Menu()
|
#Defining a parent
class Restaurant:
business = True
phoneNumber = '123-456-7890'
email = 'myrestaurant@aol.com'
#Desiging the first child
class PizzaChain(Restaurant):
cuisine = 'american'
specialty = 'pizza'
storeNumber = 345
#Designing the second child with some similiarities but also differences
class ThaiFood(Restaurant):
cuisine = 'Thai'
foodTruck = True
#Finally, showing that inheritance works!
#This first entry should print because email is part of the class definition
print(Restaurant.business)
#For these two, these properties are inherited from the parent Restaurant!
#If they don't print, then the inheritance was unsuccessful.
print(PizzaChain.phoneNumber)
print(ThaiFood.email)
#Success! These two children have inherited from Restaurant
|
num1 = 12
key = False
if num1 == 12:
if key:
print('Num1 is equal to 12 and they have the key')
else:
print('Num1 is equal to 12 and they do not have the key')
elif num1 < 12:
print('Num1 is less than 12')
else:
print('Num1 is not equal to 12')
rexrex = 100
tatsu = 1
tora = 102
if rexrex > tora:
if rexrex > tatsu:
print('rexrex is the winner!')
else:
print('tatsu is the winner! But everyone knows that is false')
elif tora > tatsu:
print('tora is the winner!')
else:
print('the results are inconclusive!')
print(isinstance(tatsu,float))
|
#Here is where we'll keep info related to the GUI for our student register!
from tkinter import *
import tkinter as tk
#Import the other modules created here
import StudentTrackingMain
import StudentTrackingFunctions
def GUI_Layout(self):
"""
I'm going to use grid geometry to lay out our five fields,
plus the two buttons for delete and submit!
Each entry row will have a label, and the entry rows themselves
should stretch for a few columns.
"""
#First Name Label and Positioning
self.labelFirstName = tk.Label(self.master, text="First Name:")
self.labelFirstName.grid(row=0, column=0, padx = (10, 0), pady = (20, 0))
#Last Name Label and Positioning
self.labelLastName = tk.Label(self.master, text="Last Name:")
self.labelLastName.grid(row=2, column=0, padx = (10, 0), pady = (20, 0))
#Phone Number Label and Positioning
self.labelPhoneNumber = tk.Label(self.master, text="Phone #:")
self.labelPhoneNumber.grid(row=4, column=0, padx = (10, 0), pady = (20, 0))
#E-mail Label and Positioning
self.labelEmail = tk.Label(self.master, text="E-mail:")
self.labelEmail.grid(row=6, column=0, padx = (10, 0), pady = (20, 0))
#Current Class Label and Positioning
self.labelCurrentClass = tk.Label(self.master, text="Current Class:")
self.labelCurrentClass.grid(row=8, column=0, padx = (10, 0), pady = (20, 0))
#Creating entry boxes now
#First Name Entry Box
self.textFirstName = tk.Entry(self.master, text="Testing")
self.textFirstName.grid(row=1,column=0, columnspan = 2, padx = (10, 0), pady = (10, 0), stick=E+W)
#Last Name Entry Box
self.textLastName = tk.Entry(self.master, text="")
self.textLastName.grid(row=3,column=0, columnspan = 2, padx = (10, 0), pady = (10, 0), stick=E+W)
#Phone Number Entry Box
self.textPhoneNumber = tk.Entry(self.master, text="")
self.textPhoneNumber.grid(row=5,column=0, columnspan = 2, padx = (10, 0), pady = (10, 0), stick=E+W)
#E-mail Entry Box
self.textEmail = tk.Entry(self.master, text="")
self.textEmail.grid(row=7,column=0, columnspan = 2, padx = (10, 0), pady = (10, 0), stick=E+W)
#Current Class Box
self.textCurrentClass = tk.Entry(self.master, text="")
self.textCurrentClass.grid(row=9,column=0, columnspan = 2, padx = (10, 0), pady = (10, 0), stick=E+W)
#Now for the buttons!
#Adding the delete button
self.buttonDeleteButton = tk.Button(self.master, width = 20, height = 2, text = "Delete", command=lambda: StudentTrackingFunctions.deleteEntry(self))
self.buttonDeleteButton.grid(row=10, column= 0, columnspan = 2, padx = (10, 0), pady = (10, 10))
#Adding the delete button
self.buttonSubmitButton = tk.Button(self.master, width = 20, height = 2, text = "Submit", command=lambda: StudentTrackingFunctions.addEntry(self))
self.buttonSubmitButton.grid(row=10, column=2, columnspan = 2, padx = (10, 0), pady = (10, 10))
#Now for the dB records so they can be viewed and deleted!
self.listMainList = Listbox(self.master)
self.listMainList.bind('<<ListboxSelect>>',lambda event: StudentTrackingFunctions.onSelect(self,event))
self.listMainList.grid(row = 1, column = 3, rowspan = 9, columnspan = 6, stick=N+E+S+W)
if __name__ == "__main__":
pass
|
"""This scraper is intended to pull weather station data from the html code of the CIMIS website. As of yet, this imple
mentation has been left for another time."""
import requests
from lxml import html
page = requests.get('http://www.cimis.water.ca.gov/Stations.aspx')
tree = html.fromstring(page.content)
#Xpath List
#/html/body/form/div[4]/div[3]/div/div[3]/div[3]/div[2]/div/div/div/table/tbody/tr[1]/td[2]
#/html/body/form/div[4]/div[3]/div/div[3]/div[3]/div[2]/div/div/div/table/tbody/tr[1]/td[3]
#/html/body/form/div[4]/div[3]/div/div[3]/div[3]/div[2]/div/div/div/table/tbody/tr[1]/td[4]
#/html/body/form/div[4]/div[3]/div/div[3]/div[3]/div[2]/div/div/div/table/tbody/tr[1]/td[5]/span
#This will create a list of station numbers:
station_num = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of names
station_name = tree.xpath('//span[@class="item-price"]/text()')
#This will create a list of counties:
counties = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of status
status = tree.xpath('//span[@class="item-price"]/text()')
print('Station Numbers: ', station_num)
print('Station names: ', station_name)
print('Counties: ', counties)
print('Status: ', status)
|
if __name__ == '__main__':
answer = []
N = int(input())
for i in range(N):
task = input().split()
if task[0] == 'append':
answer.append(int(task[1]))
elif task[0] == 'insert':
answer.insert(int(task[1]), int(task[2]))
elif task[0] == 'pop':
answer.pop()
elif task[0] == 'print':
print(answer)
elif task[0] == 'remove':
answer.remove(int(task[1]))
elif task[0] == 'reverse':
answer.reverse()
elif task[0] == 'sort':
answer.sort()
|
import turtle
from math import *
tom = turtle.Turtle()
tom.speed(0)
tom.width(10)
tom.ht()
def goto(x,y):
tom.pu()
tom.goto(x,y)
tom.pd()
def circle(x,y,radius):
heading = tom.heading()
goto(x,y-radius)
tom.setheading(0)
tom.circle(radius)
goto(x,y)
tom.setheading(heading)
angle = 0
while True:
#backgrounding
tom.color("white")
tom.width(10000)
tom.fd(0.1)
tom.width(5)
tom.color("black")
r1 = 100 #var
x1,y1=0,0 #var
circle(x1,y1,r1)
r2 = r1/2.0 #var
angle += 0.1 #var
rsum = r1 + r2 #var
x2 , y2 = x1 + rsum * cos(angle) , y1 + rsum * sin(angle) #var
circle(x2,y2,r2) |
'''
This module contains functions for text similarity
'''
import math
def getBow(text):
# This function returns bag of words given a text
# print 'text:', text
text = text.lower()
keywordList = text.split(' ')
# print keywordList
bowDict = {}
for keyword in keywordList:
if keyword in bowDict:
bowDict[keyword] += 1
else:
bowDict[keyword] = 1
# pprint(bowDict)
return bowDict
def getDotProduct(bow1, bow2):
'''
:param bow1: dictionary of bow1
:param bow2: dictionary of bow2
:return: dot product between them
'''
dot_product = 0
for keyword1, freq1 in bow1.items():
if keyword1 in bow2:
value1 = freq1
value2 = bow2[keyword1]
dot_product += value1*value2
return dot_product
def getNorm(bow):
'''
:param bow1: bag of words dictionary of text
:return: norm of the vector
'''
# print bow
sum_of_squares = 0
for keyword, freq in bow.items():
sum_of_squares += freq*freq
norm = math.sqrt(sum_of_squares)
return norm
def getCosineScore(bow1, bow2):
# print 'Inside cosine score'
'''
Get cosine score between two bag of words dictionaries
{'bow1': {'am': 1, 'anand': 1, 'i': 2}}
{'bow2': {'a': 1, 'am': 1, 'data': 1, 'i': 1, 'scientist': 1}}
mycosine = dot(a,b)/(norm(a)*norm(b))
'''
dot_product = getDotProduct(bow1, bow2)
# print dot_product
norm1 = getNorm(bow1)
norm2 = getNorm(bow2)
# print 'norm1:', norm1
# print 'norm2:', norm2
mycosine = dot_product / (norm1*norm2)
# print 'mycosine:', mycosine
return mycosine
def getSimilarityBetweenTexts(text1, text2):
# print text1
# print text2
# Get bag of words of both texts
bow1 = getBow(text1)
bow2 = getBow(text2)
# pprint({'bow1': bow1})
# pprint({'bow2': bow2})
# Compute similarity between the bag of words
mycosine = getCosineScore(bow1, bow2)
similarityScore = mycosine
return similarityScore
if __name__ == '__main__':
print 'Text Similarity Module'
# Grab the texts
text1 = 'I am Anand'
text2 = 'i am a data scientist'
# print text1
# print text2
# Get bag of words
# getBow(text1)
# Get similarity scores between the two texts
similarityScore = getSimilarityBetweenTexts(text1, text2)
print 'similarityScore:', similarityScore
# bow1 = getBow(text1)
# print bow1
# norm = getNorm(bow1)
#
# print norm
# print math.sqrt(6)
|
#exercise 1.6
#simple version
print(1+2+3+4+5+6+7+8+9)
#loop version
x = 1
sum = 0
while (x <= 9):
sum = sum + x
x = x + 1
print(sum)
|
#This generates the random numbers
import random
#This generates that we are doing math and calculating the number of coin tosses
import math
#This will print starting the program
print "Starting the program"
#setting variable head_count to 0 to start with as a default
head_count= 0
#same with tail_count
tail_count = 0
#setting the range from 1-5000
for a in range(1,5001):
#setting variable rand to generate random numbers
rand = round(random.random())
#if variable rand is equal to 0
if rand == 0:
# and the face of the coin toss is "tail"
face = "tail"
#then change the tail count plus 1
tail_count += 1
else:
#othwewise if the face of the coin toss is "head"
face = "head"
#then change the head count plus 1
head_count += 1
#print out "attempt # 1" Throwing a coin..its a (heads or tails) Got (1 heads) and (0 tails) so far
print "attempt #" + str(a) +: Throwing a coin..Its a "+face"..Got "+str(head_count)+" head(s) and "+str(tail_count)+" tail(s) so far"
print "end"
|
import numpy as np
import a3_module as am
import matplotlib.pyplot as plt
# Assignment 3
# Finn Womack
################
# Loading data #
################
Train = np.genfromtxt('knn_train.csv', delimiter=',') # Loads the Training data
Test = np.genfromtxt('knn_test.csv', delimiter=',') # loads the Test data
#############################################
# Split independent and dependent variables #
#############################################
Y_Train = Train[:,0] # loads the training class data into a vector
Y_Test = Test[:,0] # load the testing class data into a vector
X_Train = Train[:,1:] # load the training feature data into an array
X_Test = Test[:,1:] # load the testing feature data into an array
##################
# Normalize data #
##################
for n in np.arange(X_Train.shape[1]):
Min_Train = np.amin(X_Train[:,n])
Range_Train = np.amax(X_Train[:,n]) - np.amin(X_Train[:,n])
X_Train[:,n] = X_Train[:,n] - Min_Train
X_Train[:,n] = 10 * X_Train[:, n] / Range_Train
X_Test[:, n] = X_Test[:, n] - Min_Train
X_Test[:, n] = 10 * X_Test[:, n] / Range_Train
###############
# Problem 1.2 #
###############
K = np.arange(1,70,2) # set up a vector of K values
Train_Error = np.zeros(K.shape[0]) # initialize a vector for training error
eps = np.zeros(K.shape[0]) # initialize a vector for cross validation error
Test_Error = np.zeros(K.shape[0]) # initialize a vector for cross validation error
for n in np.arange(K.shape[0]): # loop through all K values
P_Train = am.knnPred(X_Train, Y_Train, X_Train, K[n]) # predict for training data
Train_Error[n] = sum((P_Train != Y_Train))/Y_Train.shape[0] # sum errors and normalize to [0,1]
for m in np.arange(X_Train.shape[0]): # loop through each sample to leave out
ind = np.ones((X_Train.shape[0],), bool) # make a vector of True values
ind[m] = False # set mth value to False
X2 = X_Train[ind,:] # Subset X to leave one out
Y2 = Y_Train[ind] # Subset Y to leave one out
P2 = am.knnPred(X2, Y2, np.array([X_Train[m,:]]), K[n]) # predict on the sample left out
eps[n] = eps[n] + (P2 != Y_Train[m]) # add errors to cross validation error
eps[n] = eps[n] / (m+1) # average cross validation error
P_Test = am.knnPred(X_Train, Y_Train, X_Test, K[n]) # predict for testing data
Test_Error[n] = sum(P_Test != Y_Test)/Y_Test.shape[0] # sum errors and normalize to [0,1]
# Note: I normalized the testing and training error so that it would be
# on the same scale as the cross validation error
plt.plot(K, Train_Error, 'bo-', K, eps, 'go-', K, Test_Error, 'mo-') # Plot the 3 error to compare
plt.xlabel('K')
plt.ylabel('Percent missed')
plt.title('Error Ratios on K-NN Predictions')
plt.show()
####################
# Unnormalize Data #
####################
Train = np.genfromtxt('knn_train.csv', delimiter=',') # Loads the Training data
Test = np.genfromtxt('knn_test.csv', delimiter=',') # loads the Test data
Y_Train = Train[:,0] # loads the training class data into a vector
Y_Test = Test[:,0] # load the testing class data into a vector
X_Train = Train[:,1:] # load the training feature data into an array
X_Test = Test[:,1:] # load the testing feature data into an array
###############
# Problem 2.1 #
###############
Stump_1 = am.treePlanter(X_Train, Y_Train, 1) # create a decition stump
pred_Test = am.treeRead(X_Test, Stump_1); # make predictions on testing data from the stump
pred_Train = am.treeRead(X_Train, Stump_1); # make predictions on training data from the stump
test_error = sum(Y_Test != pred_Test) # sum the total errors made on testing data
train_error = sum(Y_Train != pred_Train) # sum the total errors made on training data
###############
# Problem 2.2 #
###############
d = np.arange(10)+1 # initialize the depth vector
test_acc = np.zeros((1,len(d))).flatten() # initialize the testing accuracy vector
train_acc = np.zeros((1,len(d))).flatten() # initialize the training accuracy vector
for a in np.arange(len(d)): # iterate over every depth parameter
tree = am.treePlanter(X_Train, Y_Train, d[a]) # generate tree
pred = am.treeRead(X_Test, tree) # make predictions on testing data
test_acc[a] = sum(sum(np.transpose(Y_Test) != np.transpose(pred)))/len(Y_Test) # total errors and normalize to [0,1]
pred = am.treeRead(X_Train, tree) # make predictions on training data
train_acc[a] = sum(sum(np.transpose(Y_Train) != np.transpose(pred)))/len(Y_Train) # total errors and normalize to [0,1]
plt.plot(d, test_acc, 'bo-', d, train_acc, 'mo-')
plt.xlabel('Depth')
plt.ylabel('Error Rate')
plt.title('Error Rate of Predictions vs Tree Depth')
plt.show()
#############
# Problem 3 #
#############
Best_Depth = test_acc.argsort()[0] # Find the depth with the lowest testing error
######################
# Find Features Used #
######################
tree = am.treePlanter(X_Train, Y_Train, Best_Depth) # grow tree with best depth
Used_Features = [x for x in set(tree[:,0].astype(int))] # find the features used in the tree
###############
# Subset data #
###############
X_Train = X_Train[:,Used_Features]
X_Test = X_Test[:,Used_Features]
####################
# Renormalize data #
####################
for n in np.arange(X_Train.shape[1]):
Min_Train = np.amin(X_Train[:,n])
Range_Train = np.amax(X_Train[:,n]) - np.amin(X_Train[:,n])
X_Train[:,n] = X_Train[:,n] - Min_Train
X_Train[:,n] = 10 * X_Train[:, n] / Range_Train
X_Test[:, n] = X_Test[:, n] - Min_Train
X_Test[:, n] = 10 * X_Test[:, n] / Range_Train
#########################################
# Replot knn with reduced feature space #
#########################################
K = np.arange(1,70,2) # set up a vector of K values
Train_Error = np.zeros(K.shape[0]) # initialize a vector for training error
eps = np.zeros(K.shape[0]) # initialize a vector for cross validation error
Test_Error = np.zeros(K.shape[0]) # initialize a vector for cross validation error
for n in np.arange(K.shape[0]): # loop through all K values
P_Train = am.knnPred(X_Train, Y_Train, X_Train, K[n]) # predict for training data
Train_Error[n] = sum((P_Train != Y_Train))/Y_Train.shape[0] # sum errors and normalize to [0,1]
for m in np.arange(X_Train.shape[0]): # loop through each sample to leave out
ind = np.ones((X_Train.shape[0],), bool) # make a vector of True values
ind[m] = False # set mth value to False
X2 = X_Train[ind,:] # Subset X to leave one out
Y2 = Y_Train[ind] # Subset Y to leave one out
P2 = am.knnPred(X2, Y2, np.array([X_Train[m,:]]), K[n]) # predict on the sample left out
eps[n] = eps[n] + (P2 != Y_Train[m]) # add errors to cross validation error
eps[n] = eps[n] / (m+1) # average cross validation error
P_Test = am.knnPred(X_Train, Y_Train, X_Test, K[n]) # predict for testing data
Test_Error[n] = sum(P_Test != Y_Test)/Y_Test.shape[0] # sum errors and normalize to [0,1]
# Note: I normalized the testing and training error so that it would be
# on the same scale as the cross validation error
plt.plot(K, Train_Error, 'bo-', K, eps, 'go-', K, Test_Error, 'mo-') # Plot the 3 error to compare
plt.xlabel('K')
plt.ylabel('Percent missed')
plt.title('Error Ratios on K-NN Predictions with Reduced Features')
plt.show()
|
class Validator(Exception):
pass
class WordValidatorException(Exception):
pass
class WordValidator(object):
'''
Class that validates if given word is correct.
'''
@staticmethod
def validate(word):
if len(word) == 0:
raise WordValidatorException("Can't be an empty word") |
# Написать функцию, возвращающую два введеных с клавиатуры числа
def get_num():
"""Функция возвращает введенные с клавиатуры числа"""
x = int(input('Число A: '))
y = int(input('Число B: '))
return x, y
try:
print(get_num())
except ValueError:
print('Введены некорректные числа')
|
# Задача: Дано число n. С начала суток прошло n минут. Определите, сколько часов и минут будут показывать
# электронные часы в этот момент. Программа должна вывести два числа: количество часов (от 0 до 23) и
# количество минут (от 0 до 59). Учтите, что число n может быть больше, чем количество минут в сутках.
inputMinutes = int(input('Введите количество минут: '))
newDayMinutes = inputMinutes % 1440
hours = newDayMinutes // 60
minutes = newDayMinutes % 60
print(hours, minutes)
|
# Заполнить список из десяти элементов произвольными целочисленными значениями.
# Затем четные элементы расположить в начале списка, нечетные - в конце.
import random
ARR_LEN = 10
startList = [random.randint(0, 1000) for _ in range(ARR_LEN)]
result = []
print('Список: ', startList)
for i in startList:
if i % 2 == 0:
result.insert(0, i)
else:
result.append(i)
print('Сначала четные, потом нечетные: ', result)
|
# Написать функцию, принимающую длину стороны квадрата и рассчитывающую периметр квадрата, его площадь и диагональ.
# Сделать два и более варианта функции, которые должна отличаться количеством возвращаемых переменных.
# Не забыть про проверки входных данных в самой функции.
def square_calc(sides_tup):
"""Функция вычисляет периметр квадрата, его площадь и диагональ"""
perimeter = 2 * (sides_tup[0] + sides[1])
square = sides_tup[0] * sides[1]
diagonal = (sides_tup[0] ** 2 + sides[1] ** 2) ** 0.5
return perimeter, square, diagonal
def get_sides():
"""Функция возвращает введенные с клавиатуры числа"""
x = int(input('Сторона A: '))
y = int(input('Сторона B: '))
return x, y
sides = ()
try:
sides = get_sides()
except ValueError:
print('Введены некорректные числа')
exit()
per, sq, diag = square_calc(sides)
print('Периметр: {}, Площадь: {}, Диагональ: {:.2f}'.format(per, sq, diag))
|
# Написать функцию, вычисляющую сумму двух переданных чисел.
def sum_num(*args):
"""Функция вычисяет сумму переданных в нее чисел"""
num_sum = 0
for i in args:
num_sum += i
return num_sum
print(sum_num(5, 8))
|
def findbyname(tower, name):
for e in tower.elements:
if e.name == name:
return e
def get_stack(tower, element):
stack = [element]
for x in element.children:
stack += get_stack(tower, findbyname(tower, x))
return stack
def getsubtower(tower, element):
return Tower(get_stack(tower, element))
def balanced(tower):
if tower.length == 1:
return True
else:
base = tower.max_stack()
childtowers = [getsubtower(tower, findbyname(tower, name)) for name in base.children]
for t in childtowers:
if t.weight != childtowers[0].weight:
return False
return True
def balance(tower):
prev = tower
# while tower has children with different weights
while not balanced(tower):
base = tower.max_stack()
childtowers = [getsubtower(tower, findbyname(tower, name))
for name in base.children]
for child in childtowers:
imbalanced = False
# if child has children with different weights
if not balanced(child):
imbalanced = True
prev = tower
tower = child
break
# this tower is unbalanced and none of its children are, one of the
# children must be causing the problem
if imbalanced == False:
break
# Here tower is the tower with bad as a child.
# we need to identify which child is bad; it is the only one whose weight
# only occurs once.
childtowers = [getsubtower(tower, findbyname(tower, name))
for name in tower.max_stack().children]
child_weights = [child.weight for child in childtowers]
# enumerate the weights, and find the correct one (appears > 1 times)
# and the bad one (appears only once)
for idx, weight in enumerate(child_weights):
occurrences = [w for w in child_weights if w == weight]
# these checks only make sense if there is more than one element
if len(childtowers) > 1 and len(occurrences) > 1:
target = weight
elif len(childtowers) > 1 and len(occurrences) == 1:
bad = childtowers[idx]
# diff is target (a good sibling's total weight) - the bad tower's
# total weight
diff = target - bad.weight
# return bad tower's base element's weight plus the difference (with the
# test data, this is 68 + -8)
return bad.max_stack().weight + diff
class TowerElement():
def __init__(self, name, weight, children):
self.name = name
self.weight = weight
self.children = children
class Tower():
def __init__(self, elements):
self.elements = elements
self.weight = sum([e.weight for e in elements])
self.length = len(elements)
def max_stack(self):
return self.sort()[0]
def sort(self):
return sorted(self.elements, key = lambda x: getsubtower(self, x).length, reverse=True)
with open("../data/day7.txt", "r") as data:
lines = data.readlines()
elements = []
for element in lines:
name = element.split()[0]
weight = int(element.split("(")[1].split(")")[0])
if " -> " in element:
children = element[:-1].split(" -> ")[1].split(", ")
else:
children = []
elements.append(TowerElement(name, weight, children))
tower = Tower(elements)
print(tower.max_stack().name)
print(balance(tower)) |
num=float(input())
num=num.reverse()
print(num)
#didnt finish
#real answer:
num = input('Enter a float number: ')
decimals = list(num.split('.')[1])
decimals.reverse()
print(''.join(decimals)) |
class bank:
name="Viktor"
balance=0
def __init__(self):
self.name="Viktor"
self.balance=0
def display(self):
print('hello',self.name)
print('your balance is ',self.balance,'dollars')
def deposit_money(self):
print('how much money do you want to deposit?')
c=float(input())
self.balance=self.balance+c
print('Successfully deposited',c,'dolars')
print('Your new balance is',self.balance,'dollars')
def withdraw_money(self):
print('how much money do you want to withdraw?')
q=float(input())
if self.balance <q:
print('You cant withdraw that amount of money.')
else:
self.balance=self.balance-q
print('Successfully withdrew',q,'dollars')
print('Your new balance is',self.balance,'dollars')
bank()
|
class bank:
def __init__(self):
print('how much money do you want to deposit?')
a=int(init())
print(a)
bank()
|
import random
import statistics
'''
num1=[]
num2=[]
print('give me a number')
num1=int(input())
print('give me a number')
num2=int(input())
if num2 < num1:
print("the smallest number is "+str(num2))
if num1 < num2:
print("the smallest number is "+str(num1))
if num1 == num2:
print("they are the same")
#different code
num1=[]
num2=[]
num3=[]
print('give me a number')
num1=int(input())
print('give me a number')
num2=int(input())
print("give me a number")
num3=int(input())
if num1 < num2 and num3 < num2:
print("the largest number is" + str(num2))
if num1 < num3 and num2 <num3:
print("the largest number is" + str(num3))
if num2 < num1 and num3 < num1:
print("the largest number is" + str(num1))
if num1==num2 and num2==num3:
print("they are the same")
if num2 < num1 and num1==num3:
print("the largest number is"+str(num1))
if num3 < num1 and num1==num2:
print("the largest numberis"+str(num1))
if num1 < num2 and num2==num3:
print("the largest number is"+str(num2))
if num3 < num1 and num2==num3:
print("the largest number is"+str(num2))
#different code
s=[]
for n in range(0,10,1):
z=random.randint(1,100)
s.append(z)
big=1
small=100
for x in s:
if big<x:
big=x
print('the largest number is '+str(big))
for y in s:
if small>y:
small=y
print('the smallest number is '+str(small))
s.remove(big)
s.append(big)
s.remove(small)
s.insert(0,small)
a=0
for x in s:
a=a+x,
a=a/10
print(a)
print(s)
for q in range(7,10,1):
print(s[q],end= ' ')
s.pop(4)
s.pop(8)
print(s)
#different code
s=['I','Like','Pie','!!!']
for x in range(0,len(s),1):
print(s[x])
#different code
s={'a ':'human','is not':'a monster','a':'monster','is not':'a human','i like':'trains'}
print(s['a'])
print(s)
s['a']='troll'
print(s['a'])
'
#different code
s={'pop':4 ,'POP':5,'Pop':2,'POp':1,'PoP':3}
sval=s.values()
sval=list(sval)
sval.sort()
print(sval)
for n in range(0,5,1):
big=0
valbig=''
for x in s:
if big<s[x]:
big=s[x]
valbig=x
print('the bigest number is',big,valbig)
s.pop(valbig)
#diferent code
f=1
print('what is the factorial?')
F=int(input())
for s in range(F,0,-1):
f=f*s
print(f)
#different code
print('what is the factorial?')
F=int(input())
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
value=factorial(F)
print(value)
#different code
gcd=1024
gcd2=1996
def gcd(gcd1,gcd2):
if gcd2%gcd1==0:
return gcd
else gcd1%gcd2!=0:
gcd1=gcd2
gcd1/gcd2=gcd1
gcd()
#Different Code
num=''
print('what number?')
num=int(input())
flag=False
for x in range (2,num,1):
if num%x==0:
print('Not Prime')
flag=True
break
if flag==False:
print('Prime')
#different code
#sieve of erasthosthenes
print('what is the staring number?')
start=int(input())
print('what is the ending number?')
end=int(input())
for s in range(start,end,1):
flag=False
for x in range (2,s,1):
if s%x==0:
print('Not Prime')
flag=True
break
if flag==False:
print('Prime')
#different code
#ordinal code(ASCII)
print(ord('1'))
print(chr())
'''
#continuation
#cesars cypher
passw=('')
print('what is the pasword')
passw=input()
passl=passw.__len__()
cipher=random.randint(1,10000)
for a in range(0,passl,1):
ordvar=(ord(passw)+cipher)
print(chr(ordvar))
|
from tkinter import*
master=Tk()
master.title("IDK what to call this")
'''l1=Label(master,text="First Name").grid(row=0)#label
b1=Button(master,text="click to close",command=master.quit).grid(row=1,column=0)#button
e1=Entry(master)#entry
e1.grid(row=0,column=1)#entry'''
def ShowCoice():
g=v.get()
v.set(g)
l2=Label(master,textvariable=v).grid(row=6,sticky=W)
a=1
l1=Label(master,text="What's your Favorte Color?").grid(row=0,sticky=W)
v=StringVar()
stuff=[("Blue",'Correct'),("Green",'Incorrect'),("Red",'Wrong'),("Orange",'Not Right'),("Yellow",'Not Correct')]
for txt,val in stuff:
Radiobutton(master,text=txt,padx=20,variable=v,command=ShowCoice,value=val).grid(row=a,column=0)
a=a+1
|
class phonebook1:
def __init__(self,n):
self.name2=n
self.name={'bob':'111-111-1111','joe':'222-222-2222','billy':'333-333-3333'}
def name1(self):
print('What is your name?')
na=input()
print('What is your phone number?')
pn=input()
self.name[na]=pn
print(self.name)
|
import matplotlib.pyplot as plt
figure=plt.figure(1,figsize=(9,6)) #makes the boxplot
axes=figure.add_subplot(111, title="Boxplot Are cool") #adds name
axes.boxplot([[1, 2, 3, 4, 5], [6,7,8,9,10],[11,12,13,14,15]])#shows the axes each list in the list is 1 box plot
axes.set_xticklabels(["Dogs","Cats","Bats"])
plt.show() |
'''lst=[]
for s in range(1,31,1):
lst.append(s)
for i in range(0,10,1):
lst[i]=(i+1)**3
for s in range(24,30,1):
lst[s]=(s+1)**2
print("the biggest number is",max(lst),"the smallest number is",min(lst))
lst.pop(15)
lst.pop(16)
print(lst)
for x in range(25,28,1):
print(lst[x])
x=x+1
#different code
for s in range(1,51,1):
if s%5==0 and s%3==0:
print("FizzBuzz")
elif s%3==0:
print("Fizz")
elif s%5==0:
print("Buzz")
else:
print(s)
#different code
for e in range(1,10,1):
for s in range(1,10,1):
print(s*e, end=' ')
print('')
#different code
f=0
pw=''
print("what is yout password?")
pw=input()
l=len(pw)
while True:
if 5<=l<=8:
for i in range(10):
if str(i) in pw:
print("valid")
f=1
break
if f==1:
break
print("invalid please try again")
print("what is your password?")
pw=input()
else:
print("invalid please try again")
print("what is your password?")
pw=input()
l=len(pw)
'''
#different code
s={}
for e in range(1,101,1):
s[e]=e*e
for e in range(1,101,1):
if e%10==0:
s.pop(e)
print(s)
|
'''
Using Multiple Linear Regression by backward Elimination#
This script will have additional steps for backward elimination to chose the best independent variables.
By best, we mean the one which have more impact in predicting the output.
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import utility.utils as utl
#import utility.utils as utl
#read the file
dataset = pd.read_csv("50_Startups.csv")
#set the independent and dependent variable
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:, 4].values
#Encoding categorical data (State)
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelEnc_X = LabelEncoder()
#country is at index 3
X[:,3] = labelEnc_X.fit_transform(X[:,3])
#you might want to check for categories='auto'
onehotEnc = OneHotEncoder(categorical_features=[3])
X = onehotEnc.fit_transform(X).toarray()
#Avoid the dummy variable Trap, remove one dummy variable column
#Selecting all column starting from index - 1, In most cases libraries take care of it
X = X[:,1:]
#divide X,Y into test and training set
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=1/5,random_state=0)
#fitting the data into MLR
from sklearn.linear_model import LinearRegression
startup_mlr = LinearRegression()
startup_mlr.fit(X_train,y_train)
#model created, lets test the model on test data
y_pred_test = startup_mlr.predict(X_test)
'''
utl.print_actual_predicted(y_test,y_pred_test,True)
#model created, lets test the model on training data
y_pred_train = startup_mlr.predict(X_train)
utl.print_actual_predicted(y_train,y_pred_train,True)
'''
#building the optimal model via backward elimination
import statsmodels.formula.api as sm
#add column of 1, to make y = b0X0+b1X1....+bnXn. Here X0=1
#Step 0 - add 1 column for bo
X = np.append(arr = np.ones((50,1)).astype(int), values = X, axis=1)
#Step 1 - set SL = 0.5 (Significance level)
SL = 0.5
#Step 2 - fit all the predictor in the model
#create a new matrix which will contain the optimal features (right now all of them)
X_optimal = X[:,[0,1,2,3,4,5]]
#create the regression with least square from statsmodels.formula.api
#for using this we have added 1 column in Step 0 as the library will not take the intercept b0
regressior_OLS = sm.OLS(endog = y,exog=X_optimal).fit()
#This will print the summary from which we can get the P-value of different independet variables
regressior_OLS.summary()
#Step 3 - Select the predictor/feature/independent variable with highest p-value
# check if p-value > S.L. goto step 4 otherwise we got out model with needed predictors.
'''
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.951
Model: OLS Adj. R-squared: 0.945
Method: Least Squares F-statistic: 169.9
Date: Sun, 10 Feb 2019 Prob (F-statistic): 1.34e-27
Time: 21:01:49 Log-Likelihood: -525.38
No. Observations: 50 AIC: 1063.
Df Residuals: 44 BIC: 1074.
Df Model: 5
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 5.013e+04 6884.820 7.281 0.000 3.62e+04 6.4e+04
x1 198.7888 3371.007 0.059 0.953 -6595.030 6992.607
x2 -41.8870 3256.039 -0.013 0.990 -6604.003 6520.229
x3 0.8060 0.046 17.369 0.000 0.712 0.900
x4 -0.0270 0.052 -0.517 0.608 -0.132 0.078
x5 0.0270 0.017 1.574 0.123 -0.008 0.062
==============================================================================
Omnibus: 14.782 Durbin-Watson: 1.283
Prob(Omnibus): 0.001 Jarque-Bera (JB): 21.266
Skew: -0.948 Prob(JB): 2.41e-05
Kurtosis: 5.572 Cond. No. 1.45e+06
==============================================================================
'''
#Step 4 - We took X2 p-value = 0.990 which is greater then 0.5
#Remove this predictor at index 2
X_optimal = X[:,[0,1,3,4,5]]
#Step 5 - fit the model again
regressior_OLS = sm.OLS(endog = y,exog=X_optimal).fit()
#Step 3
regressior_OLS.summary()
'''
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.951
Model: OLS Adj. R-squared: 0.946
Method: Least Squares F-statistic: 217.2
Date: Sun, 10 Feb 2019 Prob (F-statistic): 8.49e-29
Time: 21:21:30 Log-Likelihood: -525.38
No. Observations: 50 AIC: 1061.
Df Residuals: 45 BIC: 1070.
Df Model: 4
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 5.011e+04 6647.870 7.537 0.000 3.67e+04 6.35e+04
x1 220.1585 2900.536 0.076 0.940 -5621.821 6062.138
x2 0.8060 0.046 17.606 0.000 0.714 0.898
x3 -0.0270 0.052 -0.523 0.604 -0.131 0.077
x4 0.0270 0.017 1.592 0.118 -0.007 0.061
==============================================================================
Omnibus: 14.758 Durbin-Watson: 1.282
Prob(Omnibus): 0.001 Jarque-Bera (JB): 21.172
Skew: -0.948 Prob(JB): 2.53e-05
Kurtosis: 5.563 Cond. No. 1.40e+06
==============================================================================
'''
#Now x1 is p-value = .94 > SL, repeat step 4,5 and go to step 3
#Step 4
X_optimal = X[:,[0,3,4,5]]
#Step 5 - fit the model again
regressior_OLS = sm.OLS(endog = y,exog=X_optimal).fit()
#Step 3
regressior_OLS.summary()
'''
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.951
Model: OLS Adj. R-squared: 0.948
Method: Least Squares F-statistic: 296.0
Date: Sun, 10 Feb 2019 Prob (F-statistic): 4.53e-30
Time: 21:24:03 Log-Likelihood: -525.39
No. Observations: 50 AIC: 1059.
Df Residuals: 46 BIC: 1066.
Df Model: 3
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 5.012e+04 6572.353 7.626 0.000 3.69e+04 6.34e+04
x1 0.8057 0.045 17.846 0.000 0.715 0.897
x2 -0.0268 0.051 -0.526 0.602 -0.130 0.076
x3 0.0272 0.016 1.655 0.105 -0.006 0.060
==============================================================================
Omnibus: 14.838 Durbin-Watson: 1.282
Prob(Omnibus): 0.001 Jarque-Bera (JB): 21.442
Skew: -0.949 Prob(JB): 2.21e-05
Kurtosis: 5.586 Cond. No. 1.40e+06
==============================================================================
'''
#Now x2 is p-value = .602 > SL, repeat step 4,5 and go to step 3
#Step 4
X_optimal = X[:,[0,3,5]]
#Step 5 - fit the model again
regressior_OLS = sm.OLS(endog = y,exog=X_optimal).fit()
#Step 3
regressior_OLS.summary()
'''
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.950
Model: OLS Adj. R-squared: 0.948
Method: Least Squares F-statistic: 450.8
Date: Sun, 10 Feb 2019 Prob (F-statistic): 2.16e-31
Time: 21:25:30 Log-Likelihood: -525.54
No. Observations: 50 AIC: 1057.
Df Residuals: 47 BIC: 1063.
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 4.698e+04 2689.933 17.464 0.000 4.16e+04 5.24e+04
x1 0.7966 0.041 19.266 0.000 0.713 0.880
x2 0.0299 0.016 1.927 0.060 -0.001 0.061
==============================================================================
Omnibus: 14.677 Durbin-Watson: 1.257
Prob(Omnibus): 0.001 Jarque-Bera (JB): 21.161
Skew: -0.939 Prob(JB): 2.54e-05
Kurtosis: 5.575 Cond. No. 5.32e+05
==============================================================================
'''
#Now x2 is p-value = .06 > SL, repeat step 4,5 and go to step 3
X_optimal = X[:,[0,3]]
#Step 5 - fit the model again
regressior_OLS = sm.OLS(endog = y,exog=X_optimal).fit()
#Step 3
regressior_OLS.summary()
'''
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.947
Model: OLS Adj. R-squared: 0.945
Method: Least Squares F-statistic: 849.8
Date: Sun, 10 Feb 2019 Prob (F-statistic): 3.50e-32
Time: 21:34:35 Log-Likelihood: -527.44
No. Observations: 50 AIC: 1059.
Df Residuals: 48 BIC: 1063.
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 4.903e+04 2537.897 19.320 0.000 4.39e+04 5.41e+04
x1 0.8543 0.029 29.151 0.000 0.795 0.913
==============================================================================
Omnibus: 13.727 Durbin-Watson: 1.116
Prob(Omnibus): 0.001 Jarque-Bera (JB): 18.536
Skew: -0.911 Prob(JB): 9.44e-05
Kurtosis: 5.361 Cond. No. 1.65e+05
==============================================================================
'''
#So the R&D value is most important predicotr/independent
print("New Optimal Input")
print(X_optimal)
print("Creating MLR using the new optimal set")
#divide X,Y into test and training set
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X_optimal,y,test_size=1/5,random_state=0)
#fitting the data into MLR
from sklearn.linear_model import LinearRegression
startup_mlr = LinearRegression()
startup_mlr.fit(X_train,y_train)
#model created, lets test the model on test data
y_pred_test = startup_mlr.predict(X_test)
utl.print_actual_predicted(y_test,y_pred_test,True)
#model created, lets test the model on training data
y_pred_train = startup_mlr.predict(X_train)
utl.print_actual_predicted(y_train,y_pred_train,True) |
# File: madlib.py
# Description: simple input/print program
# prompts user for input
# outputs a madlib story
#
#
print('The following will print a story.')
name = input('What is your name? ')
hobby = input('What is your favorite hobby? ')
color = input('What is your favorite color? ')
location = input('Where would you like to go on vacation? ')
adjective = input('Type in an adjective: ')
adverb = input('Type in an adverb: ')
sound = input('Type in an exclamation: ')
feeling = input('Type in a feeling: ')
print('\n' * 5)
print('The famous story of ' + name + ' in ' + location + '.' )
print('Once upon a time, in ' + location )
print('a character named ' + name + ' travelled to ' + location)
print(name + ' noticed a ' + color + ' boat ')
print('sitting on the ground, and '+ adverb + ' climbed aboard.' )
print('Feeling ' + feeling + ', ' + name + ' screamed ' + sound + '!!!!')
print('and began to ' + hobby)
print('\n to be continued...\n')
|
# File: dateAndTimes.py
# Description: Excercises to learn date and time format
#
# The import statement gives us access to
# the functionality of the datetime class
# - import datetime
# today() is a function that returns today's date:
# - today()
# Example: print(datetime.date.today())
# Tip: Also learned pyCharm 'power save mode' disables
# the context sensitive help!
# If disabled see: File -> PowerSaveMode
# Tip: (un)comment blocks of code in Pycharm: (select) %/
# Formatting Dates:
# References:
# %b is the month
# %B is the full month name
# %y is the two digit year
# %a is the abbreviated day of the week
# %A is the day of the week
# For a full list visit strftime.org
# Exercise:
# print the date in the following format:
# "Please attend our event Sunday, July 20 in the year 1997"
import datetime
# currentDate = datetime.date.today()
# print('Today\'s date is: ', currentDate )
# print('Day: ', currentDate.day)
# print('Year: ', currentDate.year)
# print('Month: ', currentDate.month)
#
# print('This is a different format of the date.')
# print(currentDate.strftime('%b %d, %Y'))
#
# # Format Exercise: Time: 3:39:26 / 11:11:04
# print(currentDate.strftime
# ('Please attend our event %A, %B %d in the year %Y. '))
currentDate = datetime.datetime.today().date()
birthday = input('Please enter a birthday. (mo/dd/yyyy)')
birthdate = datetime.datetime.strptime(birthday, '%m/%d/%Y').date()
print(birthday)
days = abs(birthdate - currentDate)
print(days.days, ' days exist between: Today and the birthday.')
|
from tkinter import *
import os
creds = 'tempfile.temp' # This just sets the variable creds to 'tempfile.temp'
def Signup(): # This is the signup definition,
global pwordE # These globals just make the variables global to the entire script, meaning any definition can use them
global nameE
global roots
roots = Tk() # This creates the window, just a blank one.
roots.title('Signup') # This renames the title of said window to 'signup'
intruction = Label(roots, text='Please Enter new Credidentials\n') # This puts a label, so just a piece of text saying 'please enter blah'
intruction.grid(row=0, column=0, sticky=E) # This just puts it in the window, on row 0, col 0. If you want to learn more look up a tkinter tutorial :)
nameL = Label(roots, text='New Username: ') # This just does the same as above, instead with the text new username.
pwordL = Label(roots, text='New Password: ') # ^^
nameL.grid(row=1, column=0, sticky=W) # Same thing as the instruction var just on different rows. :) Tkinter is like that.
pwordL.grid(row=2, column=0, sticky=W) # ^^
nameE = Entry(roots) # This now puts a text box waiting for input.
pwordE = Entry(roots, show='*') # Same as above, yet 'show="*"' What this does is replace the text with *, like a password box :D
nameE.grid(row=1, column=1) # You know what this does now :D
pwordE.grid(row=2, column=1) # ^^
signupButton = Button(roots, text='Signup', command=FSSignup) # This creates the button with the text 'signup', when you click it, the command 'fssignup' will run. which is the def
signupButton.grid(columnspan=2, sticky=W)
roots.mainloop() # This just makes the window keep open, we will destroy it soon
def FSSignup():
with open(creds, 'w') as f: # Creates a document using the variable we made at the top.
f.write(nameE.get()) # nameE is the variable we were storing the input to. Tkinter makes us use .get() to get the actual string.
f.write('\n') # Splits the line so both variables are on different lines.
f.write(pwordE.get()) # Same as nameE just with pword var
f.close() # Closes the file
roots.destroy() # This will destroy the signup window. :)
Login() # This will move us onto the login definition :D
def Login():
global nameEL
global pwordEL # More globals :D
global root
root = Tk() # This now makes a new window.
w = 500
h = 300
# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
# set the dimensions of the screen
# and where it is placed
root.geometry('%dx%d+%d+%d' % (500, 300, x, y))
root.title('User Login') # This makes the window title 'login'
loginframe = Frame(root,height=w,width=h)
loginframe.pack()
loginframe.grid(padx=20, pady=20)
intruction = Label(loginframe, text='Please Login\n') # More labels to tell us what they do
intruction.grid(sticky=E) # Blahdy Blah
name = Label(loginframe, text='Username : ') # More labels
password = Label(loginframe, text='Password : ') # ^
name.grid(row=1, column=1,columnspan=1, padx=20, pady=20)
password.grid(row=2, column=1,columnspan=1, padx=20, pady=20)
namevalue = Entry(loginframe) # The entry input
passwordvalue = Entry(loginframe, show='*')
namevalue.grid(row=1, column=2, columnspan=3, padx=10, pady=20)
passwordvalue.grid(row=2, column=2, columnspan=3, padx=10, pady=20)
loginB = Button(loginframe, text='Login', command=lambda:CheckLogin(namevalue.get(),passwordvalue.get())) # This makes the login button, which will go to the CheckLogin def.
loginB.grid(column=4)
loginframe.mainloop()
def CheckLogin():
#directly bypass to main window
'''with open(creds) as f:
data = f.readlines() # This takes the entire document we put the info into and puts it into the data variable
uname = data[0].rstrip() # Data[0], 0 is the first line, 1 is the second and so on.
pword = data[1].rstrip() # Using .rstrip() will remove the \n (new line) word from before when we input it
if nameEL.get() == uname and pwordEL.get() == pword: # Checks to see if you entered the correct data.
r = Tk() # Opens new window
r.title(':D')
r.geometry('150x50') # Makes the window a certain size
rlbl = Label(r, text='\n[+] Logged In') # "logged in" label
rlbl.pack() # Pack is like .grid(), just different
r.mainloop()
else:
r = Tk()
r.title('D:')
r.geometry('150x50')
rlbl = Label(r, text='\n[!] Invalid Login')
rlbl.pack()
r.mainloop()'''
def DelUser():
os.remove(creds) # Removes the file
rootA.destroy() # Destroys the login window
Signup() # And goes back to the start!
Login()
'''if os.path.isfile(creds):
Login()
else: # This if else statement checks to see if the file exists. If it does it will go to Login, if not it will go to Signup :)
Signup()'''
|
import string
table = []
def encode(initString):
res = [ ' ' if i==' ' else chr(( (ord(i)-ord('A'))*k)%n+ord('A')) for i in initString ]
print("加密:" + (''.join(res)) )
def decode(initString):
value_list = [ chr(( (ord(i)-ord('A'))*k)%n+ord('A')) for i in string.ascii_uppercase ]
key_list = [ i for i in string.ascii_uppercase]
dict_str = {}
print(value_list)
print(key_list)
for i in range(len(value_list)):
dict_str[value_list[i]] = key_list[i]
res = ""
for i in initString:
if i==' ':
res+=' '
else :
res+=dict_str[i]
print("解密:"+res)
k,n = 2,26
choice = input("加密:1 解密:2 >>> :")
initString = input("原文/密文:")
k = int(input("偏移位数:"))
k = k%n
if choice == '1':
encode(initString)
elif choice =='2':
decode(initString)
else :
print("选项有误")
|
import random
COLORS = ['red', 'green', 'blue', 'white', 'brown', 'black', 'pink', 'purple', 'lightgreen', 'lightblue']
def create_impostors(players_list, impostors_amount_):
"""
:param players_list: list of dictionaries with participants
:param impostors_amount_: integer number for impostors count
:return: changed players list with impostors
"""
# выбираем случайного участника, если всего 1 предатель
if impostors_amount_ == 1:
players_list[random.randint(0, len(players_list) - 1)]['is_impostor'] = True
# выбираем несколько случайных участников, если предателей больше одного
else:
impostors_indexes = []
while len(impostors_indexes) < impostors_amount_:
index_ = random.randint(0, len(players_list) - 1)
if index_ not in impostors_indexes:
impostors_indexes.append(index_)
for impostors_index in impostors_indexes:
players_list[impostors_index]['is_impostor'] = True
return players_list
if __name__ == '__main__':
# вводим количество предателей
print('Сколько будет предателей? от 1 до 3')
impostors_amount = int(input())
# минимальное число участников
min_players_amount = 4
if impostors_amount == 2:
min_players_amount = 7
elif impostors_amount == 3:
min_players_amount = 9
print(f'Сколько всего будет игроков? от {min_players_amount} до 10:')
players_amount = int(input())
while players_amount < min_players_amount or players_amount > 10:
print(f'Вы ввели неверное количество игроков, введите еще раз. от {min_players_amount} до 10:')
players_amount = int(input())
# заполняем список участников
players = []
for i in range(players_amount):
name = f'player_{i + 1}'
player = {
'id': i + 1,
'name': name,
'color': COLORS[i],
'is_impostor': False
}
players.append(player)
# начинаем игру (создаем предателей)
players = create_impostors(players, impostors_amount)
if impostors_amount == 1:
print('There is 1 impostor among us')
else:
print(f'There is {impostors_amount} impostor among us')
# выводим усписок участников
for player in players:
print(f'{player["id"]}. {player["name"]} - {player["color"]}')
# играем
while 0 < impostors_amount < len(players) - impostors_amount:
print('**********\nОставшиеся участники\n************')
for player in players:
print(f'{player["id"]}. {player["name"]} - {player["color"]}')
print('Как вы думаете, кто предатель?')
potential_impostor_id = int(input())
# выбор номера участника
player_to_kill = None
# находим индекс участника
for index, player in enumerate(players):
if player['id'] == potential_impostor_id:
player_to_kill = index
break
# убираем игрока из списка
if player_to_kill is not None:
if players[player_to_kill]['is_impostor']:
print(f'{players[player_to_kill]["name"]} оказался предателем')
impostors_amount = impostors_amount - 1
else:
print(f'{players[player_to_kill]["name"]} не был предателем')
del players[player_to_kill]
print(f'Осталось предателей: {impostors_amount} \n')
# выводим результаты игры
if impostors_amount == 0:
print('*********\nПОБЕДА!!!\n**********')
else:
print('*********\nПоражение\n**********')
for player in players:
print(f'{player["id"]}. {player["name"]} - {player["color"]} - {"предатель" if player["is_impostor"] else "не предатель"}')
|
#The program adapts depending on the language to/from translate. It is not case sensitive.
def hello():
print('WELCOME to JAUMEAN OFFICIAL TRANSLATOR.')
options = {"TOJAU","TOLAN"}
print('Typing TOJAU will translate your text to Jaumean, TOLAN will translate Jaumean text to your language.')
user_language = input('Please type TOJAU or TOLAN to choose in which direction you want to translate:')
user_language = user_language.upper()
if user_language not in options:
print("\n"'Hey ~€€#~¬#~¬! Choose TOJAU to translate your language to Jaumean/n Choose TOLAN to translate from Jaumean to your language'"\n")
user_language = input("\n"'Please type TOJAU or TOLAN to choose in which direction you want to translate,'"\n")
return user_language
|
n=int(input())
r=0
while n>0 :
r=n%10
r=(r*10)+r
n=n//10
print("reverse",r)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# problem001.py
#
# Copyright 2013 Stefan Thesing <software@webdings.de>
#
# License: WTFPL
#
# HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Problem 1:
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
import sys
def using_for_loop(limit):
summe=0
for i in range(1, limit):
if not i%3 or not i%5:
summe += i
return summe
def using_recursion(limit, i=1, summe=0):
if not i%3 or not i%5:
summe += i
if i<limit-1:
return using_recursion(limit, i+1, summe)
else:
return summe
def using_generator(limit):
for i in range(1,limit):
if not i%3 or not i%5:
yield i
def using_ranges(limit):
return sum(set(range(0,limit,3) + range(0,limit,5)))
def main():
limit = 1000
print "This can be done in serveral ways in Python. Some examples:"
print "Using a for loop:"
print using_for_loop(limit)
print "Using recursion:"
# The standard limit of 1000 exceeds the maximum recursion depth. So let's
# set it to the needed amount, and reset it afterwards.
# Remember the standard setting
recursion_limit = sys.getrecursionlimit()
# Set to limit+1
sys.setrecursionlimit(limit+1)
# Do it:
print using_recursion(limit)
# Set back to standard setting
sys.setrecursionlimit(recursion_limit)
print "Using a generator:"
print sum(using_generator(limit))
print "Using ranges:"
print using_ranges(limit)
if __name__ == '__main__':
main()
|
n = int(input())
numbers1 = []
x = input()
numbers = x.split()
for i in numbers:
numbers1.append(int(i))
print(min(numbers1))
|
def check_fermat(a, b, c, n):
if a**n + b**n == c**n:
print ('Holy smokes, Fermat was wrong!')
else:
print ('No, that doesn\'t work.')
def get_input():
a = input('A: ')
a = int(a)
b = input('B: ')
b = int(b)
c = input('C: ')
c = int(c)
n = input('N: ')
n = int(n)
if n > 2:
check_fermat(a, b, c, n)
else:
print ('n must be greater than 2')
def is_triangle(a, b, c):
if a + b >= c:
print ('Yes')
else:
print ('No')
def check_triangle():
a = int(input('First stick: '))
b = int(input('Second stick: '))
c = int(input('Long stick: '))
is_triangle(a, b, c)
#get_input()
check_triangle()
def bitleft(x, b):
while b != 0:
x = x * 2
b -= 1
return x
def bitright(x, b):
while b != 0:
x = x // 2
b -= 1
return x |
import collections
neg_dict = collections.defaultdict(lambda : 0)
neg_dict = {"not":1, "no":1, "n't":1, "neither":1, "nor":1, "nothing":1, "never":1, "none":1, "lack":1, "lacked":1, "lacking":1, "lacks":1, "missing":1, "without":1, "absence":1, "devoid":1, "didn't":1}
def is_negator(word):
flag = word in neg_dict
if(flag == True):
return neg_dict[word]
else:
return 0
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 09:21:52 2020
@author: karlv
"""
# Matt Parker Train Problem
"""
Solution of the form
Distance d_0, max fuel f_0, trains n
d(n) = f_0(1+1/3+1/5+1/7+1/9+...+1/(2n-1))
where d(n) < d_0
fuel_used = f_0*n
"""
# Solving above equation
def fuel_needed_eq(d: float, f_0: float):
d_n = 0
n = 0
while d_n < d:
n+=1
d_n += f_0/(2*n-1)
n -= (d_n-d)*(2*n-1)/f_0
print("Fuel used: " + str(n*f_0))
return n*f_0
# Solution using trains
def fuel_needed(d: float, f_0:float):
if d <= f_0:
return d
distance_needed = d-f_0
trains_used = 1
fuel_used = f_0
while distance_needed > 0:
distance_gone, new_fuel_used = previous_train(distance_needed, trains_used, f_0)
trains_used += 1
distance_needed -= distance_gone
fuel_used += new_fuel_used
print("Fuel used: " + str(fuel_used))
return fuel_used
def previous_train(d_unfueled, trains_used, f_0):
fuel_per_d = 2*trains_used+1
distance = min(d_unfueled, f_0/fuel_per_d)
return distance, distance*fuel_per_d
|
p,q=map(int,input().split())
r,s=map(int,input().split())
t,u=map(int,input().split())
if p==q and r==s and t==u:
print("yes")
elif p==r==t or q==s==u:
print("yes")
else:
print("no")
|
#!/usr/bin/env python
import pyazuki
import sys
def vec2list(vec):
l = []
for i in range(vec.size()):
l.append(vec[i])
return l
def demo():
print "======================================"
rp = pyazuki.ParseRegexp("(a+)b")
print "The regexp is:\n"
pyazuki.PrintRegexp(rp)
print "======================================"
program = pyazuki.CompileRegexp(rp)
print "The program is:\n"
pyazuki.PrintProgram(program)
machine = pyazuki.CreateMachine("(a+)b")
s = "aabcdabe"
print "======================================"
print "An example of regex search."
print "Find \"(a+)b\" in \"%s\".\n" %(s)
result = pyazuki.MatchResult()
while pyazuki.RegexSearch(machine, s, result, True):
print "begin = %d, end = %d, capture = " %(result.begin, result.end),
print vec2list(result.capture)
print "======================================"
print "An example of regex replace."
print "Replace \"(a+)b\" with \"$0f\" in \"%s\".\n" %(s)
print pyazuki.RegexReplace(machine, s, "$0f", True)
if __name__ == "__main__":
demo()
|
import pyttsx3 #
import datetime
import speech_recognition as sr
'''
sapi5 is to use windows inbuilt voice.
Microsoft Speech API (SAPI5) is the technology for voice recognition and synthesis provided by Microsoft
'''
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id) # Two type of voices we are using first voice(male).
def speak(audio):
engine.say(audio)
engine.runAndWait() # It will wait till the sentence get finish.
def wishMe():
hour = int(datetime.datetime.now().hour)
print(hour)
if hour >= 0 and hour < 12 :
speak("Good Morning!")
elif hour >= 12 and hour < 18:
speak("Good Afternoon!")
else:
speak("Good Evening!")
speak("I am your personal assistant! How may I help you.")
def takeCommand():
''' It takes microphone input from user and returns string output. '''
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language = 'en-in')
print(f"User said: {query}\n ")
except Exception as e:
print(e)
print("Say that again please...")
return "None"
return query
if __name__ == '__main__':
wishMe()
takeCommand()
while True:
query = takeCommand().lower()
## Logic for executing task
if "wikipedia" in query:
speak('searching wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences = 2)
speak("According to wikipedia")
speak(results)
|
x={}
for z in range(0,3):
name = raw_input("insert name ")
age = raw_input("insert age ")
year = raw_input("insert year ")
x[name] = [age, year]
print x
|
# coding:iso-8859-9 Trke
class Vanti:
def __init__ (self, takm, say):
self.takm = takm
self.say = say
def __str__ (self):
adlar = ['Olan', 'Kz', 'Papaz', 'As']
if self.say <= 10: return '{} {}'.format (self.takm, self.say)
else: return '{} {}'.format (self.takm, adlar[self.say - 11])
from random import shuffle
class Vanti_grubu:
def __init__ (self, kartlar = []): self.kartlar = kartlar
def sonrakiKart (self): return self.kartlar.pop (0)
def kartKaldM (self): return len (self.kartlar) > 0
def ebat (self): return len (self.kartlar)
def kartr (self): shuffle (self.kartlar)
class Standart_deste (Vanti_grubu):
def __init__ (self):
self.kartlar = []
for takm in ['Kupa', 'Karo', 'Maa', 'Sinek']:
for say in range (2, 15): self.kartlar.append (Vanti (takm, say))
"""
class Pinochle_deste (Vanti_grubu):
def __init__ (self):
self.kartlar = []
for takm in ['Kupa', 'Karo', 'Maa', 'Sinek']:
for say in range (9, 15): self.kartlar.append (Vanti (takm, say))
"""
deste = Standart_deste()
print ("Dizili Deste:\n","-"*20, sep="")
for i in range (len (deste.kartlar) ): print ((i+1), ".kart: ", deste.kartlar[i], sep="")
deste.kartr()
print ("\nKarl Deste:\n","-"*20, sep="")
for i in range (len (deste.kartlar) ): print ((i+1), ".kart: ", deste.kartlar[i], sep="")
yeniKart = deste.sonrakiKart()
print()
print ('==> ', yeniKart, sep="")
tahmin = input ("Bir sonraki ekecein kart yksek (y) mi, dk (d) m?: ").lower()
ardkTutturma = 0
while (tahmin == 'y' or tahmin == 'd'):
if not deste.kartKaldM():
deste = Standart_deste()
deste.shuffle()
eskiKart = yeniKart
yeniKart = deste.sonrakiKart()
print ('==> ', yeniKart, sep="")
if (tahmin == 'y' and yeniKart.say > eskiKart.say or\
tahmin == 'd' and yeniKart.say < eskiKart.say):
ardkTutturma = ardkTutturma + 1
print ("Bravo! Arka arkaya ", ardkTutturma, ".isabetli tahminin!", sep="")
elif (tahmin == 'y' and yeniKart.say < eskiKart.say or\
tahmin == 'd' and yeniKart.say > eskiKart.say):
ardkTutturma = 0
print ('YANLI, sfrlandn!')
else: print ('Eitlik var.')
tahmin = input ("\nBir sonraki ekecein kart yksek (y) mi, dk (d) m?: ").lower()
|
# coding:iso-8859-9 Trke
# Python 3 - Multithreaded Programming
# Yeni yntemle sicim yaratma: Thread altsnf, override __init__ ve run metodlar,
# sicim tip nesneleri yaratma, start ile run' koturma, icabnda join ile sicimlerin
# almas tamamlanmadan alttaki kodlamaya gememenin salanmas ve
# lock ile bir sicim tamamlanmadan (senkronizasyon) dierine geilmemesi
import threading
import time
class sicimim (threading.Thread):
def __init__ (self, sicimNo, sicimAd, tehir): # Kurucu metod...
threading.Thread.__init__ (self)
self.sicimNo = sicimNo
self.sicimAd = sicimAd
self.tehir = tehir
def run (self):
print ("Balatlyor: " + self.sicimAd)
# Sicim kilidi kapatlp, sicimin tamamlanma btnl salanyor...
sicimKilidi.acquire()
zamanGster (self.sicimAd, self.tehir, 5)
print ("Sonlandrlyor: " + self.sicimAd)
# Kilidi ap birsonraki sicime gei veriliyor...
sicimKilidi.release()
def zamanGster (ipAd, beklet, tekrarla):
while tekrarla:
time.sleep (beklet)
print ("%s: Saya(%d) Zaman: %s" % (ipAd, tekrarla, time.ctime (time.time())))
tekrarla -= 1
sicimKilidi = threading.Lock()
sicimler = []
# Yeni sicimlerimizi yaratalm...
sicim1 = sicimim (1001, "Sicim-1", 2)
sicim2 = sicimim (250, "Sicim-2", 3)
sicim3 = sicimim (1957, "Sicim-3", 1)
# Sicimleri run iin balatalm...
sicim3.start()
sicim1.start()
sicim2.start()
# Sicim listesi yapp birlikte join (alt koda gei bekletmesi) edelim...
sicimler.append (sicim1)
sicimler.append (sicim3)
sicimler.append (sicim2)
for ip in sicimler: ip.join()
print ("\nSicimler tamamland; alt kodlamalara geilebilir...")
|
# coding:iso-8859-9 Trke
# p_12106.py: Fibonaki saylar, kareleri ve endeksleri rnei.
bellek = {0:0, 1:1}
def fibonaki (n):
if not n in bellek: bellek [n] = fibonaki (n-1) + fibonaki (n-2)
return bellek [n]
def endeksiBul (*x):
if len (x) == 1: return endeksiBul (x[0], 0)
else:
n = fibonaki (x[1])
m = x[0]
if n > m: return -1
elif n == m: return x[1]
else: return endeksiBul (m, x[1]+1)
print ("20'lik fibonaki serisi listesi:", [fibonaki (i) for i in range (20)])
print()
say = 144
konum = endeksiBul (say)
if konum == -1: print (konum, "==> ", say, " says 20'lik fibonakide NAMEVCUT!", sep="")
else: print (fibonaki (konum) == say, "==> ", say, " says fibonaki ", konum, ".endekste MEVCUT.", sep="")
#--------------------------------------------------------------------------------------------------------
print ("\nfibA endeks | fibA | fibB | Kare Tpl | fibA'daki Konumu")
print ("=======================================================")
for i in range (20):
karesi = fibonaki (i)**2 + fibonaki (i+1)**2
print (" %10d | %4d | %4d | %8d | %2d" % (i, fibonaki (i), fibonaki (i+1), karesi, endeksiBul (karesi)) )
"""kt:
>python p_12106.py
20'lik fibonaki serisi listesi: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
233, 377, 610, 987, 1597, 2584, 4181]
True==> 144 says fibonaki 12.endekste MEVCUT.
fibA endeks | fibA | fibB | Kare Tpl | fibA'daki Konumu
=======================================================
0 | 0 | 1 | 1 | 1
1 | 1 | 1 | 2 | 3
2 | 1 | 2 | 5 | 5
3 | 2 | 3 | 13 | 7
4 | 3 | 5 | 34 | 9
5 | 5 | 8 | 89 | 11
6 | 8 | 13 | 233 | 13
7 | 13 | 21 | 610 | 15
8 | 21 | 34 | 1597 | 17
9 | 34 | 55 | 4181 | 19
10 | 55 | 89 | 10946 | 21
11 | 89 | 144 | 28657 | 23
12 | 144 | 233 | 75025 | 25
13 | 233 | 377 | 196418 | 27
14 | 377 | 610 | 514229 | 29
15 | 610 | 987 | 1346269 | 31
16 | 987 | 1597 | 3524578 | 33
17 | 1597 | 2584 | 9227465 | 35
18 | 2584 | 4181 | 24157817 | 37
19 | 4181 | 6765 | 63245986 | 39
""" |
# coding:iso-8859-9 Trke
def fonk1():
for i in range (10): print (i, end=" ")
print()
def fonk2():
i=100
fonk1()
print (i)
fonk1()
print()
fonk2()
print()
def sfrla():
global kalan_zaman
kalan_zaman = 0
def zamanYaz():
print (kalan_zaman, "saniye")
kalan_zaman = 30
zamanYaz()
sfrla()
zamanYaz()
print()
def f1 (x):
x = x + 1
print (x)
def f2 (L):
L = L + [4]
print (L)
a = 3
M = [1,2,3]
f1 (a)
print (a) # a deimedi...
f2 (M)
print (M) # M de deimedi!..
|
# coding:iso-8859-9 Trke
# p_13202.py: C, F, ve K dereceleri normal def ve anonim lambda ile map haritalamayala evirme rnei.
def fahrenhayt (D): return ((float (9) / 5) * D + 32)
def kelvin (D): return ((D + 459.4) * float (5) / 9)
def selsiys (D): return (D - 273)
dereceler = (-273, 0, 32, 100, 500)
F = list (map (fahrenhayt, dereceler) ) # dereceler listesini tek tek fahrenhayt'a evirir ve listeler...
K = list (map (kelvin, F) )
S = list (map (selsiys, K) )
print ("(-273, 0, 32, 100, 500) derecelerin normal fonksiyonla harita'lanmas:", "\n", "-"*70, sep="")
print ("S'ler fahrenhayt F'ye:", F )
print ("F'ler kelvin K'ye:", K )
print ("K'ler tekrar selsiys S'ye:", S )
#--------------------------------------------------------------------------------------------------------
F = list (map (lambda x: (float (9) / 5) * x + 32, dereceler)) # Dorudan lambdal map listesi elde edilmesi...
K = list (map (lambda x: (x + 459.4) * float (5) / 9, F))
S = list (map (lambda x: x - 273, K))
print ("\n(-273, 0, 32, 100, 500) derecelerin lambda anonim fonksiyonla harita'lanmas:", "\n", "-"*77, sep="")
print ("S'ler fahrenhayt F'ye:", F )
print ("F'ler kelvin K'ye:", K )
print ("K'ler tekrar selsiys S'ye:", S )
"""kt:
>python p_13202.py
(-273, 0, 32, 100, 500) derecelerin normal fonksiyonla harita'lanmas:
----------------------------------------------------------------------
S'ler fahrenhayt F'ye: [-459.40000000000003, 32.0, 89.6, 212.0, 932.0]
F'ler kelvin K'ye: [-3.157967714489334e-14, 273.0, 305.0, 373.0, 773.0]
K'ler tekrar selsiys S'ye: [-273.00000000000006, 0.0, 32.0, 100.0, 500.0]
(-273, 0, 32, 100, 500) derecelerin lambda anonim fonksiyonla harita'lanmas:
-----------------------------------------------------------------------------
S'ler fahrenhayt F'ye: [-459.40000000000003, 32.0, 89.6, 212.0, 932.0]
F'ler kelvin K'ye: [-3.157967714489334e-14, 273.0, 305.0, 373.0, 773.0]
K'ler tekrar selsiys S'ye: [-273.00000000000006, 0.0, 32.0, 100.0, 500.0]
""" |
# coding:iso-8859-9 Trke
# Python3 - Date & Time
import calendar;
import time;
yl = int (input ("Yllk takvim yln girin: "))
print (calendar.calendar (yl, w = 2, l = 1, c = 6))
input ("Devam iin [Ent]:")
calendar.setfirstweekday (5)
print (calendar.calendar (yl, w = 2, l = 1, c = 6))
print (yl, "artk yl m?", calendar.isleap (yl))
print ("1970->2018 aras artk yllarn says:", calendar.leapdays (1970, 2018) )
calendar.setfirstweekday (0)
ay = int (input ("Takvim ayn girin [1-12]: "))
print (calendar.month (yl, ay, w = 2, l = 1) )
print ("Ayn Haftalk Listeleri:\n", calendar.monthcalendar (yl, ay) )
print ("\nAyn ilk gn endeksi ve ayn toplam gn says:", calendar.monthrange (yl, ay) )
print ("\nBugn (pazartesinden itibaren) haftann kanc gn?",
calendar.weekday (time.localtime().tm_year, time.localtime().tm_mon, time.localtime().tm_wday) ) |
# coding:iso-8859-9 Trke
# p_30409c.py: Kolon ve stun matrislerinin saysal arpmda birlikte yaylmalar rnei.
import numpy as np
A = np.array ([10, 20, 30])
A1 = A[:, np.newaxis]
A2 = np.array ([[10, 20, 30], ] * 3).transpose()
B = np.array ([1, 2, 3])
B1 = np.array ([[1, 2, 3],]*3)
# A[:, np.newaxis] * B = A2 * B1 gibi oldu...
Z1 = A[:, np.newaxis] * B
Z2 = A2 * B1
print ("A 1x3 dizisi: ", A, "\n\nA[:,np.newaxis] 3x1 kolon matrisi:\n", A1, "\n\nA2=np.array([[10,20,30],]*3).transpose() 3x3 matrisi:\n", A2, sep="")
print ("\nB 1x3 dizisi: ", B, "\n\nB1=np.array([[1,2,3],]*3) 3x3 matrisi:\n", B1, sep="")
print ("\nA[:,np.newaxis]*B otomatik yaylm uyumlu bire-bir arpml 3x3 matrisi:\n", (A[:, np.newaxis] * B), sep="")
print ("\n(A[:,np.newaxis]*B) ile (A2*B1=np.array([[10, 20, 30],]*3).transpose() * np.array([[1,2,3],]*3)) eit mi?", np.array_equal (Z1, Z2) )
"""kt:
>python p_30409c.py
A 1x3 dizisi: [10 20 30]
A[:,np.newaxis] 3x1 kolon matrisi:
[[10]
[20]
[30]]
A2=np.array([[10,20,30],]*3).transpose() 3x3 matrisi:
[[10 10 10]
[20 20 20]
[30 30 30]]
B 1x3 dizisi: [1 2 3]
B1=np.array([[1,2,3],]*3) 3x3 matrisi:
[[1 2 3]
[1 2 3]
[1 2 3]]
A[:,np.newaxis]*B otomatik yaylm uyumlu bire-bir arpml 3x3 matrisi:
[[10 20 30]
[20 40 60]
[30 60 90]]
(A[:,np.newaxis]*B) ile (A2*B1=np.array([[10, 20, 30],]*3).transpose() * np.array([[1,2,3],]*3)) eit mi? True
""" |
# coding:iso-8859-9 Trke
# p_30403.py: Numpy.array iki matrisin toplamas, sayl ve ynel arpmlar rnei.
import numpy as np
A = np.array ([ [11, 12, 13], [21, 22, 23], [31, 32, 33] ])
B = np.ones ((3,3), int) # varsayl: float
print ("A (3,3) matrisi:\n", A, sep="")
print ("\nB (3,3) birler matrisi:\n", B, sep="")
print ("\n'A+(B+1)' toplam matrisi:\n", (A + (B + 1)), sep="")
print ("\n'A*(B+1)' skalar/sayl arpm matrisi:\n", (A * (B + 1)), sep="")
print ("\n'np.dot(A,B)' vektrel/ynel arpm matrisi:\n", np.dot (A, B), sep="")
print ("\n'np.dot(A,(B+1))' vektrel/ynel arpm matrisi:\n", np.dot (A, (B + 1)), sep="")
"""kt:
>python p_30403.py
A (3,3) matrisi:
[[11 12 13]
[21 22 23]
[31 32 33]]
B (3,3) birler matrisi:
[[1 1 1]
[1 1 1]
[1 1 1]]
'A+(B+1)' toplam matrisi:
[[13 14 15]
[23 24 25]
[33 34 35]]
'A*(B+1)' skalar/sayl arpm matrisi:
[[22 24 26]
[42 44 46]
[62 64 66]]
'np.dot(A,B)' vektrel/ynel arpm matrisi:
[[36 36 36]
[66 66 66]
[96 96 96]]
'np.dot(A,(B+1))' vektrel/ynel arpm matrisi:
[[ 72 72 72]
[132 132 132]
[192 192 192]]
""" |
# coding:iso-8859-9 Trke
# Python 3 - Multithreaded Programming
# Yeni yntemle sicim yaratma: Thread altsnf, override __init__ ve run metodlar,
# sicim tip nesneleri yaratma, start ile run' koturma, icabnda join ile sicimlerin
# almas tamamlanmadan alttaki kodlamaya gememenin salanmas,
# lock ile bir sicim tamamlanmadan (senkronizasyon) dierine geilmemesi,
# liste ile oklu sicimlerde dngyle ilem kolayl salanmas
import threading
import time
#import queue ==> Sorunlu, sadece son sicimi iliyor, tm sicimleri deil...
class sicimim (threading.Thread):
def __init__ (self, sicimNo, sicimAd):
threading.Thread.__init__ (self)
self.sicimNo = sicimNo
self.sicimAd = sicimAd
def run (self):
print ("Balyor: " + self.sicimAd)
kilit.acquire()
verileme (self.sicimAd)
print ("Sonlanyor: " + self.sicimAd)
kilit.release()
def verileme (ipAd):
for i in range (8):
print ("%s: (%s)inci kez ileniyor [Zaman: %s]" % (ipAd, ilemAd[i], time.ctime (time.time()) ))
time.sleep (2)
sicimAdlarListesi = ["Sicim-1", "Sicim-2", "Sicim-3", "Sicim-4", "Sicim-5"]
ilemAd= ["Bir", "ki", "", "Drt", "Be", "Alt", "Yedi", "Sekiz"]
sicimler = []
sicimNo = 1
kilit = threading.Lock()
# Sicimleri yaratp balatalm...
for ad in sicimAdlarListesi:
sicim = sicimim (sicimNo, ad)
sicim.start()
sicimler.append (sicim)
sicimNo += 1
# Tm sicimler tamamlannca alt kodlamaya gesin...
for ip in sicimler: ip.join()
print ("Sicimler tamamland; program sonlanyor...")
|
# coding:iso-8859-9 Trke
from random import *
from math import *
a = eval (input ("Herhangi bir '-/+' a girin: "))
radyan = a * pi / 180
print ("Sin(", a, ") = ", sin (radyan), sep="")
print ("Cos(", a, ") = ", cos (radyan), sep="")
print ("Tan(", a, ") = ", tan (radyan), sep="")
Y = abs (eval (input ("\nHerhangibir 4 haneli '+' yl girin: ")))
C = trunc (Y / 100)
m = (15 + C - (C/4) - (8*C+13)/25) % 30
n = (4 + C - C/4) % 7
a = Y % 4
b = Y % 7
c = Y % 19
d = (19*c + m) % 30
e = (2*a + 4*b + 6*d + n) % 7
if d == 29 and e == 6: print ("Paskalya tarihi: Nisan 19")
elif d == 28 and e == 6 and (m==2 or m==5 or m==10 or m==13 or m==16 or m==21 or m==24 or m==39): print ("Paskalya tarihi: Nisan 18")
elif (trunc(d)+trunc(e)) > 9: print ("Paskalya tarihi: Nisan", trunc (d+e-9))
else: print ("Paskalya tarihi: Mart", trunc (22+d+e))
artk = False
if Y//100 * 100 == Y and Y % 400 == 0: artk = True
elif Y//100 * 100 != Y and Y%4 == 0: artk = True
if artk: print (Y, "yl artk yldr, yani ubat 29 eker.")
else: print (Y, "yl artk yl deildir, yani ubat 28 eker.")
if Y > 1600:
artk = False
saya = 0
for i in range (1600, Y+1):
if i//100 * 100 == i and i % 400 == 0: artk = True
elif i//100 * 100 != i and i%4 == 0: artk = True
if artk: saya += 1; artk=False
print ("Ayrca 1600 ylndan bu yla kadar toplam:", saya, "adet artk yl vardr.")
kuru = abs (trunc (eval (input ("\n100 Kr veya alt tamsay bozukluk girin: "))))
if kuru > 100: kuru = 100
kalan = kuru
k1=k2=k3=k4=0
if kalan >= 50: k1 = kalan//50; kalan = kalan - k1*50
if kalan >= 25: k2 = kalan//25; kalan = kalan - k2*25
if kalan >= 10: k3 = kalan//10; kalan = kalan - k3*10
if kalan >= 5: k4 = kalan//5; kalan = kalan - k4*5
print (kuru, " kuru iinde ", k1, " adet 50 kuru ", k2, " adet 25 kuru ", k3, " adet 10 kuru ", k4, " adet 5 kuru ve ", kalan, " adet 1 kuru bozukluk vardr.")
satr = abs (trunc (eval (input ("\nMatrisin satr saysn girin: "))))
stun = abs (trunc (eval (input ("\nMatrisin stun saysn girin: "))))
print()
k=0
for i in range (satr):
for j in range (stun):
print (k, end=" ")
k += 1
if k > 9: k = 0
print()
|
# coding:iso-8859-9 Trke
from string import punctuation
dizge = "M.Nihat Yava; Yeilyurt-Malatya; 17.04.1957"
print ("Dizge:", dizge)
for k in punctuation: dizge = dizge.replace (k, " ")
dizge = dizge.replace (" ", " ")
liste = dizge.lower().split (" ")
print ("\nSplit'le liste:", liste)
print ("\nJoin'le tekrar liste'den araboluklu dizgeye:", " ".join (liste))
print ("\nJoin'le liste'den boluksuz dizgeye:", "".join (liste))
print ("\nJoin'le liste'den tireli dizgeye:", "-".join (liste))
print ("\nJoin'le liste'den ift yldzl dizgeye:", "**".join (liste))
print ("\nJoin'le liste'den virgl-boluklu dizgeye:", ", ".join (liste))
from random import shuffle
kelime = input ("\n10 adet anagram tretilecek kelimeyi girin: ").lower()
if len (kelime) == 0: kelime = "malatya"
liste = list (kelime)
for i in range (10):
shuffle (liste)
print (''.join (liste), end=" ")
|
# coding:iso-8859-9 Trke
""" Bu program biraz etrefillidir.
lk giri iin "ifreler.txt" dosyas oluturup iine de
ilk ifrenizi yerletirmelisiniz...
"""
class ifre_Yneticisi:
def __init__ (self):
self.L = []
def hesap_yarat (self, kod):
dosya = open ("ifreler.txt", "w")
print (kod, file=dosya)
def ifre_doruMu (self, kod):
self.L = [satr.strip() for satr in open ("ifreler.txt", "r")]
if kod == self.L[len (self.L)-1]: return True
print ("Aktel ifreniz yanl!")
return False
def oturum_a (self):
print ("\nOturumunuz ald:\
\nOturum formuna katlabilir,\
\nifrenizi deitirebilir,\
\nifrenizi unuttuysanz yeni hesap yaratabilir,\
\nMevcut nceki ifrelerinizi grebilirsiniz.")
input ("Ent:")
def ifreyi_deitir (self):
while True:
print ("\nifre deiiklii==>"); kod = ifre_gir()
mevcut = 0
for i in range (len (self.L)):
if kod == self.L[i]: mevcut = 1
if mevcut == 1: input ("Bu ifreniz eskiden kullanlm, yeniden deneyin [Ent]")
else: break
dosya = open ("ifreler.txt", "a")
print (kod, file=dosya)
return kod
def ifreleri_gr (self):
self.L = [satr.strip() for satr in open ("ifreler.txt", "r")]
print (self.L); input ("Ent:")
def ana_men():
men = "\n1. Yeni bir ifreli hesap yarat\
\n2. Mevcut ifreli oturumu a\
\n3. ifre deiiklii\
\n4. nceki ifreleri grme\
\n5. Son\
\n\n Seiminiz==> "
se = 0
while not (0 < se < 6):
try: se = abs (int (eval (input (men))))
except Exception: se = 0
return se
def ifre_gir():
while True:
= input ("\nifrenizi girin: ")
if len () < 5 or not [0].isalpha() or .isalpha():
print ("ifreniz enaz 5 karakter, ilki harf, enaz da 1 rakam iermeli")
else: return
ynetim = ifre_Yneticisi()
ifre = ifre_gir()
while ynetim.ifre_doruMu (ifre):
seenek = ana_men()
if seenek == 5:
print ("\nOturumu sonlandrdnz, grmek zere!")
break
if seenek == 1 and input ("\nnceki ifrelerin tamamen silinecek, emin misin ['e']: ").lower() == "e":
ynetim.hesap_yarat (ifre)
elif seenek == 2:
if ynetim.ifre_doruMu (ifre): ynetim.oturum_a()
elif seenek == 3:
if ynetim.ifre_doruMu (ifre): ifre = ynetim.ifreyi_deitir()
elif seenek == 4:
if ynetim.ifre_doruMu (ifre): ynetim.ifreleri_gr()
|
# coding:iso-8859-9 Trke
# p_13205.py: Fibonaki serisinin lambda fonksiyonla tek ve ift olarak ayrtrlmas rnei.
fibonaki = [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597]
tekSaylar = list (filter (lambda x: x % 2, fibonaki)) # x%2 kalan 1=tekse True, 0=iftse False retir...
iftSaylar = list (filter (lambda x: x % 2 == 0, fibonaki)) # Eitlik ift saylarda salandnda True retir...
# Veya: iftSaylar = list (filter (lambda x: x % 2 -1, fibonaki))
print ("Filitrelenen fibonaki ifli saylar listesi:", iftSaylar)
print ("Filitrelenen fibonaki tekli saylar listesi:", tekSaylar)
"""kt
>python p_13205.py
Filitrelenen fibonaki ifli saylar listesi: [0, 2, 8, 34, 144, 610]
Filitrelenen fibonaki tekli saylar listesi: [1, 1, 3, 5, 13, 21, 55, 89, 233,377, 987, 1597]
""" |
# coding:iso-8859-9 Trke
# p_30209.py: Dizi kopyalarndaki deiiklik python'da asln deitirmezken, numpy.array'de deitirir rnei.
import numpy as np
liste1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print ("Python liste1:", liste1)
liste2 = liste1[2:6]
liste2[0] = 22
liste2[1] = 23
print ("Python liste1 dilimlerindeki deiiklik orijinali DETRMEZ:", liste1)
dizi1 = np.array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print ("\nNumpy dizi1:", dizi1)
dizi2 = dizi1[2:6]
dizi2[0] = 22
dizi2[1] = 23
print ("Numpy dizi1 dilimlerindeki deiiklik orijinali de DETRR:", dizi1)
print ("Numpy dizi1 ve dizi2 ayn hafzay m kullanyor?", np.may_share_memory (dizi1, dizi2) )
A = np.arange (12)
print ("\nDizi A:", A)
B = A.reshape (3, 4)
print ("Dizi B=A.reshape(3,4):\n", B, sep="")
A[0] = 42
print ("A[0]=42 sonras dizi B:\n", B, sep="")
print ("Numpy dizi A ve dizi B ayn hafzay m kullanyor?", np.may_share_memory (A, B) )
"""kt:
>python p_30209.py
Python liste1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python liste1 dilimlerindeki deiiklik orijinali DETRMEZ: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Numpy dizi1: [0 1 2 3 4 5 6 7 8 9]
Numpy dizi1 dilimlerindeki deiiklik orijinali de DETRR: [ 0 1 22 23 4 5 6 7 8 9]
Numpy dizi1 ve dizi2 ayn hafzay m kullanyor? True
Dizi A: [ 0 1 2 3 4 5 6 7 8 9 10 11]
Dizi B=A.reshape(3,4):
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
A[0]=42 sonras dizi B:
[[42 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Numpy dizi A ve dizi B ayn hafzay m kullanyor? True
""" |
# coding:iso-8859-9 Trke
from random import randint
liste=[]
for i in range (randint (2,50)): liste.append (randint (0,10))
print ("Listemizdeki saya eleman says:", len (liste))
print ("Listemizdeki son elemann deeri:", liste[len (liste) -1])
print ("Listemizdeki elemanlar:", liste)
liste2 = liste[:]
liste2.sort()
print ("Sral listemizdeki elemanlar:", liste2)
liste2.reverse()
print ("Ters sral listemizdeki elemanlar:", liste2)
if 5 in liste2:
print ("Evet, 5 listemizde mevcut!")
print (" ve listemizde saya", liste2.count (5), "adet 5 var.")
else: print ("Hayr, 5 listemizde mevcut deil!")
liste2 = liste[:]
print ("Listemizden karlan ilk ve son eleman deerleri:", liste2.pop (0), liste2.pop (len (liste2)-1))
liste2.sort()
print ("Sral listemizdeki kalan", len (liste2), "elemanlar:", liste2)
liste2 = liste[:]
liste2.sort()
saya = 0
for i in liste2:
if i < 5: saya +=1
else: break
print ("Orijinal listemizde 5 deerinden kk eleman says:", saya)
print ("Liste elemanlar toplam ve ortalamas:", sum (liste2), round (sum(liste2)/len(liste2), 2))
print ("Listemizdeki enbyk 2 eleman deerleri:", liste2[len(liste2)-1], liste2[len(liste2)-2])
print ("Listemizdeki enkk 2 eleman deerleri:", liste2[0], liste2[1])
saya = 0
for i in liste2:
if i % 2 == 0: saya +=1
print ("Listemizdeki ift deerli elemanlarn says:", saya)
liste2 = [8, 9, 10]
liste2[1] = 17
liste2.append (4); liste2.append (5); liste2.append (6)
del liste2[0] # veya liste2.remove (liste2[0]) veya liste2.pop (0)
liste2.sort()
liste2 = liste2*2
liste2.insert (3, 17)
print ("[8,9,10]'dan ilenmi listemizin son dkm:", liste2)
for i in range (len (liste2)):
if liste2[i] > 10: liste2[i] = 10
print ("10'dan bykleri 10'laan listemiz:", liste2)
|
# coding:iso-8859-9 Trke
import random # from random... hata verir
print ("Seed, Gauss ve Uniform ile aynen tekrarlanan tesadfivari say retimi:\n", "-"*71, sep="")
random.seed (1)
print ("Tohum 1:", [random.randint (1, 100) for i in range (10)] )
random.seed (2)
print ("Tohum 2:", [random.randint (-50, 50) for i in range (10)])
random.seed (3)
print ("Tohum 3:", [round (random.randint (1, 10) + random.random(), 2) for i in range (10)])
random.seed (3)
print ("\nTekrar tohum 3:", [round (random.randint (1, 10) + random.random(), 2) for i in range (10)])
random.seed (1)
print ("Tekrar tohum 1:", [random.randint (1, 100) for i in range (10)] )
random.seed (2)
print ("Tekrar tohum 2:", [random.randint (-50, 50) for i in range (10)])
print ("\nGauss(64,3.5) tesadfi dalm:", random.gauss (64, 3.5) )
print ([round (random.gauss (64, 3.5), 2) for i in range (10)] )
print ("\nEit ihtimalli dalm:", random.uniform (3, 8)
)
print ([round (random.uniform (3, 8), 4) for i in range (10)] ) |
# -*- coding: iso-8859-9 -*-
# Trke karakterlerinin tantm
import sys
dosyaAd = input("Veri eklenecek/yaratlacak dosya ad: ")
try:
# Dosya sistemini aalm...
dosya = open (dosyaAd, "a")
except IOError:
print ("[", dosyaAd, "] dosyasna yazma problemi var!")
sys.exit()
dosyaVerisi = input ("Veri girin [k:son]: ")
while dosyaVerisi != "k":
if dosyaVerisi == "k":
break
dosya.write (dosyaVerisi)
dosya.write ("\n") # Bir alt satra geer...
dosyaVerisi = input ("Veri girin [k:son]: ")
dosya.close()
print()
dosyaAd = input ("erii okunacak dosya ad: ")
if len (dosyaAd) == 0:
print ("Dosya adn girmeden Enter'rladn!")
sys.exit()
try:
dosya = open (dosyaAd, "r")
except IOError:
print ("Dosya okuma hatas olutu!")
sys.exit()
dosyaVerisi = dosya.read() # Tm dosya ieriini okur...
dosya.close()
print (dosyaVerisi) |
# coding:iso-8859-9 Trke
# x+y+z=100
# x*5 + y*3 + z*1/3 = 100
print ("1 Ananas: 5 TL, 1 Mango: 3 TL ve 3 Portakal = 1 TL ise")
print ("3 meyve toplam says 100 adet ve toplam fiyat 100 TL olabilmesi iin")
print ("Meyvelerin kaar adetlik kombinasyonlar bu artlar salar?\n")
print ("="*50)
print ("{:^50s}" .format ("Ananas-Mango-Portakal"))
print ("-"*50)
print ("{:^20s}{:^28s}" .format ("Adet", "Tutar-TL"))
print ("-"*50)
for x in range (21):
for y in range (34):
for z in range (301):
if (x+y+z == 100) and (5*x + 3*y + z/3 == 100):
print ("{:3d} +{:3d} +{:3d} = 100" .format (x, y, z), end=" ")
print ("{:3d} +{:3d} +{:3d} = 100" .format (x*5, y*3, z//3))
print ("="*50)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.