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 += ... |
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+')
... |
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'... |
# !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
卡拉兹(Callatz)猜想:
对任何一个正整数 n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把 (3n+1) 砍掉一半。这样一直反复砍下去,最后一定在某一步得到 n=1。
卡拉兹在 1950 年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,
一心只证 (3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……
我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过 1000 的正整数 n,简单地数一下,需要多... |
# !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
1033 旧键盘打字 (20 分)
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现。现在给出应该输入的一段文字、以及坏掉的那些键,打出的结果文字会是怎样?
输入格式:
输入在 2 行中分别给出坏掉的那些键、以及应该输入的文字。其中对应英文字母的坏键以大写给出;每段文字是不超过 10**5个字符的串。
可用的字符包括字母 [a-z, A-Z]、数字 0-9、以及下划线 _(代表空格)、,、.、-、+(代表上档键)。题目保证第 2 行输入的文字串非空。
注意:如果上档键坏掉了,那么大写的英文字母无法被打出。
... |
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(... |
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 r... |
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 functio... |
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("가능한 팀 배열: ", tea... |
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 assoc... |
#!/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
wi... |
# 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 =... |
"""
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 “neg... |
# 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... |
# 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) - f... |
# -*- 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 t... |
counter = 0 #установим счетчик - это начальное значение переменной для дальнейших вычислений
while counter != 10: #это заголовок цикла, указываем до наступления какого события будет работать цикл.
#В данном случае цикл будет запускаться, пока счетчик не достигнет значения 9, потому что это числоо макисмально
#близко... |
# Cчитаем возраст
BirthYear = input("Введите год Вашего рождения: ") #запрашивает год рождения пользователя.
DesiredYear = input("Введите год, для вычисления возраста: ") #запрашивает год, для которого пользователь хочет вычислить свой возраст.
Age = int(DesiredYear) - int(BirthYear) #переменная для подсчёта разницы ... |
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")
STAT... |
#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(n... |
#!/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,... |
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 ... |
# 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 ... |
# 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 h... |
# 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... |
# 在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)
# ex... |
'''
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... |
# 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):
... |
'''
# 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(... |
# 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:
... |
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:... |
#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 dif... |
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 re... |
#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,
pl... |
"""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 ... |
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':
... |
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)... |
'''
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 key... |
#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... |
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 T... |
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 может быть больше, чем количество минут в сутках.
inputMin... |
# Заполнить список из десяти элементов произвольными целочисленными значениями.
# Затем четные элементы расположить в начале списка, нечетные - в конце.
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 ... |
# Написать функцию, принимающую длину стороны квадрата и рассчитывающую периметр квадрата, его площадь и диагональ.
# Сделать два и более варианта функции, которые должна отличаться количеством возвращаемых переменных.
# Не забыть про проверки входных данных в самой функции.
def square_calc(sides_tup):
"""Функция... |
# Написать функцию, вычисляющую сумму двух переданных чисел.
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))
d... |
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?')
... |
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")
#dif... |
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)
l... |
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
... |
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
fo... |
'''
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
imp... |
# 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 y... |
# 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 '... |
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
... |
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... |
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
:... |
#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_languag... |
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 WARRANTIE... |
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)... |
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
... |
# -*- 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: f... |
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 ... |
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('voi... |
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,... |
# 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 tamam... |
# 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 = f... |
# 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_zama... |
# 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... |
# 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... |
# 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 ... |
# 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="... |
# 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 tamamla... |
# 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 ("\n... |
# 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 t... |
# 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 (k... |
# 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 (lambd... |
# 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 de... |
# 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.s... |
# 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) ... |
# -*- 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 ... |
# 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}" .for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.