text stringlengths 37 1.41M |
|---|
"""
Задание 4.04
Ввести с клавиатуры целое число n. Получить
сумму кубов всех целых чисел от 1 до
n(включая n) используя цикл while
"""
num = int(input('Input number: '))
sums = 0
count = 0
while count <= num:
sums += count
count += 1
print(f'sum = {sums}')
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="Muestra el número que le hayamos pasado elevado al cuadrado")
parser.add_argument("-v", "--verbose", action="store_true",
help="incrementa la verbosidad de la salida por pantalla")
ar... |
#General Elections
from random import randint
import time#Allows time.sleep(2) work
votes1 = (randint(1, 30000))#What votes1 is
votes2 = (randint(1, 30000))#What votes2 is
votes3 = (randint(1, 30000))#What votes3 is
votes4 = (randint(1, 30000))#What votes4 is
print("Presidential Election 2016")#Prints onto the scre... |
#Mr Nazirs drive thru
sold = float(input("How many burgers have been sold this month?"))#Defines how many burgers you have sold
money = sold * 4.30#Multiplies how many sold by 4.30 (the price of the burger)
stock = float(input("How much money have you spent on stock this month?"))#Defines how much has been spent on ... |
#This code works out the perimeter of a rectangle
width = float(input("Type the rectangle width."))#Float is a decimal number
length = float(input("Type the rectangle length."))#Input allows the user to type the rectangle length
perimeter = (2 * length + 2 * width) #This multiplies the length and width by 2
print ("... |
print ("Two Times Table")#Prints Two Times Tables
for i in range (1,11):#What i is
ttvalue = 2 * i#What ttvalue is
print (ttvalue)#Prints what ttvalue equals |
# File: sorting.py
# Description: Homework 9 - Tests average runtime of different sorting operations
# Student's Name: Shan Deng
# Student's UT EID: SD33857
# Course Name: CS 313E
# Unique Number: 50739
#
# Date Created: 4/20/19
# Date Last Modified: 4/20/19
#Imported stuff that bulko suggested
import random
... |
fruit="banana"
index = len(fruit)-1
while index >= 0:
letter = fruit[index]
print letter
index = index - 1 |
import numpy as np
from mnist import MNIST
from matplotlib import pyplot as plt
def sigmoid(X):
return (1/1+np.exp(-X))
def softmax(X):
return np.exp(X)/np.sum(np.exp(X),axis=0)
class NeuralNetwork():
def __init__(self,sizes,batch_size,l_rate=0.001,epochs=3):
self.sizes = sizes
self.batch... |
import requests
import xml.etree.ElementTree as ET
def read(url='https://jobs.marketinghire.com/jobs/?&ss=1&display=rss', num_jobs=None):
'''
This function crawls and creates a dictionary of jobs from a xml job feed
As an example we parse jobs from marketinghire.com
Args:
num_jobs: Number of j... |
from AccountScheduler import AccountScheduler
from InsufficientBalanceException import InsufficientBalanceException
class Client:
def __init__(self):
self.accountScheduler = ""
def showTransactions(self):
self.accountScheduler=AccountScheduler()
while(True):
choice=input("E... |
class Account:
def __init__(self):
self.accountNo = 0
self.custName = ""
self.balance = 0
def setAccountNo(self, accountNo):
self.accountNo = accountNo
def getAccountNo(self):
return self.accountNo
def setCustName(self, custName):
self.custName = custNa... |
Space = ' ' * 25
print("%s (ATM Balance Information)" %Space)
import datetime
x= datetime.datetime.now()
print(x)
Account_Balance = 5000000
GovTax = 0.6
FedTax = 58
ATM = 18.75
Balance = int(input("Enter Amount: "))
print("You withdraw: ",Balance)
for i in range(1,999999999):
if(Balance > 50000):
... |
#Joseph Mucciaccio
#This program takes information from one file and outputs it to a second one
#also has another function that gets rid of any comments in one file and outputs it to another
def line_number(input_file, output_file):
index = 1
try:
with open(input_file,'r') as inputFile:
... |
#Joseph Mucciaccio
#This program reads a mathematical function that uses a parameter, domain, and number of samples and outputs a list of
#of elements within the sample number inputed by the user
import math
import matplotlib.pyplot as plt
def displaylist_and_plot(fun_str, domain, ns):
even_interval = (do... |
import random
from interact import *
# intro....
print(colors.yellow,'________________________ThisGuyCodez_________')
print(colors.green,' O')
print(colors.green,'\|/')
print(colors.green,' |')
print(colors.green,'/ \\')
print(colors.lightred,'_____________________________________________')
print(colors.orange,'__... |
def ab_plus_c(a,b,c):
if a==0:
return c
return b+ab_plus_c(a-1,b,c)
a=int(input("a:"))
b=int(input("b:"))
c=int(input("c:"))
print(ab_plus_c(a,b,c))
|
"""
This module handles printing of dishes of tables to the console.
"""
from collections import OrderedDict
class Table():
def __init__(self):
self.widths = OrderedDict([
("date",0),
("indications",0),
("name",0),
("price_s",0)
])
self.dishes = []
def add(self,dish):
"""
Add the given ... |
class Graph:
def __init__(self):
self.adjList = {}
def addVertex(self, v):
self.adjList[v] = []
def addEdge(self, v, w):
self.adjList[v].append(w)
self.adjList[w].append(v)
def printGraph(self):
for x in self.adjList:
print(x+'=>')
print... |
def fibo1(num):
a = 0
b = 1
arr = [b]
for x in range(num-2):
c = a+b
a = b
b = c
arr.append(b)
return arr
def fibo2(num):
a = 0
b = 1
arr = [b, a+b]
for x in range(num-2):
arr.append(arr[x]+arr[x+1]);
return arr
print(fibo1(10));
|
"""
Object Oriented Programing (OOP)
Nesne Tabanlı Programlama
Nesne --> etrafımızda ki herşey
Python'da nesnelerin özellikleri:
* Öznitelikler (attribute)
* Davranışları (behavior)
Örnek :
Penguen
* Öznitelikleri : adi, yaşı , boyu , kilosu , rengi , türü
* davranışları : yüzme, yürüme, şarkı söyleme, dans etme
OO... |
#!/usr/bin/env python3
import anki_vector
import numpy
import keyboard
from anki_vector.util import degrees, distance_mm, speed_mmps
from matplotlib import pyplot as plt
MIN_X = 0
MIN_Y = 0
MAX_X = 639
MAX_Y = 359
RED_MIN = 140
REDDER_THRESHOLD = 0
LASER_BOUNDARY_THRESHOLD = 20
LASER_RADIUS = 15
def pixel_is_red(p):... |
from tkinter import *
window = Tk() # empty window
def km_to_miles():
# print('Hello')
print(e1_value.get())
miles = float(e1_value.get()) * 0.62137
t1.insert(END, miles)
b1 = Button(window,text="Execute", command=km_to_miles) # NB no parentheses
# b1.pack() # simple, button in centre
b1... |
ch1= input("Enter the character")
if(ch1 == 'A' or ch1 == 'a' or ch1 == 'E' or ch1 =='e' or ch1 =='I'or ch1 == 'i' or ch1 == 'O' or ch1 =='o' or ch1 =='U'or ch1 =='u'):
print("This is vowel")
else:
print("This is a consonant") |
import math
# fluid properties
# TODO Implement selectable fluid and implement function to set fluid parameters and roughness
# using the following dictionaries
# Write a dictionaries with fluid properties in SI a fluid outputs a tuple (density, dynamic viscosity).
liquids = {'water': (1000, 0.001307),
'c... |
class Employee:
# __init__() method acts as contructor and it is call when instance get created
def __init__(self, first, last, pay, mail):
print("__init__ method class")
self.first = first
self.last = last
self.pay = pay
self.mail = mail
# self parameter is compulsary when we create method
def fullname(... |
def linkedListMerge(ls):
nls = []
for l in ls:
nls.extend(l)
rmd = set(nls)
l_rmd = list(rmd)
return l_rmd
if __name__ == "__main__":
a = [[2, 4, 9, 2, 1, 6], [9, 5, 22, 1, 0, 56, 8, 5]]
print(linkedListMerge(a))
# time complexity - O(N)
# space compl... |
listA = [20, 5, 2, 9, 3]
listB = [20, 2, 9, 3]
def TwoLists(lsA, lsB):
for num in lsA: # O(A) - t
if num not in lsB: # O(B) - t
return num
if __name__ == "__main__":
print(TwoLists(listA, listB))
# Time Complexity - O(A * B)
# Space Complexity - O(1) |
def LineAnalysis(line):
line_arr = list(line)
if "." not in line_arr:
return True
if line_arr[0] != "*":
return False
stars = ""
stars_arr = []
for i in range(len(line_arr)):
if line_arr[i] == "*":
stars += line_arr[i]
elif stars == ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 13:23:37 2021
@author: hthuang
"""
def is_float(a):
try:
float(a)
except ValueError:
try:
complex(a)
except ValueError:
return False
return True
def add(a):
x = a
... |
from pathlib import Path
filename = "costa_restaurants.txt"
menu_index = "menu_index.txt"
# create a function that convert strings in textfile to list
def greeting():
# greeting the user
print("Hello business owner, do you want to add a new restaurant?")
# ********************amended*****
def read_line(filenam... |
import turtle
turtle.goto(0,0)
turtle.tracer(1,0)
turtle.direction= None
def up():
turtle.direction = "Up"
print('you pressed the up key.')
on_move()
def down():
turtle.direction='Down'
print('you pressed the down button')
on_move()
def left():
turtle.direction='Left'
print('you pre... |
""" weather_api.py
Fetch the local weather data using coordinates.
"""
import json
import requests
def getWeather():
res = requests.get("https://api.darksky.net/forecast/68b57c294028ea3886af9e58b329b435/37.8715,-122.2730")
data = json.loads(res.text)
json.dump(data, open("data.json", "w", encoding="utf-... |
# Find panagram
def panagram(input_string) :
for i in "abcdefghijklmnopqrstuvwxyz" :
if(i not in input_string):
return False
return True
# adding test cases
result = panagram("This is meow")
print result # expected output False
result = panagram("The quick brown fox jumps over the lazy dog")
print result #... |
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
""" A basic assert implemenation that checks the equality of two values."""
__author__ = "Jan Wirth <contact@jan-wirth.de"
__version__ = "0.0.1"
def check_equality(a, b):
""" compare two values and print the result """
if a == b :
print("SAME VALUE: " ... |
#! /usr/bin/env python3
# -----------------------------------
# Version: 0.0.1
# Author: Jan Wirth
# Description: Extract ngram sequences from tokenized file
# -----------------------------------
import sys
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
def conll_reader(filename, ... |
#!/usr/bin/env python3
"""Übung zu veränderbaren Objekten, hier auf Listen konzentriert.
Hauptfrage: Wie werden veränderbare und unveränderbare Objekte geändert?
"""
"""VORÜBUNG:
- Führen Sie die einzelnen Anweisungen in check_mutables() im Python-Interpreter aus,
- und lassen Sie immer wieder die einzelnen Objekte ... |
print("有以下两个数,使用+,-号实现两个数的调换。")
print("请输入两个整数:")
a = int(input("第一个整数:"))
b = int(input("第二个整数:"))
a = a+b
b = a-b
a = a-b
print("使用求和法得出结果:")
print("a变换后为:%d"% a)
print("b变换后为:%d"% b) |
import random
import numpy as np
import matplotlib.pyplot as plt
def random_string(length):
"""
Returns a random bit string of the given length.
Parameters
----------
length: int
Posivite integer that specifies the desired length of the bit string.
Returns
-------
... |
import csv
class FileManager:
def __init__(self,fileName,write=None,log=None):
self.fileName = fileName
self.write = write
self.log = log
def read(self):
with open(self.fileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
line_c... |
# How much longer am I expected to live, given my sex, age, and country?
import requests
import csv
import datetime
import math
# PARAMETERS:
# sex
s = ['male', 'female']
sex = input('Are you male or female? Apologies for the forced gender norms. :( ')
while sex not in s:
sex = input('Male or female? ')
# country... |
origin = input()
opers1 = ("+", "-")
opers2 = ("*", "/")
stack = []
answer = ""
for i in origin:
if i == "(":
stack.append(i)
elif i == ")":
while stack and stack[-1] != "(":
answer += stack.pop()
stack.pop()
elif i in opers1: # +, - 일때
while stack and stack[-... |
#솔루션 with deque
from collections import deque
n = int(input())
d = deque(range(1, n+1))
while len(d) > 1:
d.popleft()
d.rotate(-1)
print(d[0])
# ideal 솔루션 without deque
# import math
# a = int(input())
# n = math.ceil(math.log2(a))
# x = 2**n - a
# answer = 2**n - 2*x
# print(ans... |
# coding=utf-8
"""
PROBLEM 028 - Number Spiral Diagnoals
Written by: Yuanjie Li
Date: Oct 25, 2017
Starting with the number 1 and moving to the right in a clockwise direction a
5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can ... |
"""
PROBLEM 003 - Largest Prime Factor
Written by: Yuanjie Li
Date: Jan 19, 2017
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
# Arr of primes under 5
PrimeArr = [2, 3]
def main():
Remaining = 600851475143
NextLargest = 3
while 1:
# S... |
# coding=utf-8
"""
PROBLEM 036 - Double-base Palindromes
Written by: Yuanjie Li
Date: Mar 20, 2018
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in
base 10 and base 2.
(Please note that the palindromic number,... |
"""
PROBLEM 001 - Multiples of 3 and 5
Written by: Yuanjie Li
Date: Jan 19, 2017
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.
"""
def main():
Output = 0
for i in range(... |
# coding=utf-8
"""
PROBLEM 025 - 1000-Digit Fibonacci Number
Written by: Yuanjie Li
Date: Oct 25, 2017
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
... |
item_price_dict = {
'Apple': 50,
'Orange': 20,
'Grapes': 20,
'Guava': 20,
'Bananas': 15
}
cart={}
total_price=0
final_cart={}
final_check= None
print('Choose item from the below list for your cart:')
for index, (item, price) in enumerate(item_price_dict.items()):
print('{0:<9}:Price(in Rs):{1:^}... |
# Python has a set of methods available for the file object.
# Method Description
# close() Closes the file
# detach() Returns the separated raw stream from the buffer
# fileno() Returns a number that represents the stream, from the operating system's perspective
# flush() Flushes the internal buffer
# isatty() Retur... |
"""turtle used to draw a graphics/make graphic game type or for drawing
Turtle graphics is a popular way for introducing programming to
kids. It was part of the original Logo programming language developed
by Wally Feurzig and Seymour Papert in 1966.
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After ... |
""" modules
# modules are the method/functions which are written in a separate .py file and its all objects can be used in separate
# file/programs which we intend to write. Module are predefined or manually defined by us to import/retrieve and use.
# when they are written they are intend to make impact at that time wi... |
# function annotation and type hint
# function annotation
# it helpful to determine the data type of params and return value
# if we used this then there is no need to write the datatype of param in docstring or anything about param in docstring
# to writ eth function annotation we follow below way to initialize them
#... |
# functions
def album_options():
"""
:return: print options for user to choose from
"""
return """CHOOSE OPTIONS:
1. 1 TO ADD NEW ALBUM DETAILS
2. 2 TO CHANGE EXISTING ALBUM DETAILS (ALBUM/ARTIST/YEAR ONLY)
3. 3 TO ADD/REMOVE/UPDATE SONGS IN DEFINED ALBUM
... |
age = int(input('Write your age: '))
if age > 17:
print('You are of age')
else:
print('You are under age')
number = int(input('Write a number: '))
if number > 5:
print('The number is greater than 5')
elif number == 5:
print('equals 5')
else:
print('The number is less than 5')
|
# def print_messages():
# print('Special message')
# print('I\'m learning to use functions')
# print_messages()
# print_messages()
# print_messages()
# def conversation(message):
# print('Hi')
# print('How are you')
# print(message)
# print('Bye')
# option = int(input('Select an option (1, 2,... |
#for i in range(10):
# print(i)
#print("Hello") # это комментарий
num = int(1.5e1)
print(num)
|
"""Property exercises"""
import math
class Circle:
"""Circle with radius, area, etc."""
def __init__(self, radius=1):
if (radius < 0):
raise ValueError("Radius cannot be negative!")
self._radius = radius
self.radius_changes = [self._radius]
@property
def area(self):
... |
"""
Playing With Wheels
Uva: 10067
programming-challenges Chapter09 PR_066
"""
from sys import stdin
import collections
def read_and_convert_to_int(line):
return int(line)
def read_and_convert_into_tuple(num_in_string):
return tuple(int(n) for n in num_in_string.split())
def read_input():
num_of_... |
__author__ = 'Soniya Rode'
from graph import Graph
import math
import random
import turtle
import sys
def file_len(fname):
'''
This function returns the height and width of the maze
:param fname: File name
:return: height, width of the maze
'''
with open(fname) as f:
for i, l in enume... |
x = 50
y = 60
z = 70
print("global x is", x)
print("global y is", y)
print("global z is", z)
print("---------------------")
def xFuction():
x = 5
print("local x is", x)
def yFunction():
y = 6
print("local y is", y)
def zFunction():
z = 7
print("local z is", z)
def xChange(num1):
glob... |
import pygame
class Graphics:
def __init__(self, caption="Checkers", frame_rate=60):
self.caption = caption
self.frame_rate = frame_rate
self.fps = 60
self.window_height = 800
self.window_width = 800
self.square_size = int(min(self.window_height, self.window_width)... |
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Adding widgets to the root window
Label(root, text = 'Packman Game', font =(
'Verdana', 15)).pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = r"C:/Users... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def ReverseList(self, pHead):
cur = None
pre = pHead
while pre:
temp = pre.next
pre.next = cur
cur = pre
pre = temp
return cur |
edad = int(input('Bienvenido al CineUNIMET\n Ingrese su edad para determinar el costo de su boleto: '))
if(edad<4):
print('Tu entradas en GRATIS!!')
elif(edad>= 4 and edad<=18):
print('El precio de tu entrada es de $10')
elif(edad>18):
print('EL precio de tu entrada es de $14') |
inputArray = [25, 57, 37,48, 12, 92, 86, 33]
Y = [-1]*len(inputArray)
h=0 #largest index
t=0 #smallest index
s=0
l=0
Y[0]=inputArray[0]
def insertionSort():
for i in range(1, len(inputArray)):
key = inputArray[i]
j = i-1
while j >=0 and key < inputArray[j] :
inputAr... |
print("Данный логический калькулятор работает по схеме A?B, где 'A' и 'B' - переменные (0 или 1), a '?' - логическая операция")
n=9999
while True:
while True:
a = float(input("Введите переменную A: "))
if (a<0) or (a>1):
print("Введено недопустимое значение A (0,1)")
print("="*30)
else: n=0... |
from classfila import Fila
from classpilha import Pilha
def main():
pilha_s=Pilha()
pilha_aux=Pilha()
pilha_aux_2=Pilha()
fila_aux=Fila()
qtde=int(input('Quantos elementos deseja inserir em sua pilha S? '))
for i in range(qtde):
element=input(f'{i+1}* Elemento: ')
pil... |
#!/usr/env/bin python
# -*- coding:utf-8 -*-
import os
import sys
'''This is script for converting the .gff format into .csv format.
The .csv format can present the infomation of each gene clearly.
The output file includes the chromesome information and each gene sites' start point, end point, strand,name,type,chromeso... |
"""
reverse(['a', 'b', 'c'], 0, 2)
/ | \
swap a & c | return ['c', 'b', 'a']
swap b & b
"""
def single_var_swap(data, i, n):
"""
:description Single variable
:param data:
:param i:
:param n:
:return:
"""
if i >= n // 2:
... |
def len_of_last_word(s: str):
return len(s.strip().split(' ')[-1])
def optimized_len_count(s: str):
size = len(s)
max_count = 0
flag = False
for i in range(size - 1, 0, -1):
if s[i] == ' ' and flag:
break
if s[i] != ' ':
max_count += 1
flag = ... |
def best_closing_time(customer):
max_score = score = 0
best_hour = - 1
for i, c in enumerate(customer):
score += 1 if c == 'Y' else -1
if score > max_score:
max_score, best_hour = score, i
return best_hour + 1
if __name__ == '__main__':
best_closing_time('YYNY')
... |
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
def reverse_vowels(s):
s_list = list(s)
left, right = 0, len(s) - 1
while left < right:
while left < right and s[left] not in vowels:
left += 1
while left < right and s[right] not in vowels:
right -= ... |
"""
LEETCODE -> https://leetcode.com/problems/text-justification/
"""
import math
def add_words_per_line(words, word_index, max_width, result, row_index):
cur_words = []
cur_len = 0
while word_index < len(words):
cur_len += (len(words[word_index]) + 1)
if cur_len <= max_width:
... |
from dice import Dice
class Player:
def __init__(self, name, quantity_dices=4, turns=100000, games=7):
self.__results = {}
self.__results["wins"] = 0
self.__results["lose"] = 0
self.__results["draw"] = 0
self.__results["name"] = name
self.__results["information"] = ... |
class television():
def __init__(self, number_channel=0, name_channel="1st", volume=0):
self.number_channel = number_channel
self.name_channel = name_channel
self.volume = volume
def get_info(self):
print("На данный момент вы находитесь на канале ", channels[self.number_channel]... |
"""
Следующая итерационная последовательность определена для набора натуральных чисел:
n → n / 2 ( n четное)
n → 3 n + 1 ( n нечетное)
Используя приведенное выше правило и начиная с 13, мы генерируем следующую последовательность:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
"""
numbers = list(range(13, 20))
count = ... |
'''
Выбрать любое число от 1 до 100
Предложить роботу отгадать число с помощь метода рандом
Приравнять попытки к значению 1
пока число загаданное пользователем не равно числу робота
если оно больше загаданного
сузить числа от min до выбранного им числа -1
иначе
сузить числа от загаданного им числа + 1 до max
... |
def factorial(x):
factor = 1
while x >= 1:
factor *= x
x -= 1
return factor
print(factorial(3)) |
n = int(input("Введите число "))
fib = lambda n: fib(n-1) + fib(n-2) if n > 2 else 1
print(fib(n))
|
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
DESCRIPTION:
A function to load and merge the data from messages and target disaster categories
INPUT:
messages_filepath - a csv file with message data
catego... |
# Given a 32-bit signed integer, reverse digits of an integer.
# Input: 123
# Output: 321
#########################################################
# str to int finally int to str, it should notice that after reverse it might
# exceed the scope
class Solution:
def reverse(self, x: int) -> int:
i... |
#script for play the game
#for 667 final proj
#Author Weiheng Chai
#email wchai01@syr.edu
###############################################
from game.connect4 import Connect4
def playconnect4():
print('please input widht:')
x = input()
print('please input height')
y = input()
while not x.isdigit() o... |
#encoding = utf-8
# 存储网站和密码
# 实现增删改查功能
class pw_management(object):
def __init__(self):
self.passwds = [] # 用于存放所有的密码信息
self.passwd_temp = {} # 构建单个密码信息
#创建新密码
def new_passwd(self):
self.passwd_temp["address"] = input("请输入新的网址:")
self.passwd_temp["password"] = input(... |
# encoding = utf-8
# 打印文件中除了#开头的内容
# 输入要打开的文件
file_name = input("请输入要打开的文件名:")
# 获取文件内容
f = open(file_name,"r")
contents = f.readlines()
print(contents)
# 打印输出
for temp in contents:
if temp.startswith("#"):
#print(end="")
continue
else:
print(temp)
f.close() |
# Dada uma lista de compras, queremos saber qual é o item mais caro da lista.
# Formato de entrada: Uma sequência de itens, cada um descrito numa linha. Cada item contém
# um código de produto (um número inteiro), a quantidade do produto e o preço unitário (um float).
# A sequência termina com um item com 0 como cód... |
# Faça um programa em Python3 que receba uma temperatura em Fahrenheit, calcule e
# imprima o valor convertido para a escala Celsius e para a escala Kelvin, de
# acordo com as equações de conversão abaixo:
# t_celsius = (t_fahrenheit - 32) * 5/9
# t_kelvin = t_celsius + 273.15
# A entrada será um número real n, com ... |
# Escreva um programa em Python3 que receba 4 valores, referentes à altura de 4 pessoas,
# calcule e imprima a média desses valores.
#As entradas serão números reais positivos não nulos. Não é necessário fazer nenhum tipo de
# validação dos dados de entrada
v1 = float(input("Primeira altura: "))
v2 = float(input("S... |
import pygame # Imports a game library that lets you use specific functions in your program.
import random # Import to generate random numbers.
# Initialize the pygame modules to get everything started.
pygame.init()
# The screen that will be created needs a width and a height.
screen_width = 1040
scree... |
from tkinter import *
window = Tk()
window.minsize(width=100,height=200)
window.config(padx=20, pady=20)
def cal():
km =float(input.get())
label2["text"] = 0.62*km
new_label = Label(text="is equal to")
new_label.grid(column=0, row=1)
input = Entry()
input.grid(column=1, row=0)
label1 = Lab... |
'''
Guess The number
Generate a random integer from a to b. You and your friend have to guess a number between two numbers a and b. a and b are inputs taken from the user. Your friend is player 1 and plays first. He will have to keep choosing the number and your program must tell whether the number is greater than th... |
# -*- coding: cp1252 -*-
#/usr/bin/env python
#Simon H. Larsen
#Buttons.py - example
#Project startet: d. 28. august 2012
#Import pygame modules and Buttons.py(it must be in same dir)
print("HI")
import pygame, Buttons
from pygame.locals import *
#Initialize pygame
pygame.init()
print("HI2")
class Button_Example:
... |
from re import compile, X
PATTERN = compile(
r"""
(?P<x>\d+), # x coord
(?P<y>\d+), # y coord
(?P<f>NORTH|EAST|SOUTH|WEST) # facing
""", X
)
def parse(line):
"""Parse one command line and return valid components
An exception is raised if ... |
import os
import collections
class KeyValues(collections.MutableMapping):
"""Class for representing Key Values objects, with container behavior.
This class implements the tree data structure used by KeyValues, exposing
method for acting like a python Dictionary, but keeping the key order.
It also imp... |
#https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
class Solution:
def subtractProductAndSum(self, n: int) -> int:
# break the original number into chars
n_list = list(str(n))
n_len = len(n_list)
sum_digits = 0
prod_digits = 1
fo... |
lado = float(input("Digite o valor de um dos lados do quadrado: "))
print("A área do quadrado é de: {:.2f}. E seu dobro é de: {:.2f}".format((lado**2), (2*lado**2)))
|
def calci():
print('Welcome to CALCULATOR PRIME.')
print('+ for addition, - for subtraction, * for multiply, / for divide, ** for power')
oper = input('Please enter the operation you to perform: ')
num1 = int(input('Enter your first no: '))
num2 = int(input('Enter your second no: '))
i... |
# print(0.1 + 0.1 + 0.1 - 0.3)
from decimal import Decimal
print(Decimal('0.1')+Decimal('0.1')+Decimal('0.1')-Decimal('0.3'))
from fractions import Fraction
print(Fraction(1, 10) + Fraction(1, 10) + Fraction(1, 10) - Fraction(3, 10))
print((2.5).as_integer_ratio())
f = 2.5
x = Fraction(1, 3)
z = Fraction(*f.as_... |
# decimal
d = 123
# hexa
h = 0x1F2
# octa
o = 0o71
# binary
b = 0b1010
print(d, h, o, b)
# complex numbers
print(complex(1, 2))
a = 3
b = 4
print(a + 1, a - 1)
print(b * 3, b / 2)
print(a % 2, b ** 2)
print(2 + 4.0, 2.0 ** b)
print(b / (2.0 + a))
print('1' == 1)
# same as 1 == 2 and 2 < 3
print(1 == 2 < 3)
x = ... |
distancia = float(input('Digite a distância da viagem: '))
if distancia <= 200:
print('O valor da viagem será de R${:.2f}'.format(distancia * 0.50))
else:
print('O valor da viagem será de R${:.2f}'.format(distancia * 0.45))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.