text stringlengths 37 1.41M |
|---|
# create a class that return capital letters using a iterator
class Upper_case_iterartor:
def __init__(self):
self.start = "A"
def __next__(self):
if ord(self.start) > 90:
raise StopIteration
else:
self.start = chr(ord(self.start) + 1)
retur... |
# accept 10 marks and display marks which are greater than the average
marks = []
aaveg = []
sum = 0
for i in range(10):
n = int(input("Enter the Marks of the student : "))
sum += n
marks.append(n)
l = len(marks)
avg = sum / l
print(f"The Average Mark is : {avg}")
for i in marks :
if i >= av... |
# accept a list of number and print them in names.txt in sorted order
n = open("names.txt", "wt")
names = []
while True:
m = input("Enter a Name (Press ENd to stop) :")
if m == "end":
break
else:
names.append(m)
for l in sorted(names):
n.write(l + "\n")
n.close()
|
# to set both the number to the highest of them
a = int(input("Enter the First Number : "))
b = int(input("Enter The Second Number : "))
print(f"The Input Numbers are : {a} {b}")
if a > b:
b = a
else:
a=b
print(f"The Required Numbers : {a} {b}")
|
import time
from binary_search_tree import BinarySearchTree
start_time = time.time()
import sys
sys.setrecursionlimit(10**6)
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names... |
# 4.1.3:P091-谁是冠军
# 这次面试的冠军在A、B、C、D四位同学中。
# A说:“不是我。”
# B说:“是C。”
# C说:“是D。”
# D说:“C说的不对。”
# 已知四人中有一人说了假话。你能判断出到底谁是冠军吗?
champion = ['A', 'B', 'C', 'D'] # 设置选手列表
for i in champion: # 循环读取选手编号
cond = (i != 'A') + (i == 'C') + (i == 'D') + (i != 'D') # 查找符合条件的选手
if cond == 3: # 说真话是否是3人
print("冠军是:", ... |
import tkinter.ttk
import datetime
import random
import string
class MyIterator:
# 单位字符集合
min_digits = 0
max_digits = 0
def __init__(self, letters, min_digits, max_digits):
self.letters = letters
# 实例化对象时给出密码位数范围,一般4到10位
if min_digits < max_digits:
self.min_digits ... |
import tkinter # 导入tkinter模块
def caesarcipher(): # “加密”按钮激发函数
c = mingwen.get("0.0", "end")[:-1] # 获取mingwen对象的内容(明文)
b = ""
miwen.delete("0.0", "end") # 清空miwen对象的内容
for i in range(len(c)): ... |
print('这是一个有关累加问题1+1/2+1/3+1/4+……1/n的程序')
n = int(input("请输入整数n的值:"))
s = 0
for i in range(1, n + 1):
s = s + 1 / i
print("1 + 1/2 + … + 1/{} = {}".format(n, s))
input("运行完毕,请按回车键退出...")
|
# P098-斐波那契数列
def fib(a):
# 迭代求Fibonacci数列
f2 = f1 = 1
for i in range(3, a + 1):
f1, f2 = f2, f1 + f2
return f2
n = int(input('输入需要计算的月份数:'))
print('兔子总对数为:', fib(n))
input("运行完毕,请按回车键退出...")
|
listque = [] # 定义列表listque存储订单
x = 0
while x != 4: # 当x!=4时,执行循环
print('\n1. 添加订单')
print('2. 发货')
print('3. 查看订单列表')
print('4. 退出')
x = int(input("输入你的选择:")) # 输入选择项
if x == 1:
y = input("输入订单编号:") # 输入订单编号
listque.append(y) # 在列表listque中添加订单号
elif x == 2:
if le... |
import tkinter
window = tkinter.Tk() # 建立一个窗体的实例并命名为window
window.geometry('300x300') # 设置窗体的宽度和高度
window.title('窗口标题') # 设置窗体的标题
# 定义按钮被点击后的执行函数
def click_button():
text.delete('0.0','end') # 清空text这个文本框里的所有输入的内容
photo = tkinter.PhotoImage(file='logo.png')
# 建立一个label标签组件并命名为label,设置文字内容格式
label = tkint... |
que_list = [] # 定义列表que_list存储停车状况
max_volume = 8 # 停车位最大容量
while True: # 永远执行循环
print('\n1. 进栈停车') # \n表示换行打印
print('2. 开车出栈')
print('3. 查看停车库')
print('其他. 退出')
x = input("输入你的选择:") # 输入选择项
if x == '1':
if len(que_list) < max_volume:
print("还有" + str(max_volume - len(qu... |
# 杨辉三角形
# 又称Pascal三角形,它的第i+1行是(a+b)i的展开式的系数。
# 它的一个重要性质是:三角形中的每个数字等于它两肩上的数字相加。
# 定义函数如下(其中:x指定行、y指定列)
def f(x, y):
if y == 0 or x == y:
return 1
else:
return f(x - 1, y - 1) + f(x - 1, y)
# 获取第5行第3列
print(f(5, 3))
input("运行完毕,请按回车键退出...")
|
# 尝试用二分法求解方程x**3-x**2-x-1=0
def f(x):
return x ** 3 - x ** 2 - x - 1 # 【补】函数表达式
while True:
# 要保证 f(x1) * f(x2) < 0 才能确认方程在(x1, x2)内有解
x1 = float(input("请输入有解单调区间左边界:"))
x2 = float(input("请输入有解单调区间右边界:"))
if f(x1) * f(x2) <= 0 and x1 < x2:
break
else:
print("输入的区间可能无解!")
x0 =... |
print('这是一个有关求1+1/2+1/3+1/4+……+1/n值不小于3的最小n的程序')
s = 0
i = 0
while s < 3:
i = i + 1
s = s + 1 / i
print("最小n值为:", i, "此时和为", s)
input("运行完毕,请按回车键退出...")
|
import tkinter
import tkinter.messagebox
def caesar_cipher1(): # “加密”按钮激发函数
c = mingwen.get("0.0", "end")[:-1]
if c == '':
tkinter.messagebox.showinfo('恺撒密码', '请输入明文。')
return
b = ""
miwen.config(state="normal")
miwen.delete("0.0", "end")
for i in range(len(c)):
if 'a'... |
class Test:
def __init__(self):
self.a=10
self.b=20
def m1(self):
self.c=30
t1=Test() ##Adds a and b to the instance object
t1.m1() ##Adds c to the instance object
t1.d=40 ##Adds d to the instance object
print(t1.__dict__)
t2=Test()
print(t2.__dict__)
|
def romanToInt(s):
dict = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
value = 0
prev = 0
for character in s:
current = dict[character]
if prev < current:
value += current - 2*prev
else:
value += current
prev = current
roman... |
def reverse(x):
if x <= -2**31 or x >= 2**31-1:
return 0
else:
numStr = str(x)
result = 0
if x >= 0:
reverse = numStr[::-1]
result = int(reverse)
else:
numStr = numStr[1:]
reverse = "-" + numStr[::-1]
result = in... |
# decorators
from abc import abstractmethod
class Datatype:
@abstractmethod
def __init__(self, *args):
pass
@abstractmethod
def __len__(self):
pass
@abstractmethod
def __getitem__(self, key):
pass
@abstractmethod
def __setitem__(self, key, value):
... |
#!/usr/bin/env python
# coding: utf-8
# In[10]:
def say_hello():
"""function of saying Hello."""
print("Assalamualaikum.")
say_hello()
a=say_hello
# In[15]:
def sum_n_numbers():
"""sum of n numbers in python"""
n=int(input("Enter a number:"))
s=0
for i in range(n+1):
s+=i
... |
"""
File: best_photoshop_award.py
Name: Pei-Feng (Kevin) Ma
----------------------------------
This file creates a photoshopped image
that is going to compete for the 2020 Best
Photoshop Award for SC101P.
Please put all the images you use in image_contest folder
and make sure to choose which award you are aiming at
"""... |
"""
File: bouncing_ball.py
Name: Name: Pei-Feng (Kevin) Ma
-------------------------
This program simulates a bouncing ball at (START_X, START_Y)
that has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
from campy.graphics.gobjects import GOval, GLabel
from campy... |
"""
File: boggle.py
Name: Pei-Feng (Kevin) Ma
----------------------------------------
This program will find all the exist word in a 4*4 boogle game.
It allows user to input 4 words in 4 rows, and print out words that are
in the dictionary in the console.
"""
# This is the file name of the dictionary txt file
# we wil... |
"""
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
"""
class Solution:
def climbStairs(self, n: int) -> int:
# 状态转移方程
#... |
"""
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的
现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防
盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报
装置的情况下,能够偷窃到的最高金额。
示例 1:
输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入: [2,7,9,3,1]
输出: 12
解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9... |
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
def insert(self, val):
if self.val:
if val < self.val:
if self.left is None:
self.left = Node(val)
else:
se... |
class solution:
def URLify(self,input_str,key):
input2 = ""
for i in range(len(input_str)):
if(input_str[i] != ' '):
input2+=input_str[i]
elif((input_str[i]==' ') and (input_str[i+1] == ' ')):
return input2
elif((input_str[i]==' ') ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 25 08:46:51 2018
@author: python
"""
import multiprocessing
def create_items(pipe):
output_pipe,_=pipe
for item in range(10):
output_pipe.send(item)
output_pipe.close()
def multiply_items(pipe_1,pipe_2):
close,input_pipe=pipe_1
close.close... |
#참과 거짓 boolen
#만약 -하다면 if
#true, False
#and, or , # NOT
# a = True
# b = False
#
# #A가 참이거나 혹은 B가 참이라면
# print (a and b)
# #A가 참이고 그리고 B가 참이라면
# print (a or b)
# # = & ==
# c=True
# print(a==True)
# print(a is True)
d=7
if d>10:
print("숫자는 10보다 큽니다")
elif d>5 and d<10:
print("숫자는 10보다 작거나 같고, 5보다는 큽니다.")
el... |
#input 숫자로받기
#for 반복
# for i in range(2,3):
# for j in range(1,3):
# print(i*j)
#
# i=input("몇 단을 출력하시겠습니까? ")
# for j in range(10):
# print(i*j)
#1)사용자로부터 몇 단을 출력할지 받을것
#2) 해당단을 곱하기 1에서 9까지 실행할것
dan=int(input("몇 단을 출력 하시겠습니까?"))
for num in range(1,10):
print("{}*{}={}".format(dan,num,dan*... |
"""
ID: jasonhu5
LANG: PYTHON3
TASK: palsquare
"""
def convert(num, B):
digits = '0123456789ABCDEFGHIJK'
res = []
while num > 0:
res.append(digits[num % B])
num //= B
return ''.join(reversed(res))
def is_palindrome(s):
return all(s[i] == s[-i-1] for i in range(len(s)//2))
def solv... |
import os,re
from collections import Counter
import nltk
from nltk.corpus import stopwords
useless_words=['the','I','and','']
def main():
for file in os.listdir("."):
result=Counter()
if file.endswith('.text'):
with open(file,'rt') as f:
for line in f:
# delete the stopwords in note
words=line.sp... |
'''
Quando utilizar?
- Se deseja reutilizar uma determinada feature em várias classes diferentes.
- Para melhorar modularidade
Mixins é uma forma controlada de adicionar funcionalidades as classes.
Propriedades:
1) não deve ser extendida
2) não deve ser instanciada
E python o conceito de mixins é implementa... |
# ****
# ******
# *
# ***
# *****
# *******
# *************************
z = [4, 6, 1, 3, 5, 7, 25]
w = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def draw_stars(arr):
for i in range(len(arr)):
string_sum = ""
for j in range(arr[i]):
string_sum = string_sum + "*"
print s... |
exOne = ['magical unicorns',19,'hello',98.98,'world',7, 9]
exTwo = [2,3,1,7,4,12]
exThree = ['magical','unicorns']
def checkType(a_list):
listLength = len(a_list)
stringSum = ""
numSum = 0
temp_type = ""
for x in range(0, listLength):
if isinstance(a_list[x], str):
temp_type =... |
# Start with a list like this one: . Sort your list first.
# Then, split your list in half. Push the list created from the first half to position 0 of the list created from the second half.
# [[-3, -2, 2, 6, 7], 10, 12, 19, 32, 54, 98]
Final = []
x = [19,2,54,-2,7,12,98,32,10,-3,6]
x = sorted(x)
# print x
NewBeg = x... |
ex1 = ["potatoes", 25, "explaining fast","turkey day",45,30]
ex2 = ["potatoes","explaining fast","turkey day"]
ex3 = [25,45,30]
def typeCheck(ex_list):
listLength = len(ex_list) #length of list input
tempType = type(ex_list[0]) #check data type of list input at index 0
print tempType
typeFind ="" #unde... |
name="Jack"
print(name)
name="angela"
print(name)
name=input("What is your name?")
length=len(name)
print(length) |
print("Welcome!!")
height = int(input("What is your height in cm? "))
if height >=120:
print("You can ride the rollercoster")
else:
print("Sorry!!") |
# БСБО-05-19 Салынь Даниил Леонидович
ru_alphabet = list("абвгдеёжзийклмнопрстуфхцчшщъыьэюя")
ru_upper_alphabet = list("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")
def encrypt_caesar(msg: str, shift=3):
global ru_alphabet
global ru_upper_alphabet
list_msg = list(msg)
for i in range(len(list_msg)):
if ... |
# БСБО-05-19 Салынь Даниил Леонидович
import random
import re
ascii_lowercase = 'abcdefghijklmnpqrstuvwxyz23456789'
def generate_password(m):
password = generate_ch_password(m)
while True:
if check(password):
break
else:
password = generate_ch_password(m)
return pa... |
#БСБО-05-19 Салынь Даниил Леонидович
def month_name(month_num: int, lang: str):
if lang == "ru":
if month_num == 1:
print("Январь")
elif month_num == 2:
print("Февраль")
elif month_num == 3:
print("Март")
elif month_num == 4:
print("Апр... |
#БСБО-05-19 Салынь Даниил Леонидович
def translate(text: str):
text = text.replace("А", "")
text = text.replace("а", "")
text = text.replace("Е", "")
text = text.replace("е", "")
text = text.replace("И", "")
text = text.replace("и", "")
text = text.replace("О", "")
text = text.replace("о... |
# БСБО-05-19 Салынь Даниил Леонидович
import math
def find_farthest_orbit(orbits: list):
for i in orbits:
if i[0] == i[1]:
orbits.remove(i)
orbit_count = lambda x: x[0] * x[1] * math.pi
mapObj = map(orbit_count, orbits)
mappedList = list(mapObj)
return orbits[mappedList.index(m... |
import tkinter
root = tkinter.Tk()
root.geometry("300x300")
root.title("Try code")
entry = tkinter.Entry(root)
entry.pack()
print(entry.get())
def on_button():
if entry.get() == "Screen" or entry.get() == "screen": #corrected
slabel = tkinter.Label(root, text="Screen was entered")
slab... |
from turtle import Turtle
P1_POS_0 = (-350, 0)
P2_POS_0 = (350, 0)
PADDLE_STEP = 15
class Paddle(Turtle):
def __init__(self, player):
super().__init__()
self.shape("square")
self.penup()
self.color("white")
self.score = 1
self.shapesize(5, 1)
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:42:35 2021
@author: Nils
"""
import bluetooth
def goright():
print("I'm going right")
def goleft():
print("I'm going left")
def forward():
print("I'm vrroooming forward")
def back():
print("BEEEP BEEEEEEP B... |
#!/usr/bin/env python
"""
A class containing all enums related to pitches, keys and relative keys as well as ways to compute them easily.
"""
from typing import Union
class MeasureException(Exception):
"""
An exception for when a key is invalid
"""
class MR(object):
"""
An class for measure numb... |
import numpy as np
import matplotlib.pyplot as plt
distance_measurements = (38.91, 37.14, 38.19, 41.03, 34.86, 37.33, 35.16, 37.96, 36.93, 40.41, 29.50, 37.33, 41.84, 37.53, 34.12, 34.11, 37.94, 34.43, 36.68, 41.31, 39.61, 35.48, 34.98, 39.05, 39.62, 37.96, 39.02, 37.47, 33.76, 36.51) #List of distance measurements da... |
"""
Solutions to the programming problems from quiz #7.
Author: Henry Lefkowicz
Date: 29/03/2020
"""
def count_cheeseburgers(filename):
"""Returns the number of lines in the file that start with the word
cheeseburger.
Parameters:
filename - the name of the file to be read (a string)
Return... |
#Import Modules
import os
import csv
#Start Stat Tracking Variables
month_count=0
total_profit_loss=0
max_profit=0
min_profit=0
total_change=0
change=0
last_month=0
#Import Budget Data
csv_name = "budget_data.csv"
with open(csv_name) as csvfile:
budget_data = csv.reader(csvfile, delimiter=',')
header=next(bud... |
########################################
##
## introductie code python
#### data types ##############################
#### integer and doubles
# this is by default a integer
x = 9
x = 9.
type(x)
x = 7
y = 2
# default operations work between integers and doubles
9 + 9.
7/3
7/3.
x/y
# integer division and modu... |
'''Faça um Programa que peça um número e então mostre a mensagem
O número informado foi [número].'''
number = int(input())
print(f'The number informed was {number}')
|
'''Faça um Programa que peça a temperatura em graus Celsius,
transforme e mostre em graus Farenheit.'''
from decimal import Decimal, getcontext
# Números com 2 casa de precisão
getcontext().prec = 4
degreesC = float(input('Celsius: '))
degressF = (Decimal(degreesC * 1.8) + 32)
print(f'Farenheit: {degressF}F') |
from turtle import Turtle
START_POS = (-260, 260)
FONT = ("arial", 14, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("darkslateblue")
self.penup()
self.hideturtle()
self.setposition(START_POS)
self.level = 0
def write_le... |
# funkcja która zwraca sumę i testy do niej
def add(x, y):
return x + y
# funkcja która zwraca iloczyn i testy do niej
def product(x, y):
return x * y
# fukcja która odwraca napis
def words(string):
return string[::-1]
def sq(n):
return n**2
# fukcja która sprawdza czy slowo jest palindromem
de... |
<<<<<<< HEAD
#exercise 19
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print ("You have %d cheeses!" % cheese_count)
print ("You have %d boxes of crackers!" % boxes_of_crackers)
print ("Man that's enough for a party!")
print ("Get a blanket.\n")
print ("We can just give the function number... |
<<<<<<< HEAD
#exercise 4
cars=100
space_in_a_car=4.0
drivers=30
passenger=90
cars_not_driven=cars - drivers
cars_driven=drivers
carpool_capacity=cars_driven * space_in_a_car
average_passenger_per_car=passenger / cars_driven
print ("There are", cars, "cars available.")
print ("There are only", drivers, "drivers availab... |
import numpy as np
def sigmoid (x) :
return 1 / (1 + np.exp(-x))
training_inputs = np.array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])
training_outputs = np.array([[0,1,1,0]]).T
np.random.seed(1)
synaptic_weights = 2 * np.random.random((3,1)) - 1
print("Случайные инициализирующие веса:")
print(synaptic_weights)
# м... |
from random import randint, choice
import sqlite3
from datetime import date
data_atual = date.today()
conn = sqlite3.connect('desejo.db')
cursor = conn.cursor()
#função principal de desejos
def desejos():
p5 = ['Diluc', 'Mona', 'Keqing', 'Jean']
p4 = ['Barbara', 'Fishl', 'Noele', 'Razor']
p3... |
#Sets - blazingly fast unordered Lists
friends = ['John','Michael','Terry','Eric','Graham']
friends_tuple = ('John','Michael','Terry','Eric','Graham')
friends_set = {'John','Michael','Terry','Eric','Graham','Eric'}
my_friends_set = {'Reg','Loretta','Colin','Eric','Graham'}
print(friends_set.intersection(my_friends_s... |
print('Guessing game')
# Guess the correct number in 3 guesses. If you don’t get it right after 3 guesses you lose the game.
# Give user input box: 1. To capture guesses,
# print(and input boxes) 1. If user wins 2. If user loses
# Tip:( remember you won’t see print statements durng execution, so If you want to see ... |
# The split() method splits a string into a list.
# syntax: string.split(separator, maxsplit)
msg ='Welcome to Python 101: Split and Join'
csv = 'Eric,John,Michael,Terry,Graham'
friends_list = ['Eric','John','Michael','Terry','Graham']
print(msg.split())
print(msg.split(' '), type(msg.split(' ')))
print(csv.split... |
from random import randrange as r
from time import time as t
num_questions = int(input("Quantas perguntas você quer responder?"))
max = int(input("Maior número a ser usado para as perguntas"))
score = 0
ans_list = []
start_t = t()
for n in range(num_questions):
num1, num2 = r(1,max+1), r(1,max+1)
r_ans = n... |
my_list = [1,5,3,7,2]
my_dict = {'car':4,'dog':2,'add':3,'bee':1}
my_tuple = ('d','c','e','a','b')
my_string = 'python'
# print(my_list,'original')
# print(my_list.sort())
# print(my_list,'new')
# [1, 5, 3, 7, 2] original
# None
# [1, 2, 3, 5, 7] new
# print(my_list,'original')
# print(my_list.reverse())
# print(my_... |
lista = [1,5,3,7,2]
dicionario = {'car':4,'dog':2,'add':3,'bee':1}
print(lista.sort()) #None
print(lista,'sort') #[1, 2, 3, 5, 7] sort
print(lista.reverse()) #None
print(lista,'reverse') #[7, 5, 3, 2, 1] reverse
print(list(reversed(lista))) #[1, 2, 3, 5, 7]
print(lista[::-1]) #[1, 2, 3, 5, 7]
print(sorted(lista)) #[1,... |
from dataclasses import dataclass, field
@dataclass
class Employee:
"""
Employee(id, first_name, middle_name, surname, acct_balance)
"""
id: int
first_name: str
middle_name: str
surname: str
acct_bal: int
_email: str = field(repr=False, init=False)
def __post_init__(self):... |
def main():
from math import sqrt
import math
a=4
b=5
operacion1= 2*(3/4)+4*(2/3)-3*(1/5)+5*(1/2)
operacion2= (2*35)+(4*((36**3)**.5))-(6*49)
operacion3= (a**3+2*b**2)/(4*a)
operacion4= ((2*((a+b)**2))+(4*((a-b)**2)))/((a*b)**2)
operacion5= ((((a+b)**2)+(2**(a+b)))**.5)/(((2*a)+(2*b)... |
values = range(5)
for x in values:
print("Item is available")
else:
print("Item not available") |
group = [1, 2, 3, 4]
search = int(input("enter the search group element: "))
for element in group:
if search == element:
print("the element is found")
break
else:
print("element not found") |
num = 1
while num <= 5:
print(num)
num+= 1
print("end") |
x = 6000
y = 3000
z = y//x
print(z)
if(z<0):
print("the number is positive")
elif(z>0):
print("the number is negative")
else:
print("the number is devcimal")
print("ENter the values from 0 to 5")
a = int(input("enter the number"))
if a == 0:
print("entered value is :", a)
elif a == 1:
print("enter... |
# Escribimos funciones con el nombre test_ALGO
from intervalo import *
import numpy as np
def test_adicioAn():
a = Intervalo(1, 2)
b = Intervalo(2, 3)
c = a + b
# Quiero checar que c, definido asi, esta bien:
assert c.lo == 3 and c.hi == 5
def test_multiplicacion():
# Test de la multiplicac... |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
count=0
sconf=0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
sconf=sconf+float(line[line.find('.'):].rstrip())
count=count+1
print("Average spam confidence:",sconf/cou... |
from pygame import Surface, Rect
from hanoi.constants import *
class Tower(list):
def __init__(self, n):
left = SCREEN_HMARGIN + TOWER_MARGIN * (n * 2 + 1) + TOWER_WIDTH * n
top = SCREEN_VMARGIN
self.rect = Rect(left, top, TOWER_WIDTH, TOWER_HEIGHT)
def draw(self, screen):
po... |
import sys
if __name__ == '__main__':
sample_str = sys.argv
if len(sample_str[1]) > 2:
print(sample_str[1][:2] + sample_str[1][-2:])
if len(sample_str[1]) == 2:
print(sample_str[1][:2] + sample_str[1][-2:])
if len(sample_str[1]) < 2:
print('EMPTY STRING')
|
# TASK 1
from datetime import date
name = input("Hi, what's your name?\n")
today = date.today()
print('Nice to meet you!')
print(f"Good day {name}! {today} is a perfect day to learn some python.")
print('-' * 100)
# TASK 2
name1 = 'Ilya Pasichnyk'
name_first = name1[:4]
name_last = name1[5:]
print('So you are %s %... |
class Author:
def __init__(self, name, country, birthday):
self.name = name
self.country = country
self.birthday = birthday
self.books = []
def __repr__(self):
return f'{self.name} - was born in {self.country} on {self.birthday}\nHe is author of those books - {self.book... |
import pygame, sys, random
def ball_animation():
global ball_speed_x, ball_speed_y, player_score, opponent_score, score_time
ball.x += ball_speed_x
ball.y += ball_speed_y
#making barriers for the ball to be in
if ball.top <= 0 or ball.bottom >= screen_height:
ball_speed_y *= -1
... |
#!/usr/bin/env python3
import os
from makeConnection import connectThenExecute
def searchAgeRange():
minAge = input("\n Enter Minimum Age: ")
maxAge = input(" Enter Maximum Age: ")
# Clear the terminal screen
os.system('cls' if os.name == 'nt' else 'clear')
print("\nSearching by age 'BETWEEN {} AND {}'..... |
# 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.
s=0
for i in xrange(1,1000):
if not (i%3):
s += i
elif not (i%5):
s += i
print s
|
from tkinter import Tk
from tkinter import Canvas
def move():
global Dx,Dy
x1,y1,x2,y2=w.coords(id1)
if x1+Dx<=0 or x1+Dx>=190:
Dx=-Dx
if y1+Dy<=0 or y1+Dy>=190:
Dy=-Dy
w.coords(id1,x1+Dx,y1+Dy,x2+Dx,y2+Dy)
root.after(10,move)
root=Tk()
w = Canvas(root, width=200, height=200,
... |
"""
=================== TASK 2 ====================
* Name: Even and Odd Numbers
*
* Write a script that will populate list with as
* many elements as user defines. For taken number
* of elements the script should take the input from
* user for each element. You should expect that user
* will always provide integer... |
"""
title:http://www.doutula.com/
author:zhangyi
test_____
采用自动化运维的方式,提取(多线程)
流程:
1.进入主界面,在search_input输入自定义文字,按下button,进入下一界面
2.(进入该网页没有分页,必须先点击'查看更多')获取相应页码
3.获取(每一页)每一张的图片地址(作为一个集合)
4.启用多进程池
5.下载每一张图片,并保存至不同文件夹(以格式分类)
6.退出
"""
from bs4 import BeautifulSoup #美味的汤
fr... |
# Andrei's Python Guessing game code
from random import randint
import sys
# generate a number 1~10
answer = randint(1, 10)
def validate_user_input(guess, answer):
if 0 < guess < 11:
if guess == answer:
print('you are a genius!')
return True
else:
print('hey bozo, I sa... |
#!/usr/bin/env python
from __future__ import division
import time
import math
import primefac
from itertools import count
"""
Investigating multiple reflections of a laser beam
Problem 144
In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam.
The beam enters the cell, ... |
#!/usr/bin/env python
import time
import primefac
import math
import itertools
"""
Consecutive prime sum
Problem 50
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest su... |
#!/usr/bin/env python
import time
import primefac
"""
Distinct primes factors
Problem 47
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 * 7
15 = 3 * 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 22 * 7 * 23
645 = 3 * 5 * 43
646 = 2 * 17 ... |
import numpy as np
class Polygon(object):
def __init__(self, points: list):
self.points = points
def __repr__(self):
return '{} Poly: {}'.format(len(self.points), self.points)
def calc_poly_intersection(first: Polygon, second: Polygon):
pass
def calc_plane_equation(points: Polygon):
... |
## Name: Jesus Ivan Gonzalez
## Create Date: August 15th 2015
## Description: Script opens stopwatch.txt (contains start/stop/elasped times). If not,
## it creates one. Requires user to start & stop internal timer, saves times
## to stopwatch.txt for future referen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/7 下午9:07
# @Author : Lucas Ma
# @File : retFunc
'''
返回函数
'''
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f1 = lazy_sum(1, 3, 5, 7, 9)
f2 = lazy_sum(1, 3, 5, 7... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/11 下午8:33
# @Author : Lucas Ma
# @File : defunc
# 自定义函数
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
print(my_abs(-9))
# 如果想定义一个什么... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/13 上午11:22
# @Author : Lucas Ma
# @File : slice
#
# slice demo
# 取一个list或tuple的部分元素是非常常见的操作。比如,一个list如下:
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
# 取 L 的前三个元素 0,1,2
print(L[:3])
# 取倒数两个元素
print(L[-2:])
# 取倒数第二个元素
print(L[-2:-1])
# 创建一个... |
#-*- coding: utf8 -*-
# 두 수를 더한다.
x = 4
y = 5
z = x + y
print("Output #2: Four plus five equals {0:d}.".format(z))
# 두 리스트 더한다.
a = [1, 2, 3, 4]
b = ["first", "second", "third", "fourth"]
c = a + b
print("Output #3: {0}, {1}, {2}".format(a, b, c))
|
# 집합 축약을 이용하여 리스트의 고유한 튜플 집합을 고르기
my_data = [(1,2,3), (4,5,6), (7,8,9), (7,8,9)]
set_of_tuples1 = {x for x in my_data}
print("Output #131 (set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data)
print("Output #132 (set function): {}".format(set_of_tuples2))
|
# split
string1 = "My deliverable is due in May"
string1_list1 = string1.split()
string1_list2 = string1.split(" ", 2)
print("Output #21: {0}".format(string1_list1))
print("Output #22: FIRST PIECE:{0} SECOND PIECE:{1} THIRD PIECE:{2}"\
.format(string1_list2[0], string1_list2[1], string1_list2[2]))
string2 = "Your,del... |
# replace
string5 = "Let's replace the spaces in this sentence with other characters."
string5_replace = string5.replace(" ", "!@!")
print("Output #32 (with !@!): {0:s}".format(string5_replace))
string5_replace = string5.replace(" ", ",")
print("Output #33 (with commas): {0:s}".format(string5_replace))
|
# 리스트를 만들기 위해 대괄호를 사용한다.
# len() 함수를 통해 리스트 내 원소의 수를 센다.
# max() 함수와 min() 함수는 최대/최소 값을 찾는다.
# count() 함수는 리스트 내 특정 값이 등장한 횟수를 센다.
a_list = [1, 2, 3]
print("Output #58: {}".format(a_list))
print("Output #59: a list has {} elements.".format(len(a_list)))
print("Output #60: the maximum value in a_list is {}.".format(max(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.