text stringlengths 37 1.41M |
|---|
def sayHello():
print('Hello World!')
sayHello()
def printMax(a = 2, b):
if a > b:
print(a)
else:
print(b)
a = 4
b = 0
printMax(b) |
import pygame
class Circle:
def __init__(self, rad):
self.rad = rad
print("Ball rad {} has been created!".format(self.rad))
def position(self, x, y):
self.x = x
self.y = y
print("Ball with rad {} is in ({}, {}) position.".format(self.rad, self.x, self.y))
def dire... |
import random
a=input("请输入您要猜的数:")
print(type(a))
#数字范围是[1,1000]
secret = random.randint(1, 1000)
guess = 0
while guess != secret:
guess = int(input("Guess a number: "))
if guess == 0:
print("Sorry to see you go")
break
if guess > secret:
print("too large")
elif gues... |
class Employee:
salary_raise = 1.04
def __init__(self, name, last, salary):
self.name = name
self.last = last
self.salary = salary
def __str__(self):
return f"Name: {self.name} -- Last: {self.last}\nSalary: {self.salary}"
def apply_raise(self):
self.sal... |
from tkinter import *
from time import strftime
class Clock:
def __init__(self, root):
self.root = root
self.root.title("Clock")
self.root.resizable(0, 0)
self.root.iconbitmap("clock-icon.ico")
# VARS
self.time_var = StringVar()
# Time Label
self.tim... |
import numpy as np
import math as math
import cv2 as cv
import Layer
class ReLuLayer(Layer.Layer):
"""Actually a leaky ReLU in order to avoid dead neurons
Has the form f(x) = max(0.1x, x)
Has no learned parameters"""
def __init__(self, input_dim):
Layer.Layer.__init__(self, input_dim, i... |
"""
给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
示例:
输入: [1,2,3,0,2]
输出: 3
解释: 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
"""
class Solution:
def maxProfit(self, prices) -> int:
if len(prices) <= 1:
... |
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/... |
"""
把两个树重叠,重叠部分求和,不重叠部分是两个树不空的节点
"""
"""
题目大意
将两个二叉树进行merge操作。操作方式是把两个树进行重叠,如果重叠部分都有值,那么这个新节点是他们的值的和;如果重叠部分没有值,那么新的节点就是他们两个当中不为空的节点。
解题方法
递归
如果两个树都有节点的话就把两个相加,左右孩子为两者的左右孩子。
否则选不是空的节点当做子节点。
时间复杂度是O(N1+N2),空间复杂度O(N)。N = t1 的 t2交集。
"""
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: Tre... |
#快排 O(N) O(1)
"""class Solution:
def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int':
return self.quick_sort(nums, k)
def quick_sort(self, nums, k):
k = len(nums) - k
left = 0
right = len(nums)
"""
# 首先要明确,此题目求的是 第K个最大元素,就是说将数据进行从小到大排序,倒数第K个元素。
class Solution:
def... |
"""
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
提示:
每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。
"""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
... |
ara=input("enter the string\n")
reverse=''
i=len(ara)
while i>0:
reverse=reverse+ara[i-1]
i=i-1
print(reverse) |
#Implement a program with functions, for finding the area of circle, triangle, square
p=3.147
def area_of_circle():
x=int(input("enter the radius of circle:\n"))
return (p*x*x)
def area_of_triangle():
b=int(input("enter the base:\n"))
h=int(input("enter the height:\n"))
return(0.5*b*h)
def area_of_square():
r=... |
abc=input("enter the string\n")
count=0
for b in abc:
if (b=='a' or b=='e' or b=='i'or b=='o'or b=='u'):
count=count+1
print("number of vowels in string is",count) |
class User:
"""
a class that generates new instances of passwors
"""
user_list = []
def __init__(self,first_name,last_name,password):
"""
_init_ a method that helps to define properties for our objects.
"""
self.first_name = first_name
self.last_name = last... |
my_dict = dict()
for i in range(0,3):
key = input("Enter the name: ")
value = input("Enter the usn: ")
my_dict[key] = value
print(my_dict) |
import unittest
import twothirds
class TestGame(unittest.TestCase):
def test_initialisation_from_other_than_list_gives_errors(self):
data = 2
self.assertRaises(ValueError, twothirds.TwoThirdsGame, data)
def test_initialisation_from_list(self):
data = range(100)
g = twothirds.Tw... |
x = int(raw_input("Dime un numero: "))
y = int(raw_input("Dime otro numero: "))
while x<=y:
if x%2==0:
print x
x += 1 |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
X = input("Enter first string: ").lower()
Y = input("Enter second string: ").lower()
#X ="I love horror movies"
#Y ="Lights out is a horror movie"
# tokenization
X_list = word_tokenize(X)
Y_list = word_tokenize(Y)
# sw contains the list of sto... |
# A Dictionaries is a collection which is unordered, changeable and indexed. No duplicate members.
#Note: Dictionaries are same as Objects in javascipt
#Create dict
person={
'first_name' : 'theodore',
'last_name' : 'kimana',
'age': 24,
}
household={
'dad': 'Theobare',
'mom' : 'Odette',
'dad_age': 54,
'mom_a... |
import util
class Obstacle:
"""
Classe représentant un obstacle
...
Attributs
-----
min_y : int
Position en y
pos_x : int
Position en x
largeur : int
largeur de l'obstacle
hauteur : int
hauteur de l'obstacle
Méthodes
-----
... |
#!/usr/bin/env python
#-*-coding:utf-8 -*-
# print 'hello, %s' % 'world'
# print 'Hi, %s, you have $%.1f.' %('Michael', 33.111)
# print '%02d - %03d' % (2,1)
# print "growth rate: %d%%" % 7
# source1 = 72
# source2 = 85
# imp = ((85 - 72) / 72) * 100
# # print "improve: %.1f%%" % ((source2-source1)/source1)*100
# ... |
import numpy as np
import matplotlib.pyplot as plt
# Calculating the parameters based on formulas
def best_fit(X, Y):
a1 = ((X*Y).mean() - X.mean()*Y.mean())/((X**2).mean() - (X.mean()**2))
a0 = Y.mean() - a1*X.mean()
return a0, a1
X = np.array([1, 2, 3, 4, 5, 6])
Y = np.array([1.5, 4, 4, 6, 7, 8])
plt.scatter(X... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
class Classifier(object):
""" Multi Class Classifier base class """
def __init__(self, input_size, n_classes):
"""
Initializes a matrix in which each column will be the Weights for a specific class... |
# -*- coding: utf-8 -*-
from sklearn.externals import joblib
from classifier import Classifier
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
class MultinomialLR(Classifier):
""" Multinomial Logistic Regression """
def __init... |
from constants import *
from math import fabs, sqrt
class Matches:
"""creates group(field) of matches that can be drawn selectively"""
def __init__(self, field_power, indent=INDENT_BETWEEN_MATCHES, indent_x=MATCH_INDENT_X, indent_y=MATCH_INDENT_Y):
self.field_power = field_power
self._create_... |
#枚举类
from enum import Enum
Month=Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Aug','Sep','Oct','Nov','Dec'))
for name,member in Month.__members__.items():
print(name,'=>',member,',',member.value)
#type()函数既可以返回一个对象的类型,又可以创建出新的类型
class Hello():
def hello(self,name='world'):
print('Hello %s .'% name... |
print('Welcome to input checker!')
original = input("Enter a word:")
if len(original) > 0: # Checks that something was inputted
print(original)
else:
print("Your input is empty")
print('Welcome to alphabetical input checker!')
original = input("Enter a word:")
if len(original) > 0 and original.isalpha(... |
# Return sorted sequence (by value order)
c = {'a': 10, 'c': 22, 'b': 1}
tmp = list()
for k, v in c.items():
tmp.append((v,k))
print(tmp)
tmp = sorted(tmp, reverse=True)
print(tmp) |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
# find all lines starting with "From" and capture the email address in the list 'emails'
emails = list()
for line in handle:
if line.startswith('From '):
emails.append(line.split(' ')[1])
#print(emails)
# from the l... |
while True:
operator = input("To multiply or divide, please select * or /: ")
if operator == "/" or operator == "*":
break
else:
print("That is an invalid operator, please try again\n")
def math_function(num1, num2):
if operator == "*":
math_function = int(num1) * int(num2)
... |
dct = {'chuck': 1, 'fred': 42, 'jan': 100}
# print dictionary
print(dct)
# change dictionary keys into list
print(list(dct))
# change dictionary keys into list with method
print(dct.keys())
print(list(dct.keys()))
# change dictionary values into list with method
print(dct.values())
print(list(dct.values()))
# chan... |
def product(nums):
total = 0
print(nums)
for n in nums:
if total == 0:
total = n
else:
total *= n
print(total)
return total
product([4, 5, 5])
# ---------------------------#
def product(nums):
total = 1
print(nums)
for n in nums:
total *... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
count = 0
spam_total = 0.0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
count += 1
num = line.find(":")
spam = float(line[num+1:])
spam_total = spam_total + s... |
def reverse(x):
drow = ''
for i in range(len(x) -1, -1, -1):
drow += x[i]
i -= 1
# print(drow)
return drow
print(reverse('abcd'))
# ---------------------------------------- #
to_one_hundred = list(range(101))
# print(to_one_hundred)
backwards_by_tens = to_one_hundred[::-10]
print(bac... |
class Students:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def avg(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
print("{} is going to {}.".format(self.name, self.school))
anna = Students("Anna"... |
#!/usr/bin/python
#coding:utf8
'''
first step:pip install pyramid-arima
'''
import pandas as pd
import numpy as np
from pyramid.arima import auto_arima
print("load dataset...")
data = pd.read_csv('international-airline-passengers.csv')
#divide into train and validation set
train = data[:int(0.7*(len(data)))]
valid ... |
# Quiz 1: Create Usernames
#Write a for loop that iterates over the names list to create a usernames list.
#To create a username for each name, make everything lowercase and replace
#spaces with underscores. Running your for loop over the list.
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buf... |
"""
This neural network is to be used to compare to our k-means model. We hope that
this model is a good comparison. The code is made by following the implemention by
http://neuralnetworksanddeeplearning.com/chap1.html
"""
# Useful libraries
import numpy as np
import random
# Our Defined Libraries
import Sigmoid
... |
from Exceptions.Numbers import Numbers
n = Numbers()
try:
num1, num2 = input("Introduce dos numeros separados por comas:")
except NameError as ex:
print("Exception:", ex)
except TypeError:
print("No se indicaron los numeros separados por comas")
else:
print("Solo se ejecuta cuando no entra a ni... |
import numpy as np
# 损失函数梯度
def DJ(X_b, y, theta):
"""
:param X_b: 处理之后的矩阵
:param y: y值
:param theta: θ
:return res: 梯度向量
"""
res = np.empty(len(theta))
res[0] = np.sum((X_b.dot(theta) - y))
for i in range(1, len(theta)):
res[i] = np.sum((X_b.dot(theta) - y).dot(X_b[:, i]))... |
strHours = input('Enter Hours: ')
strRate = input('Enter Rate: ')
floatHours = float(strHours)
floatRate = float(strRate)
if floatHours > 40 :
overtimeHours = floatHours - 40
overtimeRate = floatRate * 1.5
# print('')
# print('Overtime hours: ' + str(overtimeHours))
# print('Overtime rate: ' + str... |
print("Hello World double quote")
print('Hello World single quote')
print('O----')
print(' !|')
print('*' * 10)
price = 10
price = 25
print(type(price), price)
rate = 2.5
print(type(rate), rate)
name = "Naveen"
print(type(name), name)
isHappy = True
print(type(isHappy), isHappy)
|
import random
import string
for i in range(3):
print(random.random())
print(random.randint(10, 50))
alphabets = string.ascii_lowercase[:26]
print("random", random.choice(alphabets))
class Dice:
def roll(self):
f = random.randint(1, 6)
s = random.randint(1, 6)
return f, s
dice =... |
#coding=utf-8
import sys
"""
掌握内容
1、迭代器有两个基本的方法:iter() 和 next()
2、生成器的yield函数
3、str.strip()把字符串(str)的头和尾的空格,以及位于头尾的\n \t之类给删掉,
"""
#使用生成器处理文件,用户指定要查找的内容,将文件中匹配到的行输出到屏幕
def read_file(filename,test):
with open(filename) as file:
for line in file:
if test in line:
yield line
RR =... |
__author__ = 'jonathan'
from collections import OrderedDict
# following code inspired from:
# http://stackoverflow.com/questions/2437617/limiting-the-size-of-a-python-dictionary
class DictionaryWithLimitedSize(OrderedDict):
"""A python dictionary that has a limited size."""
def __init__(self, *args, **kwd... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 19 11:23:37 2019
@author: user
"""
#create a Node
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
def printListFromTailToHead(self,listNode):
alist = []
while listNode:
alist.append(l... |
# load up the libraries we will need
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
# load the dataset from the csv file
dataset = pd.read_csv('house-prices.csv')
# print the ... |
list=[1,2,3,4,5]
for i in range(len(list)):
print(list[i]) |
def add(a,b):
"""
this method is to get the sum of two numbers
a:number
b:number
"""
s = a+b
return s
sum = add(10,20)#s
print(sum) |
name_list = ["david","xavier","jim","alan","jim"]
def clearAll(name_list):
"""
this method is to clear all the elements in a list
name_list:list
"""
name_list.clear()
return(name_list) |
str1=input('plz input ur str')
str2=input('plz input ur str')
new_str=str1[:2]
print(new_str)
str1=str1.replace(str1[:2],str2[:2])
print(str1)
str2=str2.replace(str2[:2],new_str)
print(str2)
new_str=str1+' '+str2
print(new_str) |
#insert sort model:队伍的壮大
list=[3,5,6,0,1,2]
for i in range(1,len(list)):
for j in range(i,0,-1):
if list[j-1]>list[j]:
num=list[j]
list[j]=list[j-1]
list[j-1]=num
print(list) |
#1.准备任务
import threading
import time
def coding():
print("coding_thread:",threading.current_thread())
for i in range(10):
print("coding...")
time.sleep(0.3)
def debugging():
print("debugging_thread:",threading.current_thread())
for i in range(10):
print("debugging...")
... |
age=int(input("plz input your age:"))#str
def ifBasic(age):
"""
this method is to judge if user's inputted age greater than 16.
age:age
"""
if age>=16:#if filter int float
return "adult,you can enjoy your happy hour!"
print(ifBasic(age))
|
# 3.2 应用二:计算1-100偶数累加和
def even():
"""
this method is to get the sum of all the even numbers from 1-100
"""
sum = 0
num=1#初始条件
while num<=100:#判断条件
if num%2==0:
sum = sum+num
num+=1#while的步进
return(sum) |
import random
num=random.randint(0,100)
uI = int(input("plz enter your input:"))
while uI!=num:
if uI<num:
print('smaller')
elif uI>num:
print('bigger')
uI = int(input("plz enter your input:"))
print('bingo')
|
name_list=['david','xavier','alan','jim']
print(name_list)
#del:删除指定元素
del name_list[0]
print(name_list)
#pop():从list中弹出指定元素
name=name_list.pop(0)
print(name_list,name)
#remove():删除列表中指定元素(第一个匹配的)
name_list.remove('alan')
print(name_list)
#clear:清空list
name_list.clear()
print(name_list)
|
def sorry():
"""
this method is to say sorry to your girlfriend though you don't have one
"""
i = 1
while i <= 5:
if i == 3:
print('so sick')
i += 1
continue
print('sorry')
i += 1
else:
return 'thank you for your forgiveness' |
str=input('your sentence?')
if str.find('not')!=1 and str.find('poor')!=-1:
begin=str.index('not')
end=str.index('poor')
print(str.replace(str[begin:end+len('poor')],'good',100))
elif str.find('poor')!=-1:
print(str)
|
num_list = [3,5,6,0,1,2]
#res_list[]
#假设min=3 min=0
#num_list = [3,5,6,1,2]
def BubbleSort(num_list):
"""
this method is to sort the elements form smallest to greatest
num_list:array which contains elements
"""
num = len(num_list)-1
while num>0:
for j in range(num):
if num_l... |
# str="hello" \
# "world"
# print(str)
def enter():
"""
this method is to print a string in a new line
"""
str=""" hello
world
"""
return(str) |
list=[1,2,3,4]
# list.append(5)
# print(list)
# list=["byte","tube"]
# list.extend("dal")
# print(list)
def removeEle(list):
"""
this method is to remove 1 element in the list and show the length of the list
list:list
"""
list.remove(11,100)
return len(list)
|
class Student(object):
def __init__(self,name,gender,grade):
self.name=name
self.gender=gender
self.grade=grade
def __str__(self):
return f'{self.name},{self.gender},{self.grade}' |
integer=100
res=0
while integer>=1:
if integer%2==0:
if integer==66:
integer-=1
continue
res+=integer
integer-=1
else:
print(res) |
"""
Given a sorted array of integers, return the two numbers that they add up to a specific target. You may assume that
each input would have exactly one solution, and you may not use the same element twice.
"""
arr = [-2, 1, 2, 4, 7, 11]
target = 13
# Brute Force:
# Time complexity: O(n^2)
# Space complexity: O(1)
de... |
"""
Problem:
write a function that takes an array of sorted integers and a key and returns the index of the first occurrence of that
key from the array.
For example, for the array:
[-14, -10, 2, 108, 108, 243, 285, 285, 285, 401]
with target = 108, the algorithm would return 3, as the first occurrence of 108 in th... |
"""
Problem:
Given two numbers, find their product using recursion.
"""
x = 5
y = 3
def product_recursive(num1, num2):
# Cutting down in on the number of recursive calls
if x < y:
return product_recursive(y, x)
if num2 == 0:
return 0
return num1 + product_recursive(num1, num2 - 1)
... |
"""
Problem:
Implement an algorithm to determine if a string has all unique characters.
"""
def unique_char(word):
letters = dict()
for char in word:
if char not in letters:
letters[char] = 1
else:
letters[char] += 1
unique = ""
for k, v in letters.items():
... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def ... |
size = int(input())
array_input = []
for x in range(size):
array_input.append([int(y) for y in input().split()])
print(array_input)
for i in array_input:
for j in i:
print(j, end=" ")
print()
|
"""
Walrus Operator ":="
"""
def func(x):
return x + 1
if (x := func(4)) >= 5:
print(x)
(walrus := func(2))
# print(walrus)
"""
String Intern => Mutability of Objects
Intern: A method of storing only one copy of each distinct string value, which must be immutable.
"""
a = "".join(['o', 'k', 'a', 'y'])
... |
from numpy import *
from matplotlib.pyplot import *
# Create 100 equidistant points between 0 and 2*pi
xs = linspace(0, 2.*pi, 100)
# Create a title for the plot
title("How to make plots")
# Create labels for the axes
# Note that in the label, you can use TeX-strings!
xlabel("$x$")
ylabel("$f(x)$")
# Now create two p... |
import random
import time
import sys
import os
class TicTacToe:
board = ['_', '|', '_', '|', '_', '_', '|', '_', '|', '_', ' ', '|', ' ', '|', ' ']
remaining_choices = ['1', ' ', '2', ' ', '3', ' ', '4', ' ', '5', ' ', '6', ' ', '7', ' ', '8', ' ', '9']
player_game_piece = str
comp_game_piec... |
import urllib
import urllib2
import requests
# Test URL
url = "http://rfunction.com/code/1202/120202.R"
# 1. Using urllib module
print "Begin download with urllib"
urllib.urlretrieve(url, "code1.R")
# 2. Using urllib2 module
print "Begin download with urllib2"
f = urlllib2.urlopen(url)
with open("code2... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 21
b = 10
c = 0
if ( a == b ):
print ("1 - a=b")
else:
print ("1 - a!=b")
if ( a != b ):
print ("2 - a!=b")
else:
print ("2 - a=b")
if ( a <> b ):
print ("3 - a!=b")
else:
print ("3 - a=b")
if ( a < b ):
print ("4 - a<b" )
e... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个的元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
'''
非法,不能重新赋值
list... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 可写函数说明
def changeme(mylist):
u"修改传入的列表"
mylist.append([1,2,3,4]);
print u"函数内取值: ", mylist
return
# 调用changeme函数
mylist = [10,20,30];
changeme(mylist);
print u"函数外取值: ", mylist |
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-5,5,0.01)
y=x**3
plt.axis([-6,6,-10,10])
#plt.ylim()
plt.plot(x,y)
plt.show()
plt.grid(True) |
def Print(msg):
print msg
def Add(x, y):
z = x + y
ret = Print("Hello, python!")
print "ret: ", ret
ret = Add(3, "2")
print "ret: ", ret |
import numpy as np
import matplotlib.pyplot as plt
# arange is similar to function range, but returns NumPy array of floats
x = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
# NumPy functions return NumPy arrays
cos_x = np.cos(x)
sin_x = np.sin(x)
# Demonstrate PyPlot interface to matplotlib
plt.figure()
plt.plot(x, cos_x,... |
"""Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа
должна подсчитывать сумму чисел в файле и выводить ее на экран. """
from itertools import count
# Собираем числа от 1 до n и сразу считаем их сумму
n = 4
nums = []
nums_sum = 0
for el in count(1):
if e... |
"""
Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных,
вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту
ситуацию и не завершиться с ошибкой. """
class MyZeroDiv(Exception):
def __str__(s... |
"""Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк,
количества слов в каждой строке."""
with open('5-02-text.txt') as file:
i = 1
words_len = {}
# Собираем пары "номер строки: количество слов"
for line in file:
words_len.update({i: le... |
number = int(input("Введите число "))
degree2 = '{}{}'.format(number, number)
degree3 = '{}{}'.format(degree2, number)
sum = number + int(degree2) + int(degree3)
print(sum) |
input_month = int(input("Введи порядковый номер месяца - "))
#Решение с dict
seasons_dict = {'Зима':{11,12,1},'Весна':{2,3,4}, 'Лето':{5,6,7}, 'Осень':{8,9,10}}
for key,val in seasons_dict.items():
if input_month in val:
print(key)
#Решение с list
seasons_month = [
[11, 12, 1],
[2, 3, 4],
[5, ... |
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline
def f(X):
return (X[0]**2 + X[1] - 11)**2 + (X[0] + X[1]**2 - 7)**2
# Аналитический способ вычисления производных
def theory_df(X):
derivative_x1 = 2 * (-7 + X[0] + X[1] ** 2 + 2 * X[0] * (-11 + X[0]**2 + X[1]))
derivative_x2 = 2 * (-... |
# Inspired by "12 Beginner Python Projects - Coding Course" from FreeCodeCamp.
# Added input validation, games keeps replaying untill user types 'exit' (loop) &
# displays computer's pick to the player.
import random
import pyinputplus as pyip
def play():
global user
global computer
print("Make ... |
# Guess The Number Game
# Challenge 3, chapter 3 python for the absolute beginner
# The player has to guess the number (between 1 and 30).
# The player has 5 chances to guess, otherwise he gets a chastising message.
import random
print("\t\t\t\t\t\tGuess the right number!")
print("\nChoose a number between 1 ... |
#! python3
# 2048.py - my solution to practice project "2048"
# from "Automate The Boring Stuff".
# 2048 is a game where you combine tiles by sliding them using the arrow keys.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox()
browser.ge... |
# Задание 2
from random import randint
list = []
for i in range(15): # создание списка
a = randint(0, 100)
a = int(a)
list.append(a)
print(list)
print([list[i] for i in range(len(list)) if list[i] > list[i - 1]]) # вывод значений
# |
# Задание 4
#без генератора
my_list = [1, 2, 1, 2, 5, 6, 13, 2]
my_set = set(my_list)
#print(my_set) - тестовая строка
new_list = list(my_set)
print(new_list)
#с генератором
from random import randint
my_list = []
for i in range(15): # создание списка
a = randint(0, 10)
a = int(a)
my... |
# raise案例-2
# 自己定义异常
# 需要注意: 自定义异常必须是系统异常的子类
class DanaValueError(ValueError):
pass
try:
print("我爱王晓静")
print(3.1415926)
# 手动引发一个异常
# 注意语法:raise ErrorClassName
raise DanaValueError
print("还没完呀")
except NameError as e:
print("NameError")
except DanaValueError as e:
print('DanaValueEr... |
from tkinter import messagebox
from tkinter import *
import numpy as np
b = []
h = []
j = []
k = []
root = Tk()
root.title(" Solving simultaneous linear equations ")
root.geometry('650x1900')
root.configure(bg='teal')
dg = Label(root, text='enter names of variables in the equations ')
dg.grid(column=0, row=0, column... |
Number = input("Enter a number")
Number = int(Number)
if Number > 10:
print(str(Number) + " is greater than 10")
elif Number == 10:
print(str(Number) + " is 10")
elif Number < 10:
print(str(Number) + " is less than 10") |
formula = input()
splited_by_minus = formula.split("-")
sum = 0
for num in splited_by_minus[0].split("+"):
sum += int(num)
for i in range(1, len(splited_by_minus)):
for num in splited_by_minus[i].split("+"):
sum -= int(num)
print(sum)
|
import arcade
from .game import GameObject
UP = "up"
DOWN = "down"
RIGHT = "right"
LEFT = "left"
POSITIVE_DIRECTION = 1
NEGATIVE_DIRECTION = -1
NEUTRAL_DIRECTION = 0
START_DIRECTION_X = POSITIVE_DIRECTION
START_DIRECTION_Y = NEUTRAL_DIRECTION
class SnakeTurningPoint(GameObject):
"""
Holds the data that re... |
import csv
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Op... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Tsou"
# Email:625139905@qq.com
"""
1.函数
在python中,函数通过def关键字、函数名和可选的参数列表定义。
通过return关键字返回值。
"""
# def foo():
# return 1
# print(foo())
"""
方法体是必须的,通过缩进来表示,
在方法名的后面加上双括号()就能调用函数
"""
"""
2.作用域
在python中,函数会创建一个新的作用域。
python开发者可能会说函数有自己的命名空间,差不多一个意思。
这意味着在函... |
temp_C = input("enter temperature in degC: ")
temp_F = float(temp_C)*9/5+32
print("The temperature in {} degF".format(temp_F))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.