text stringlengths 37 1.41M |
|---|
from tkinter import *
def get_selected_row():
pass
win=Tk()
win.wm_title("My routine database")
l1=Label(win, text="Date")
l1.grid(row=0, column=0)
l2=Label(win, text="Earnings")
l2.grid(row=0, column=2)
l3=Label(win, text="Exercise")
l3.grid(row=1, column=0)
l4=Label(win, text="Study")
l4.grid(... |
import random
from timeit import default_timer
def Randomized_hiring_assistant(list,fees):
cost=int(0)
best=0
num=int()
for i in range(0,len(list)):
num=list[i]
if num>best:
best=num
cost+=fees
return (best,cost,list)
def Randomize_in_place(list,fees):
fo... |
class node:
def __init__(self,value=0,next=None):
self.value=value
self.next=next
class queue(node):
def __init__(self,head=None,tail=None):
self.head=node()
self.tail=node()
self.length=0
# operations on a queue.
# 1) Queue_empty()
# 2) Enqueue()
# 3) Deq... |
from timeit import default_timer
def Matrix_multiplication(A,B):
m3=[]
for i in range(0,len(A)):
v=[0]*len(B[0])
for j in range(0,len(B[0])):
v[j]=0
for k in range(0,len(B)):
v[j]+=int(A[i][k])*int(B[k][j])
m3.append(v)
return m3
def main():
... |
from random import choice, random, seed
seed(1211) # arbitrary seed for testing
class Board:
def __init__(self, size=4, start=(0, 0), pit_rate=0.1, gold_loc=None, wumpus_loc=None, n_wumpus=1):
"""
The board is represented as a list of lists.
Most placings are either random or intended to ... |
# Weather App that provides you the temperature and timezone details of a city on a click
from tkinter import *
import requests
import json
root = Tk()
root.title("Weather App")
root.iconbitmap('disneyland.ico')
root.geometry("600x200")
root.configure(background="White")
api_p1 = "https://api.weather... |
from re import match
def check_if_can_do_without_palette(dictionary):
if "Figures" in dictionary:
figures = dictionary["Figures"]
for elem in figures:
if "color" in elem:
if not match("[a-z]+", elem["color"]) and not match("\(\d{1,3},\d{1,3},\d{1,3}\)", elem["color"]) a... |
from numpy import array, sqrt, ones, Float
import _regress
def bistats(x, y):
"""
Basic statistics summarizing a bivariate distribution.
xbar, xstd, ybar, ystd, covar, rho = bistats(x,y)
xbar, ybar are the sample means
xstd, ystd are the sample standard deviations (with 1/n
rathe... |
n1 = float(input('Quantos reais você tem na sua carteira? '))
print('Você pode comprar {} dólares'.format(n1/3.27)) |
s = int(input('Salário do funcionário: '))
print('O salário aumentado é: {}'.format(s*1.15)) |
num = int(input('Escolha um número de 0 até 9999: '))
n= str(num)
print('Unidades: {}'.format(n[3]))
print('Dezenas: {}'.format(n[2]))
print('Centenas: {}'.format(n[1]))
print('Milhares: {}'.format(n[0])) |
d = float(input('Quantos km é a viagem? '))
if d<=200:
print('Sua viagem custará {} reais'.format(d*0.5))
else:
print('Sua viagem custará {} reais'.format(d*0.45)) |
class Person:
def __init__(self,name='', bdate='', gender=''):
self.name=name
self.bdate= bdate
self.gender = gender
def set(self,name='',bdate='', gender=''):
self.name=name
self.bdate= bdate
self.gender = gender
def get(self):
return se... |
import turtle as t
import random
import time
def message(str_up, str_down): # 위아래로 메시지 출력
player.goto(0,100)
player.write(str_up, False, "center", ("Arial", 20, "bold")) # Arial 폰트, 폰트 크기 20, 굵게, 가운데 정렬로 str_up 작성
player.goto(0,-100)
player.write(str_down, False, "center", ("Arial", 15, "normal... |
'''p.s.一定要在所有地雷上正確放上旗子才算勝利'''
'''p.p.s.一局結束若輸入y以外則都當作n,結束遊戲'''
#### set up ####
import random
import time
parting = ' +---+---+---+---+---+---+---+---+---+'
column = ['a','b','c','d','e','f','g','h','i']
row = ['1','2','3','4','5','6','7','8','9']
instruction = 'Enter the column followed by the row (ex: a5). ... |
#替規函數概念:調用含數自身的行為
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
number = int(input('請輸入一個正整數:'))
result = factorial(number)
print('%d 的階層是: %d'%(number, result))
|
some_text = input('enter text')
memory = ''
for word in some_text.split():
if len(word) > len(memory):
memory = word
print(memory)
|
x = input()
1234
x
'1234'
list(x)
['1', '2', '3', '4']
x = list(x)
x[0]
'1'
if int (x[0]) + int (x[1]) == int (x[2]) + int (x[3]):
print('A happy ticket')
else:
print('Not a happy ticket')
x = input()
100001
y = x[::-1]
if int(x[0, 1, 2]) == int(x[3, 4, 5]):
print('Palindrom')
elif x == y
print('Palin... |
number = input('Put yor number ')
counter = 0
for item in number:
counter += int(item)
print(f'Sum is {counter}')
|
num = int("5")
for i in range(1,11):
print(num, 'x', i,' = ' , num * i) |
def element_concat_list(number1: int, number2: int, text: str) -> str:
return text + str(number1 + number2)
if __name__ == '__main__':
result = element_concat_list(2, 3, 'sum is ')
print(result)
|
print ("=============================================welcome to idk 74 puzzle===============================================")
print("to start and get first clue tipe start")
print("no space in soluion")
start='what is full of holse but still holds water?'
asponge='what gos up and never comes down?'
yourage='i sha... |
"""
Filename: blackjack.py
Authors: Matt Matt's Coding by the Campfire Crew
"""
import random
from simpleimage import SimpleImage
#image = SimpleImage(filename)
MIN_RANDOM = 1
MAX_RANDOM = 11
NUM_RANDOM = 3
def main():
# Let's get started with some liquid courage
print("I still remember how to do a print... |
import numpy as np
import pandas as pd
#Desafio3
# En la siguiente carpeta: inputEjemplos vas a encontrar un archivo llamado
# CurrenciesRaw el cual no tiene encabezados y tiene campos erróneos. Lo que te solicitamos:
# Eliminar las columnas que no tienen valores y/o están en cero.
# Eliminar los campos que se encuen... |
#!/usr/bin/env python3
import numpy as np
def diamond(n):
def dims(n):
return 2 * n - 1
nxn = dims(n)
base = np.eye(nxn)
bottom_left = base[0:n,0:n]
# will be bottom left of result. right side will have dims one less than left
bottom_right = base[n-1:, n:]
bn = bottom_right.shape[... |
#!/usr/bin/env python3
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
from sklearn.decomposition import PCA
def explained_variance():
f = os.path.dirname(os.path.realpath(__file__)) + "/data.tsv"
df = pd.read_table(f, sep = '\t')
# fit model and transform da... |
#!/usr/bin/env python3
import os
import pandas as pd
def municipalities_of_finland():
f = os.path.dirname(os.path.realpath(__file__))
df = pd.read_csv(f + "/municipal.tsv", sep = "\t", index_col = "Region 2018")
return df["Akaa":"Äänekoski"]
def swedish_and_foreigners():
df = municipalities_of_fin... |
#!/usr/bin/env python3
import math
def solve_quadratic(a, b, c):
discriminant = (b*b - 4 * a * c)
if discriminant < 0:
x1 = "complex number"
else:
x1 = -1 * b + math.sqrt(discriminant)
x1 /= 2*a
if discriminant < 0:
x2 = "complex number"
else:
x2 = -1 * b -... |
#!/usr/bin/env python3
def find_matching(L, pattern):
lst = []
for i, v in enumerate(L):
if pattern in v:
lst.append(i)
return lst
def main():
find_matching(["sensitive", "engine", "rubbish", "comment"], "en")
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
import numpy as np
def meeting_lines(a1, b1, a2, b2):
# a1 *= -1
# a2 *= -1
A = np.array([[-b1, 1],[-b2, 1]])
b = np.array([a1, a2])
return np.linalg.solve(A, b)
def main():
a1=1
b1=4
a2=3
b2=2
x, y = meeting_lines(a1, b1, a2, b2)
print(f"Lines meet at... |
#!/usr/bin/env python3
import os
import pandas as pd
def subsetting_with_loc():
f = os.path.dirname(os.path.realpath(__file__))
df = pd.read_csv(f + "/municipal.tsv", sep = "\t", index_col = "Region 2018")
cols = ["Population", "Share of Swedish-speakers of the population, %", "Share of foreign citizens of... |
import math
def splitCheck(total,partySize):
if partySize <=1:
raise ValueError("Not enough people. Go grab that hobo you saw down the street a moment ago.")
cpp= math.ceil(total / partySize)
return cpp
try:
totalDue= float(input("What did the end amount come to? "))
crewSize= float(input(... |
#!/usr/bin/env python3
# lesson-03.py - show a $30 withdrawal and a $15 deposit
#
# Learn:
# the tedium of repetition
balance = 100
print('Welcome to the bank.')
print('Your balance is $%d.' % balance)
print()
amount = 10
print('Withdraw $%d.' % amount)
balance -= amount
print('Your balance is $%d.' % balance)
p... |
#!/usr/bin/env python3
# lesson-10.py - allow unlimited transactions
#
# Learn:
# looping
# break out of a loop
# Boolean literal
# single-branch conditional statement
def showBalance():
global balance
print('Your balance is $%d.' % balance)
print()
def withdrawal(amount):
global bala... |
#!/usr/bin/env python3
# lesson-21.py - create Account class with static balance member instead of passing around
#
# Learn:
# class definition
# static (class) members and access to them
# variable and method members
# another way to avoid globals
import sys
class Account:
balance = None
sta... |
from abc import ABC, abstractmethod
class Message(ABC):
"""
the abstract base class that serves at the input to both the encrypter and decrypter modules
"""
@abstractmethod
def get_text(self):
pass
class PlaintextMessage(Message):
def __init__(self, message_text):
"""
... |
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers import Cipher, modes
from cryptography.hazmat.backends import default_backend
from os import urandom
from cryptography.hazmat.primitives import padding
from src.encrypter.encryptor import Encryptor
class AESE... |
import urllib
import json
import datetime
user_id = "" # Not needed
api_id = "115d7627cf1dc308de3ae6111e2b33fd"
zip_code = 30070
units = "imperial"
def fetch_weather_data(zip_code):
request_url = "http//api.openweathermap.org/data/2.5/weather?zip=" + str(zip_code) + "&units=" + units + "&appid=" + api_id
tr... |
import fileinput
class Stack:
def __init__(self, max_size):
self.max = max_size
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
if self.size() >= self.max:
print('overflow')
else:
self.items.append(item)
... |
from random import *
computerNumber = randint(1,10)
# print "The correct number is: " + str(computerNumber) + ". This is for debugging purposes only -DELETE"
playerGuess = raw_input("I have a number 1-10. Whats the number? ")
if int(playerGuess) == computerNumber:
print ("Correct!")
if int(playerGuess) != c... |
def StartOver(func):
print("voulez-vous rejouer? (O/N)")
answer = input()
if (answer == "O" or answer == "o"):
func()
elif (answer == "N" or answer == "n"):
print("Au revoir! ;)")
return
else:
print("je n'ai pas compris votre réponse")
func()
#--------------... |
import sys
sys.path.append('..')
from PUtilitaires import StartOver
from PUtilitaires import inputInt
from PUtilitaires import inputFloat
from PUtilitaires import inferior
def rulesExo4():
print("Bonjour et bienvenu dans l'exo4!") #Hello a... |
# name = input("What is your Name? ")
# print("My name is " + name + "!")
print("Sum >")
num1 = input("First Number : ")
num2 = input("Second Number : ")
num1 = int(num1)
num2 = int(num2)
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2)
print(num1 % num2)
if(num1 % 2 == 0):
print("num1... |
file = open("input.txt", "r").read()
# file = open("test.txt", "r").read()
file = open("mitch.txt", "r").read()
entries = file.split("\n")
origin = None
class planet:
def __init__(self, name, orbits):
self.name = name
self.orbits = orbits
def countOrbits(self):
orbits = self.orbits
... |
import array
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def insert(self, data):
if self.last_node is None: #IF LAST NODE IS NULL SO NODE DATA INSIDE ... |
# importing necessary packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# I followed the link below to learn how to read in the table of data from the website
# https://towardsdatascience.com/web-scraping-html-tables-with-python-c9baba21059
url = 'https://questionnaire-148920.appspot.com/... |
from pyspark.sql import SparkSession
from pyspark.ml.clustering import KMeans
spark = SparkSession \
.builder \
.appName("DataFrameExample") \
.getOrCreate()
# Loads data.
dataset = spark.read.format("libsvm").load("sample_kmeans_data.txt")
# Trains a k-means model.
kmeans = KMeans().setK(2).s... |
from datetime import date, timedelta
from docx import Document
import os
DAYS = d = {'Mon': 0, 'Tue': 1, 'Wed': 2, 'Thu': 3, 'Fri': 4, 'Sat': 5, 'Sun': 6}
days = 0
course_day = []
course_title = []
d1 = date.today()
print(d1)
starting_day = 0
def input_system():
global d1, course_day, course_title, days, starti... |
""" Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:
You need to round the answer to 2 decimal places and return it as String.
If the given value is 0 then it should return 0.00
You will only be giv... |
idade = int(input("Digite sua idade: "))
if idade >= 18:
print("Vc é maior de idade")
elif idade == 0:
print("vc ainda nao nasceu")
else:
print("Vc é menor de idade")
|
'''
Simple function that takes a list square its elements
and returns another list
'''
def square(list_num):
results = []
for i in list_num:
results.append(i*i)
return results
list_num = range(1,10)
sqr_list = square(list_num)
print(sqr_list)
'''
Modifying the code above to produce a Generator
'... |
"""Problem:
Created By: AJ Singh
Date: April 13, 2021
Time: 12:20 AM MST
Time Taken:
Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper
before I started coding, and am sharing what I did here.
+++++ General Ideas/First Thoughts +++++
+++++ A... |
"""Problem: Given a string, return the longest palindromic substring.
Created By: AJ Singh
Date: April 7, 2021
Time: 1:20 PM MST
Time Taken: 1 hour 13 minutes
Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper
before I started coding, and am sharing w... |
"""Problem: Determine the sum of all primes less than or equal to n.
Created By: AJ Singh
Date: April 13, 2021
Time: 7:55 PM MST
Time Taken:
Here are my problem-solving thoughts, and explanations of each solution I constructed. I did some rough work on paper
before I started coding, and am sharing what I did here.
... |
import numpy as np
from datetime import datetime
x=int(input('숫자 얼마까지 덧셈을 할까요? '))
#print("\n")
score = 0
ts=datetime.now()
for i in range(10):
a=np.random.randint(1,x+1)
b=np.random.randint(1,x+1)
#print("%2d + %2d = %2d" %(a,b,a+b))
y=input("%2d) %2d + %2d = " %(i+1,a,b))
if int(y) == (a+b):
... |
Casos = int(input())
for i in range(Casos):
Comida = float(input())
Dias = 0
while Comida > 1:
Comida /= 2
Dias += 1
print("{:d} dias".format(Dias))
|
Pares = 0
for i in range(5):
Num = int(input())
if Num % 2 == 0:
Pares += 1
print("{:d} valores pares".format(Pares))
|
def to_roman(Number):
Roman_Numbers = {1 : 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D',900: 'CM',1000: 'M'}
Temp_num = [x for x in str(Number)]
Result = ''
Numbers = dict.keys(Roman_Numbers)
print()
if Number > 99:
Temp_num[0] += '00'
Temp_num[1] += '0'
... |
Casos = int(input())
for i in range(Casos):
Jogo = input()
if int(Jogo[0]) != int(Jogo[2]):
if Jogo[1].islower():
print(int(Jogo[0])+int(Jogo[2]))
continue
else:
print(int(Jogo[2])-int(Jogo[0]))
else:
print(int(Jogo[0])*int(Jogo[2]))
|
goal_number = 100
def check_number(x):
if x == goal_number :
print("congratulations. You won, Your number is right")
elif goal_number < x:
print("the number is lower")
else:
print("the number is higher")
programm_running = True
while(programm_running):
inp = input... |
# making edits wooooo
def output(days):
initial_infected = 7
reproduction_rate = 1.2
population = 39740
tuition = 9972
total = calc_total_infected(days, initial_infected, reproduction_rate)
percentage = total / population
print(f"total num infected: {total}")
print(f"percentage of students infected: {percenta... |
number = int(input('please enter number : '))
checkingType = int(input('please select cheking type 1 - with for loop , 2 - with minimum symbols '))
def t2(n):
return sum([int(k) for k in str(n)])
if __name__ == "__main__":
if checkingType == 1 :
result = 0
while number > 0 :
... |
import pandas as pd
import numpy as np
row = ['Person1','Person2','Person3']
data = [['Vlad','Harutyunyan',50,'Armenia'],['Vlad','Harutyunyan',30,'Armenia'],['Vlad','Harutyunyan',20,'Armenia']]
col = ['Name','Surname','Age','Country']
df = pd.DataFrame(data=data,index=row,columns=col)
print(df)
c1 = df.reset_index()... |
#!/usr/bin/env python3
"""This program can tell you who loves who by the sentences it read
either from file or from prompted text.
Multiline input is supported
"""
import argparse
import sys
def get_argparser():
"""Builds and returns a suitable argparser"""
parser = argparse.ArgumentParser(description='')
... |
"""pygame package will allow access to the Sprite class."""
import pygame
class Player:
"""Creates a character which is controllered by a player."""
def __init__(self, group, image, x, y, tile_size):
"""Constructor method for Player class. Defines an image and position."""
self.x = x
self.y = y
self.sprite ... |
#Exercise Question 3: Given a list slice it into a 3 equal chunks and rever each list
#Origigal list [11, 45, 8, 23, 14, 12, 78, 45, 89]
# Chunk 1 [11, 45, 8]
#After reversing it [8, 45, 11]
#Chunk 2 [23, 14, 12]
#After reversing it [12, 14, 23]
# Chunk 3 [78, 45, 89]
#After reversing it [89, 45, 78]
import sys... |
import sys
import math
import matplotlib.pyplot as plt
##def histogram(items):
# for n in items:
# output=''
# times=n
# while times>0:
# output+='@'
# times-=1
# print(output)
#histogram([9,2,4,5,3])
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
import sys
def multiplication_or_sum(num1, num2):
product= num1*num2
if (product>1000):
return product
else:
return num1+num2
num1= int (input ("enter first number"))
num2= int (input ("enter second number"))
result= multiplication_or_sum(num1, num2)
print("the result: ", result)
|
#Question 4: Pick a random charcter from a given String
import sys
import random
sst= "sevilay"
CHAR= random.choice(sst)
print("random character form text: ", CHAR)
|
import sys
import random
#Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations.
#Sample data:
#/*
#X = [10, 20, 20, 20]
#Y = [10, 20, 30, 40]
#Z = [10, 30, 40, 20]
target = 70
#*/
hit=[]
X = [10, 20, 20, 2... |
import sys
import os, platform
#Write a Python program to find the operating system name, platform and platform release date.
print("the opersating system name")
print(os.name)
print("the platform system")
print(platform.system())
print("the platform release")
print(platform.release())
print(isinstance(25,int) or (isin... |
import sys
# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.
#
ss=[]
for i in range(2000,3200):
if (i%7)==0 and (i%5)!=0:
... |
import sys
import json
print("enter the integer values")
x,y=map(int,input().split())
print("the integer values is ", x,y)
#Write a Python program to print a variable without spaces between values.
x="30"
v=json.dumps(x)
print("the variable of x",v)
y=3
print('the value of x "{}"'.format(y))
|
import re
#Write a Python program to find the substrings within a string.
#Sample text :'Python exercises, PHP exercises, C# exercises'
#Pattern :'exercises'
#Write a Python program to abbreviate 'Road' as 'Rd.' in a given string.
text= 'Everything will be fine soon 1234 Read and it is goining to be nice 12'
pattern=... |
#! python 3
import re
#1-What is the function that creates Regex objects?
##regexObject=re.compile(r'blabla')
#2-2. Why are raw strings often used when creating Regex objects?
#3. What does the search() method return? retrun first much of values
#4. How do you get the actual strings that match the pattern from a Matc... |
#Exercise Question 5: Given a string input Count all lower case, upper case, digits, and special symbols
#input_str = "P@#yn26at^&i5ve"
#Total counts of chars, digits,and symbols Chars = 8 Digits = 3 Symbol = 4
import sys
inputStr="P@#yn26at^&i5ve"
sml=0
cap=0
digit=0
say=0
for char in inputStr:
if char.islower():
... |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and c... |
#!/usr/bin/python
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# 5 -> (fib(4) + fib(3)) -> (fib(3) + fib(2) | fib(2) + fib(1)) | (fib(2) + fib(1) | )
# 5 ( 3 + 2 ) ( 2 + 1) + ( 1 + 1 )
def main():
print fib(7)
if __name__=='_... |
#!/usr/bin/python
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
size = 0
for word in words:
i... |
#!/usr/bin/python
# create a list. Lists are simply collections of things. They're denoted in brackets with separating commas
a = [1,2,3,4,5,6,7,8,9,10]
# define a count function
def count(b):
# define a variable that you'll be updating as you sum up the ints in the list
counter = 0
# loop through list. Notic... |
#!/usr/bin/python
import re
def learning_dict():
normal_d = {}
# open dictionary
f = open('small_dict.txt', 'r')
words = f.read().split()
# put into dictionary
for word in words:
normal_d[word.lower()] = None
h = open('small_string.txt', 'r')
# make a list of words from holy_grail.txt
hg = h... |
#!/usr/bin/python
#
# Question 0
#
# You remember yesterday how we wrote that little program, I think we called
# it count. Basically what it did was declare a list of natural numbers then
# summed them from 1 to n.
#
# So, for example, if we hardcoded the list [1,2,3,4,5] and then called
# count(), we get back 15.
#
... |
#!/usr/bin/python
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
|
#!/usr/bin/env python3
user = input("What is your name?").strip()
icecream = ["flavors", "salty"]
icecream.append(99)
print(f"{icecream[-1]} {icecream[0]}, and {user} chooses to be {icecream[1]}.")
|
a = int(input("Enter a Number: "))
b = int(input("Enter a Number: "))
c = int(input("Enter a Number: "))
s = (a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))** 2
print(area) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 10:40:34 2020
Exercise Bank account
Make a class that represents a bank account. Create four methods named set_details,
display, withdraw and deposit.
In the set_details method, create two instance variables : name and balance. The
default valu... |
import requests
print('Please enter a date of your choice with this format => YYYY-MM-DD :')
date=input()
print('Please enter one or multiple cryptocurrency symbols "separated with comma please" :')
symbol=input()
print('Please enter your preferred target currency :')
trgt=input()
api='4976d29d2ffb43259ac94f12ff54646... |
import random
class Shark():
def __init__(self,parent=None):
self.life=1
self.x = random.randrange(0,18,1)
self.y = random.randrange(0,15,1)
self.position = [self.x,self.y]
self.old_position=[None,None]
self.step=0
self.hunger=9
def move(self):
... |
#escreva uma função recursiva que imprima de um numero x até um número y.
n = int(input("informe o número a ser exibido: "))
def exibir(n):
if (n<=n and n>=0):
print(n)
return exibir(n-1)
exibir(n)
|
# 并发和并行一直是很容易混淆的概念,并发通常指的是有多个任务需要同时进行。并行则是同一个时刻有多个任务执行。用上课来举例就是,
# 并发情况下是一个老师在同一个时间段辅助不同的人功课。并行是好几个老师同时辅助多个学生功课。简而言之就是一个人同时吃三个馒头还是
# 三个人同时分别吃一个的情况,吃一个馒头算一个任务。
# asyncio 实现并发,就需要多个协程来完成,每当有任务阻塞的时候就await, 然后其他的协程继续工作。创建多个协程的列表,然后将这些协程注册到事件循环中。
import asyncio
import time
now = lambda : time.time()
async def do_some_wo... |
# coding:utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 反转一个链表。
# pre 指向... |
i = input("请输入起始值")
e = input("")
sum = 0
i = int(input("请输入起始值"))
sum = int(input("请输入终止值"))
elif i > sun
print("起始值不能大于终止值")
while i < 1000000000000000001:
print(i)
sum+=i
i+=1#i = i+1
print(sum)
|
'''
str = "baimingrui"
for i in str:
print(i)
'''
i = 0
j = len(str)
while i < j:
print(str[i])
i+1
|
def test2(a):
a+=a
print(a)
'''
x = [1,2]
test2(x)
print(x)
'''
def test3(a):
a = a+a
print(a)
x = [1,2]
test3(x)
print(x)
|
import random
import time
print('欢迎使用QQ'.center(50,'*'))
print('请先注册你的QQ号'.center(50,' '))
while True:
a = input('请输入你要注册的QQ号:')
b = input('请输入你要注册QQ号的密码:')
#判断是否输入正确
if len(a) == 11 and a.startswith('1') == True and len(b)>=6:
print('输入正确')
break #如果输入正确,结束本次循环
else:
print('输入有误,请重新输入')
print('正在给你发送验证码...... |
import time
import datetime
class Timer(object):
def __init__(self):
self.start = 0
self.for_start = 0
self.end = 0
self.for_end = 0
self.pause = 1
def began(self):
self.start = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
def get(self, how):
... |
class Calculadora(object):
def __init__(self,marca_param ):
self.marca = marca_param
def sumar(self,numero1,numero2):
resultado = numero1 + numero2
return resultado
def restar(self,numero1,numero2):
resultado = numero1 - numero2
return resultado
def multiplic... |
"""This timer module provides stop watch functionality for measuring how
long loops / methods take to execute. """
import time
class Timer(object):
"""Timer for making ad-hoc timing measurements"""
def __init__(self, verbose=False):
self.verbose = verbose
self.secs = 0
self.msecs = 0
... |
def binary_search(arr, left, right, x):
if left <= right:
middle = left + (right -left) // 2
if arr[middle] == x:
return middle
elif arr[middle] < x:
return binary_search(arr, middle + 1, right, x)
else:
return binary_search(arr, left, middle - 1, ... |
class StackNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def push(self, data):
node = StackNode(data)
node.next = self.head
self.head = node
def is_empty(self):
return self.he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.