text stringlengths 37 1.41M |
|---|
# 引入BeautifulSoup
from bs4 import BeautifulSoup
# 读取MySoup.html文件
Open_file = open('MySoup.html', 'r', encoding='utf-8')
# 将MySoup.html的内容赋值给Html_Content,并关闭文件
Html_Content = Open_file.read()
Open_file.close()
# 使用html5lib解释器解释Html_Content的内容
soup = BeautifulSoup(Html_Content, "html5lib")
# 输出title
print('html title is... |
import re
text = "This is the last one"
res = re.match('(.*) is (.*?) .*', text, re.M | re.I)
if res:
print("res.group() : ", res.group())
print("res.group(1) : ", res.group(1))
print("res.group(2) : ", res.group(2))
print("res.groups() : ", res.groups())
else:
print("No match!!")
|
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/8/10 11:47
# filename: traverse1.py
import os, os.path
def traverse(pathname):
for item in os.listdir(pathname):
fullitem = os.path.join(pathname, item) # 将父目录和当前项拼接起来,获得文件全名
print(fullitem)
if os.path.isdir(fullitem... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
'''
object.__getattr__(self, name)
找不到attribute的时候,会调用getattr,返回一个值或AttributeError异常。
object.__getattribute__(self, name)
无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)
'''
class User:
def __init__(self, info={}):
self.inf... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '18793'
list1 = ["apple", "banana", "grape", "orange", 'C']
print(list1.index("apple")) # 打印apple的索引
print(list1.index("orange")) # 打印orange的索引
print("orange" in list1) # 判断orange是否在列表中
list1.sort() # 排序
print("Sorted list :", list1)
list1.reverse() # 反转... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
class Sample:
def __enter__(self):
print("in __enter__")
return "Foo"
def __exit__(self, exc_type, exc_val, exc_tb):
print("in __exit__")
def get_sample():
return Sample()
with get_sample() as sample:
print("Sample: ", sample)
'''
整个运行... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
hu = eval('3+4') # 将字符串当表达式求值 得到7
print(hu)
exec('a=100')
print(a)
s = "for i in range(0,10):print(i)"
c = compile(s,',',"exec")
exec(c)
x=3
y=4
s2 = "3*x+4*y"
c2 = compile(s2, '', 'eval')
result = eval(c2)
print(result) |
#!/usr/bin/env python
#-*- coding:utf8 -*-
from multiprocessing import Process
g_num = 100
def plus():
print("-----子进程1开始-----")
global g_num
g_num += 50
print("g_num is %d " % g_num)
print("------子进程1结束-----")
def minus():
print("-----子进程2开始-----")
global g_num
g_num -= 50
print(... |
#个性化异常处理
x=input("输入0-4会有异常:")
if x not in ['0','1','2','3','4','5']:
print("本次没有发生异常。程序结束。")
import sys
sys.exit(0)
else:
try:
triger=int(x)
if triger==0:
e=1/0
if triger==1:
a=[1,2,3,4,5,6]
print(a[6])
if triger==2:
a='2'+... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/9/8 21:17
# filename: 08.小试牛刀.py
num_list = [5, 0, 73, 0, 16]
class ExceptionNum(object):
def __init__(self):
pass
@staticmethod
def num_operation():
# 正常数数组
normal_num_list = list()
# 异常数数组
... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/10/28 14:50
# filename: 02.短路冒泡排序.py
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i] > alist[i + ... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/8/5 17:56
# filename: 11.创建简单的绘图实例.py
import tkinter
class MyButton:
def __init__(self, root, canvas, label, type):
self.root = root
self.canvas = canvas
self.label = label
if type == 0: # 根据类型创建按钮
... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
class INIT_class:
def __init__(self, x, y=0):
self.x = x
self.y = y
def mycalc(self):
return self.x + self.y
diaoyong1 = INIT_class(2)
print("调用myclac方法1")
print(diaoyong1.mycalc())
print("".center(100, "*"))
print("调用myclac方法2")
diaoyong2 =... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
class Ant:
def __init__(self, x=0, y=0, color="black"): #定义构造方法,将实例属性和参数一一绑定
self.x = x
self.y = y
self.color = color
def crawl(self,x,y):
self.x = x
self.y = y
print("爬行....")
self.info()
def info(self):
... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
class Dog(object):
def say(self):
print("a dog")
class Cat(object):
def say(self):
print("a cat")
class Duck(object):
def say(self):
print("a duck")
# animal_list = [Dog, Cat, Duck]
#
# for animal in animal_list:
# animal().say()
de... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/7/28 12:51
# filename: 03.保留最后 N 个元素.py
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
#属性描述符
import numbers
#只要一个类实现了下面三种魔法函数中的一种,这个类就是属性描述符
class IntField:
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
if not isinstance(value,numbers.Integral):
raise ValueError("必须为int")
... |
#!/usr/bin/env python
#-*- coding:utf8 -*-
'''
值传递 ----> 不可变对象
引用传递 -----> 可变对象
'''
def deam(obj):
print("原值:", obj)
obj +=obj
#调用函数,值传递
print("="*10,"值传递","="*10)
mot = "唯有在追赶的时候,你才能真正的奔跑" #不可变对象
print("函数调用前:",mot)
deam(mot)
print("函数调用后:",mot)
print("="*10,"引用传递","="*10)
list = [1,2,3,4,5,6] ... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/6 15:19
# filename: 异常else语句.py
import datetime as dt
def read_date_file(filename):
try:
with open(filename) as file:
in_date = file.read()
in_date = in_date.strip()
date = dt.datetime.strptime(in... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/14 13:59
# filename: 使用metaclass.py
# metaclass类的__new__方法的作用就是:当丞相使用class定义新类时,如果指定了metaclass,那么metaclass的__new__方法就会被自动执行
class ItemMetaClass(type):
def __new__(cls, name, bases, attrs):
# 为该类动态添加一个cal_price方法
attrs['cal_p... |
#冒泡排序
showDebug=int(input("打印调试信息吗?【1】是;【0】否:"))
def bubbleSort(arr):
"""冒泡排序"""
for i in range(len(arr)-1):
for j in range(len(arr)-1-i):
if(arr[j] < arr[j + 1]):
arr[j],arr[j+1]=arr[j+1],arr[j]
if showDebug==1:print("(调试信息)第",i+1,"轮:",arr)
return arr
#列表构造器
def... |
inputList = list()
with open('input.txt') as f:
read_data = f.read()
inputList = read_data.split("\n")
valid = 0
for item in inputList:
parts = item.split(" ")
ranges = parts[0].split("-")
lower = int(ranges[0]) - 1
upper = int(ranges[1]) - 1
character = parts[1][0]
string = parts[2]
... |
"""
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree
Date: 2017 April 30
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node i... |
#!/usr/bin/python3
total=0
mass=open("input.txt", "r")
for line in mass:
total+=int(int(line)/3)-2
print(total)
|
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('python tkinter')
alabel=ttk.Label(root,text='Enter a Name')
alabel.grid(column=0,row=0)
def clickMe():
file_name=name.get()
with open(file_name) as file:
f=file.read()
action.configure(text=f)
alabel.configure(foreground='... |
from random import uniform, choice
from typing import Union, Tuple, List
class Ball:
def __init__(self, game, radius, speed):
self._game = game
self._speed = speed
self._radius = radius
self.__dx = 0
self.__dy = 0
self.__x = game.width / 2 - self._radius
sel... |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
# print("Hello World")
# x = 5
# print(x)
# weapons = ['sword', 'gun', 'knife']
# print(weapons)
# class Person:
# def __init__(self, name, age):
# self.name = name
# self.age = a... |
'''
Collection of utils used for displaying sacred results in notebooks.
'''
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as sts
'''
This function creates a plot in the given axis. This plot shows, for a certain
specified metric, the mean and the confidence interval of the metric ... |
#!/usr/bin/env python3
def DoTwo(num1,num2):
b=num1+7
print (b,num2,(b+num2),(num1+num2)) #Lol
print("End of function")
#первая строка указывает что нужно компилировать при помощи интерпритатора питон3
print ("Hello World!!!")
name = input("What is your name?\n")
strng = 'Nikita'
print(strng*5)
print("printf")
var ... |
""" Python program to encrypt and decrypt text in an image.
The top left 5 pixels and bottom right 5 pixels will be WHITE BLACK WHITE BLACK WHITE iff the image is encrypted.
The 6th top left pixel holds the row number from which the encryption starts
The 7th top left pixel holds the spacing value. So if the value is ... |
from random import randint
# Fermat's Little Theorem
def isPrime(n):
return pow(2, n-1, n) == 1
if __name__=='__main__':
prime1, prime2 = False, False
while not prime2:
select = randint(10000000,20000000)
prime1 = isPrime(select)
if prime1:
p = (2*selec... |
def lettersInString(stringPassed):
numberLetters = 0
for i in range(len(stringPassed)):
if (ord(stringPassed[i]) >= 65 and ord(stringPassed[i]) <= 90) or (ord(stringPassed[i]) >= 97 and ord(stringPassed[i]) <= 122):
numberLetters += 1
return numberLetters
print(str(lettersInString("--"))) |
#Código para demonstrar o funcionamento de uma lista de adjacencias
def inicializar_lista():
for i in range(vertices):
grafo.append([])
def mostrar_grafo():
for i in range(vertices):
print(i+1, ' : ', grafo[i])
def mostrar_grafo_detalhado():
for i in range(vertices):
print('')
... |
import socket
from graphical_widgets import ExternalWindows
# Here we have the connection class! It is responsible for starting the connection with the server
# It also does the message sending and receiving part (handles all messages)
class MConnection:
# Here we have the first part, we start the program by usin... |
# SIMPLE TRIANGLE PATTERN
n=int(input("Enter the number of rows: "))
#NESTED FOR LOOP
for i in range(0,n):
for j in range(0,i+1):
print("* ",end="")
print("\n")# WE USE PRINT TO CHANGE LINE IN THIS APPROACH
#ANOTHER WAY OF FOR NESTED LOOP
# for i in range(0,n): # Outer loop for rows
# star=""
# for... |
#NUMERICAL PATTERN
n=int(input("Enter the number of rows: "))
for i in range(0,n):
for j in range(1,i+2):
print(f"{j} ",end="")
print("\n") |
print("\t Even Odd Test\n ")
print("Enter the no to be tested: ")
no= int(input())
if no%2==0:
print(f"{no} is Even")
else:
print(f"{no} is Odd")
|
word = input()
fav_num = input()
fav_lett = input()
if len(fav_lett) == 1:
if fav_num.isdigit():
fav_num = int(fav_num) - 1
if len(word) >= fav_num:
if word[fav_num] == fav_lett:
print("ДА")
else:
print("HET")
else:
print("... |
def roots_of_quadratic_equation(a, b, c):
roots = set()
if a == 0 and b == 0:
return ["all"] if c == 0 else ["false"]
elif a != 0:
if b != 0:
d = (b**2) - 4 * a * c
if d < 0:
return ["no valid roots (only complex)"]
roots.add((- b + d **... |
def encrypt_caesar(msg, shift):
shift = shift if str(shift.__class__) == "<class \'int\'>" and shift > 0 else 3
encrypted_msg = ""
for i in msg:
encrypted_msg += chr(((ord(i) % 1072 + shift % 32) % 32) + 1072) if i.islower() else \
chr(((ord(i.lower()) % 1072 + shift % 32)... |
def ask_password():
password = "password"
attempts = 0
for i in range(3):
user_pass = input()
if user_pass != password:
attempts += 1
else:
print("Пароль принят")
return 0
print("В доступе отказано")
ask_password() |
import re
def insert_dash(string, index, insert):
return string[:index] + insert + string[index:]
def space_deleter(line):
if " " in line:
spaces = []
regex = re.findall(r"[ ]+", line)
for r in regex:
spaces.append(str(r))
temp = " ".join(line.split())
if ... |
from dinosaurs import Dinosaur
from robots import Robot
from fleet import Fleet
from herd import Herd
class Battlefield:
def __init__(self):
self.fleet = Fleet
self.herd = Herd
def run_game(self):
print(
"Welcome to Robos vs Dinos! Where a fleet of Robots are set to fight ... |
#!/usr/bin/env python3
a = int(input('Number A?'))
b = int(input("Number B?"))
answer = a + b
print(answer) |
def thousand_number_separator(number) :
string = ""
counter = 0
for i in range(len(str(number))-1,-1,-1):
if counter % 3 == 0 and i != len(str(number))-1 :
string = "," + string
string = str(number)[i] + string
counter += 1
return string
print(thousand_number_separator(131312)) |
from flask import Flask
# create instance of the app
app = Flask(__name__)
@app.route('/')
def homepage():
return 'Homepage of Flask Calc'
# math = {
# 'add': lambda x, y: x + y,
# 'sub': lambda x, y: x- y
# }
# make a dictionary then return it in the
# results = math[oper](num1,num2)
# return str(resul... |
import numpy as np
import matplotlib.pyplot
def predict(X, theta):
return np.dot(X, theta)
def muSigma(X):
return (np.mean(X,axis=0), np.std(X,axis=0))
def zScore(X, mu, sigma):
return np.divide((X - mu), sigma)
def computeCost(X, y, theta):
m = len(y)
h = predict(X, theta)
di... |
from typing import Dict
from typing import List
from typing import NamedTuple
from typing import Union
class Passport(NamedTuple):
byr: int # (Birth Year)
iyr: int # (Issue Year)
eyr: int # (Expiration Year)
hgt: str # (Height)
hcl: str # (Hair Color)
ecl: str # (Eye Color)
pid: str ... |
import random # This will bring the randomizer function within this code and it would be used later
import Left_Path # Imports the Left_Path file
from Left_Path import * # Imports everything from the Left_Path
import right_path # Imports the Right_Path file
from right_path import * # Imports everything from ... |
#!/usr/bin/python
# -*- encoding: utf8 -*-
import numpy as np
def accuracy(label, score):
'''
This method accepts a true label and its associating predicted score to
computer the prediction accuracy
params:
label: the true labels of the sample
score: the predicted scores that is used... |
from random import randint
def partition(arr,pivot_loc,si,ei):
j=si-1
for i in range(si,ei):
#print "current:%d"%arr[i]
#print "pivot:%d"%arr[pivot_loc]
#print "current j=%d"%j
if(pivot_loc==i):
i=i+1;
else:
if arr[i]<=arr[pivot_loc]:
... |
def LinearSearch(arr, n, x):
for i in range(n):
if arr[i] == x:
return i
return -1
arr = [12,56,89,59,45]
n = len(arr)
x = 89
search = LinearSearch(arr, n, x)
if search == -1:
print("not found!")
else:
print("fount at index: ",search)
# TC = O(n)
|
# TC of Linear search is O(n)
# Now for worst case-
# for last element write in O(1)
# for not found write in O(n/2)
def LinearSearch(arr, n, x):
left = 0
right = n-1
position = -1
while left <= right:
if arr[left] == x:
position = left
print("found at inde... |
# works on sorted array
# Exponential search involves two steps:
# Find range where element is present
# Do Binary Search in above found range.
def BinarySearch(arr, l, r, x):
if l <= r:
mid = int(l + (r-l)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
... |
''' The expression tree is a binary tree in which each internal node corresponds
to the operator and each leaf node corresponds to the operand '''
''' Inorder traversal of expression tree produces
infix version of given postfix expression
(same with postorder traversal it gives prefix expression) '''
class No... |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def inOrder(root):
if root:
inOrder(root.left)
print(root.data,end=" ")
inOrder(root.right)
def preOrder (root):
if root:
print(root.data,end=" ")
... |
class Node:
def __init__(self,data):
self.data = data
self.left = self.right = None
def SortedArrayToBalancedBST(arr) :
if not arr:
return None
mid = int(len(arr)/2)
root = Node(arr[mid])
root.left = SortedArrayToBalancedBST(arr[:mid])
root.right = SortedA... |
''' Given a 2D screen, location of a pixel in the screen and a color,
replace color of the given pixel and all adjacent same colored pixels
with the given color.
'''
def isValid(x,y,n,m):
return x >= 0 and x < n and y >= 0 and y < m
def BFS(screen,x,y,color,n,m):
visited = [[False for col in rang... |
# method 2 - Recursive Approach
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.he... |
class Node:
def __init__(self,data):
self.data = data
self.left = self.right = None
def getPreIndex():
return constructTreeUtil.preIndex
def incrementPreIndex():
constructTreeUtil.preIndex += 1
def constructTreeUtil(pre,low,high,size):
if (getPreIndex() >= size or low > hi... |
''' You are given n pairs of numbers. In every pair, the first number is always smaller
than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain
of pairs can be formed in this fashion. Find the longest chain which can be formed
from a given set of pairs.
'''
''' Bottom Up Approach - Tab... |
from random import randint
i = 0
MIN = 0
MAX = 99
number = randint(MIN, MAX)
guessed = False
print "We have generated the integer number between " + str(MIN) + " and " + str(MAX) + ". Please try to guess it.\r\n"
while not guessed:
i += 1
try:
guess = int(raw_input('Enter your guess: '))... |
"""
<369게임>
게임이 끝난 숫자 N이 주어졌을 때
N이전까지 박수를 친 횟수를 구하여라
input -> output
10 -> 3
35 -> 15
"""
# -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
user_input = input() #N
count=0
for k in range(1,int(user_input)): #1-user_input까지 숫자 반복 , k=int
a=str(k) # k를 문자열로 만들기
for i in a: # 문자열 순서대로 탐색
#i자리의 값... |
######## Aug 16, 2015 ########
######## Umesh Singla ########
import pygame
import level
from pygame.locals import *
pygame.init() #initialise pygame to initialise pygame.font and others
class Board(object):
#screen dimensions
screen_height = 690
screen_width = 640
border_width = 12
gap = ... |
"""
This is an exercise in file analysis. Fundamentally it is an exercise in the use of the basic collection objects in
Python such as strings, lists, tuples, dictionaries and sets.
We are going to use Abraham Lincoln's Gettysburg address of 1863, This is famous for many things, including for being a
short speech.
TA... |
start = "Welcome to Mall of America! You have a big day of shopping ahead of you. But keep in mind, you only have $125 in your wallet. As soon as you walk in, you walk past Lord & Taylor and spot a dress that you love. The price tag reads $50. Would you like to buy it?"
shoe_message = "You walk out of Lord & Taylor and... |
#!/bin/bash/python
number = 15
running = True
while running:
guess = int(raw_input('Enter an integer ' ))
if guess == number:
print 'Congratulation, you guessed it.'
running = False
elif guess<number:
print 'No,it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print '... |
import requests
import json
""" Used to create a new empty playlist ready to accept 'mixed' songs.
This function simply creates a new playlist for the program to access
later when adding the 'mixed' songs. Returns a playlist id.
Ex:
create_playlist(base_playlist_name,username,token)
"""
def create_playlist... |
from rand_string import rand_string
from Population import Population
from Evaluator import Evaluator
from Parents import Parents
from EnuBubbleSort import (
bubble_sort,
) # ?? Is the syntax for importing a function from a .py file the same as the syntax for importing a class from a .py file?
from crossover impor... |
# -*-coding:Utf-8 -*
annee = input("year: ")
try: # On essaye de convertir l'année en entier
annee = int(annee)
print(annee)
except:
print("Erreur lors de la conversion de l'année.")
try:
resultat = numerateur / denominateur
except NameError:
print("La variable numerateur ou denominateur n'a pas... |
b = 7
var = 4
a = 5
def print_a():
"""Fonction chargée d'afficher la variable a.
Cette variable a n'est pas passée en paramètre de la fonction.
On suppose qu'elle a été créée en dehors de la fonction, on veut voir
si elle est accessible depuis le corps de la fonction"""
print("La variable a = {0}... |
from time import sleep
n = 0
while n < 38:
print("13 x",n,"= ",13*n) # print the thirteen-times table
n = n+1
sleep(0.5)
print(f"n now has value {n} and our program is complete!") |
myList = [1,2,3,4]
factor = 3
newList = []
for num in myList:
newList.append(num * factor)
|
name = 'Ariel'
if name == 'Ariel':
print('YES these strings are the same.')
if name != 'Yolanda':
print('NO these strings are different.') |
good = .2
fair = .15
bad = .1
bill_amount = input('How much was the bill?\n')
service_quality = input('How good was the service? Select \'Good\', \'Fair\', \'Bad\'.\n')
bill_amount = int(bill_amount)
if service_quality == 'Good':
tip_amount = bill_amount * good
elif service_quality == 'Fair':
tip_amount = bi... |
myListOfNames = ['Ariel', 'Pandora', 'Elizabeth', 'Scarlett', 'Robert']
myListOfNames[2] = 'foo'
myListOfNames[4] = 'bar'
print(myListOfNames)
myListOfNames[2:3] = ['Alex', 'Jacob']
print(myListOfNames) |
sum_of_even_terms = 0
fib1 = 0
fib2 = 1
term = 0
while term < 4000000+1:
term = fib1 + fib2
if term % 2 == 0:
sum_of_even_terms += term
fib1 = fib2
fib2 = term
print(sum_of_even_terms)
|
import matplotlib.pyplot as plt
import numpy as np
#Todo:
# 1) Think about a way to make the class work with Costas Sequences
# that aren't one based. Maybe scale them?
# 2) Extend the methods to account for Sonar Sequences and Costas sequences
# whose image is not [n], for example (1,2,4). The show fails for t... |
import pygame
class Rocket():
def __init__(self, screen):
"""Initialize the rocket and its starting position."""
self.screen = screen
# Load the rocket image and get its rect.
self.image = pygame.image.load('images/rocket.bmp')
self.rect = self.image.get_rect()
sel... |
import os
import shelve
import shutil
myFile = open('.\\workingwithfiles.txt')
print(myFile.read())
myFile.close()
#you can only read a file once, have to close and reopen to read again so put in variable instead
myFile = open('.\\workingwithfiles.txt')
myFileRead = myFile.read()
myFile.close()
print(myFileRead)
#re... |
def collatz():
numInput = input("Enter a number")
if int(numInput)%2 == 0:
print (int(numInput) // 2)
elif int(numInput)%2 != 0:
print (3 * int(numInput) + 1)
try:
collatz()
except ValueError:
print("Error: not an integer") |
"""
Library of EV3 robot functions that are useful in many different applications. For example things
like arm_up, arm_down, driving around, or doing things with the Pixy camera.
Add commands as needed to support the features you'd like to implement. For organizational
purposes try to only write methods into ... |
valor = int(input())
aux = valor
def calc(nota):
global aux
qtd = aux // nota
if(qtd > 0):
aux = aux - (qtd * nota)
print("{0} nota(s) de R$ {1},00".format(qtd, nota))
return qtd
print(valor)
calc(100)
calc(50)
calc(20)
calc(10)
calc(5)
calc(2)
calc(1) |
valor = float(input())
intervalo = ""
if(valor >= 0 and valor <= 25):
intervalo="[0,25]"
if (valor > 25 and valor <= 50):
intervalo = "(25,50]"
if(valor > 50 and valor <= 75):
intervalo="(50,75]"
if (valor > 75 and valor <= 100):
intervalo = "(75,100]"
x = "Intervalo %s" %intervalo if intervalo !=... |
input('Anyone there?')
print('hello whirled')
answer = input('did I spell that right?' )
answer = answer.lower()
if answer != 'yes' or 'no':
answer = input("I didn't understand, could you repeat that?")
if answer == 'yes':
print('Okay, thanks')
elif answer == 'no':
print('sorry, i meant to say "hello ... |
def binary_search(arr,l,n,x):
while l <= n:
m = int(l+(n-l)/2)
if arr[m] == x:
return m+1
if arr[m] < x:
l = m+1
else:
n = m-1
return -1
print('Enter the array elements')
arr_list = input().split(' ')
arr = [int(i) for i in arr_list]
print('Enter the element to be searhed')
x = int(input())
n = len(... |
def Bubble_Sort(arr,n):
for i in range(n-1):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1], arr[j]
print("The array after Bubble_Sort becomes")
for i in range(n):
print(arr[i], end=' ')
#print(int(i) for i in arr)
print("Enter the array elements")
arr = input().split(' ')
arr =... |
#encoding=utf-8
'''
Created on 2019年8月18日
@author: zhangxiao
'''
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.5,0.8,0.4],xticklabels=[],ylim=(-1.2,1.2))
ax2 = fig.add_axes([0.1,0.1,0.8,0.4],ylim=(-1.2,1.2))
x = np.linspace(0,10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x... |
#! /usr/bin/env python3
"""Database code to connect to newsdata.sql."""
import psycopg2
DBNAME = "news"
# create a function that establishes the database connection
def connect(database_name="news"):
try:
db = psycopg2.connect("dbname={}".format(database_name))
cursor = db.cursor()
retu... |
'''
Name : Xingjia Wang
Date : 10/02/2018
Project Name: PyTorch Based MNIST Demo with Linear Models
Project Description:
A simple machine learning project with a self-built neural network linear model based on the
MNIST handwritten number training (60000 samples) and testing datasets (10000 samples.) Training takes ... |
a = open('input.txt', 'r')
data = a.readlines()
a.close()
def checkTrees( goRight=3, goDown=1):
print("Check trees for: D:{} R:{}".format(goDown, goRight))
toCheck = []
x = 0
y=0
while y < len(data):
while x < len(data[x]):
toCheck.append((x,y))
x += goRight
... |
a = open('input.txt', 'r')
input = a.readlines()
a.close()
goal = 2020
print(input)
for line in input:
for line2 in input:
line = line.replace('\n', '')
line2 = line2.replace('\n', '')
#print("{}, {}".format(line, line2))
if line == '' or line2 == '':
continue
# ... |
from tkinter import *
window = Tk()
window.title("Miles to Km Converter")
window.minsize(width=250, height=250)
# Miles input box
input_box = Entry()
input_box.grid(column=2, row=1, padx=20, pady=20)
# Miles label
ml = Label(text="Miles")
ml.grid(column=3, row=1, padx=20, pady=20)
# Is equal to label
equal_to = La... |
"""
Provides the main game mechanics
"""
import math
import operations
def handle_outcome(technician, customer, queue, success, disaster, data_disasters):
"""Handle the outcomes of helpdesk interactions"""
lost = False
if success is True:
exp = customer.exp
technician.add_exp(exp)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 09:46:46 2020
@author: ash
"""
class formulaire:
def __init__(self, nom, prenom, naissance):
self.nom = nom
self.prenom = prenom
self.naissance = naissance
def _set_naissance(self, naissance):
... |
def readIntArray():
return list(map(lambda x: int(x), input().split()))
def readInt():
return int(input())
def countBottles(containerCapacity, capacitiesOfBottles):
bottlesCounter = 0
for cap in capacitiesOfBottles:
containerCapacity -= cap
if containerCapacity <= 0:
break... |
def readIntArray():
return list(map(lambda x: int(x), input().split()))
def readInt():
return int(input())
def repair(field, line, cell, size):
for i in range(size):
for j in range(size):
field[i+line][j+cell] ^= 1
def countSteps(n, m, k, field):
result = 0
for line in range(... |
import random
code = random.randrange(1 ,3)
userName = input("What is your name? ")
dict = {1 : "Rock", 2 : "Paper", 3 : "Scissors"}
print("1: Rock 2: Paper 3: Scissors")
userInput = int(input("Please select a option: "))
print("\nComputer selected: " + dict[code])
print(userName + " selected: " + dict[userInput])
if... |
import random
# Rock database list
class RockDatabase:
def __init__(self):
self.db = {}
# Debug layer
Debug = RockTableEntry("Debug", "red", "Sedimentary", 0.8)
# Building the sedimentary layers
Dolomite = RockTableEntry("Dolomite", "#5B5B50", "Sedimentary", 0.60)
... |
#
# Project Euler problem 1
# Solution written by Jennifer Ralph
#
# Function for determining the sum 1 + 2 + ... + n
def sum(n):
ans = (n*(n + 1)) / 2
return ans
# Determine the sum of integers less than or equal
# to the maximum that are a multiple of n.
# Note that n + 2n + ... + xn is equal to
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.