text stringlengths 37 1.41M |
|---|
num1 = 1
for i in range(4):
for j in range(i + 1):
print(num1, end = " ")
num1 += 1
print()
|
"""
Program 2 : Write a Program that accepts an integer from user and print Sum of
all number up to entered number .
Input: 10
Output: The s um number up to 10 : 55
"""
num = input("Enter the number : ")
sum1 = 0
for itr in range(1,num+1):
sum1 = sum1 + itr
print("The Sum of number upto "+str(num)+" : "+str(sum... |
a = input("input : ")
if a >= 'A' and a <= 'Z':
print(a,"is in Upper Case")
else :
print(a,"is in Lower Case") |
c = raw_input("Enter Character : ")
try :
if(ord(c) >= 65 and ord(c) <= 90):
print("{} is in UpperCase".format(c))
elif(ord(c) >= 97 and ord(c) <= 122) :
print("{} is in LowerCase".format(c))
else :
print("{} is not alphabet".format(c))
except TypeError as te:
print("Character is not Entered")
pass |
r = float(input("Radius : "))
print("Area : ", 3.14 * r * r) if r >= 0 else print("Enter valid input.")
|
#!/usr/bin/env python3
a = int(input())
b = int(input())
# Stampa un messaggio se i numeri sono uguali
if a == b:
print("I due numeri sono uguali")
print(a + b)
|
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM) # Create TCP Socket
# Prepare a server socket
#Fill in start
# Identifier for a message/request: browser will assume port 80 and the webpage will be shown if your server is listening at port 80
serverPort = 6789
serverName = '10.0.0.... |
import math
print("Введите коэффициенты для квадратного уравнения (ax^2 - (3-c)x - c = 0):")
a = float(input("a = "))
c = float(input("c = "))
b=-(3-c)
D = b ** 2 - 4 * a * c
print("D = %.2f" % D)
if D > 0:
x1 = (-b + math.sqrt(D)) / (2 * a)
x2 = (-b - math.sqrt(D)) / (2 * a)
if x1>x2:
print(x1)
... |
print('Введите значение аргумента')
import math
try:
try:
x=float (input('x = ',))
z1=(math.sin(2*x)+math.sin(5*x)-math.sin(3*x)) / (math.cos(x)-math.cos(3*x)+math.cos(5*x))
z2= math.tan(3*x)
print('z2 = ',z2)
print('z1 = ',z1)
except ZeroDivisionError:
print('Про... |
import requests
# Headers info for HTTP requests
headers = {"User-Agent":
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" +
"(KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"}
# Function to retrieve JSON from a GET request.
def getJSON(url):
# Variable stores a URL's data
# ... |
class TrieNode:
def __init__(self, alphabet, char):
self.alphabet = alphabet # The alphabet is a dictionary that can will have keys that tell us if a particular
# character has been used at that junction
self.char = char # The node will contain the character for concatenation while searchi... |
import turtle as tt
tt.shape("turtle")
tt.penup()
tt.goto(0, -120)
tt.pendown()
i = 0
while(i < 360):
tt.forward(3)
tt.left(1)
i+=1
|
'''
Курс "Информатика на Python 3" на ФБМФ.
Работа №16, задача 3, частотный анализ текста.
'''
class FrequentAnalysis:
alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
def __init__(self, text, correct_order):
# Считаем вхождения русских букв в текст независимо от регистра
counter = [text.lower(... |
'''
George Whitfield
gwhitfie@andrew.cmu.edu
June 9 2020
client.py - client for testing the communication with the server in server.py
How to use this file:
python3 client.py <message to send to server>
'''
import socket
import sys
# starter code copied from python documentation about socketserver and sockets
... |
""" A coordinate location on the graph """
import numpy as np
import math
from matplotlib.patches import Rectangle
class Point:
def __init__(self, coord):
""" Initialize a point on the Graph
coord: int or ndarray
if only x is specified, then a 1x2 array with coordinates
"""
if np.array(coord).shape != (2,)... |
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Data for three-dimensional scattered points
# zdata = 15 * np.ra... |
#Output an image to the console
import Question1 # catch the training set
import numpy as np
def Question1Image(no):
myimage = Question1.train_images[no]
myimage = np.array(myimage)
return myimage
# print image to console
def printImage(myimage):
for row in myimage:
for col in row:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 11:35:24 2019
@author: mica
"""
""" PROJECT OVERVIEW
KENTUCKY DERBY WEIGHTED HORSE PICKER
This is a simple console program designed to allow the user to
generate various Kentucky derby bets, with random choice, based
on how they would rate each... |
'''
isinstance(x,y) x是否為y的子類
type(x) 誰實例化x
'''
class A:
pass
class B(A):
pass
class C:
pass
a = A()
b = B()
# isinstance(b,B) or isinstance(b,A) or isinstance(b,C)
print(isinstance(b, (B, A, C)))
|
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'name={self.name} age={self.age}'
s1 = Student(name="test", age=20)
l1 = [1, 2, 3]
d1 = {1: 1, 2: 2}
# Student.__bases__
'''
<type 'type'>
type of all types
<type 'upject'>
base o... |
import important
'''
切片方式
[start:end:step]
結果不包含end 只到end前面一位
[:] 包含全部內容 拷貝的意思
[:3] = [0:3]
[0:5:3] 取index = 0 and index = 3的值
反向取值
a = [1, 2, 3, 4, 5, 6]
d = a[5:0:-1] # [6, 5, 4, 3, 2]
c = a[::-1] # [6, 5, 4, 3, 2, 1]
'''
# 獲取列表機本信息
list1 = [1, 2, 3, 5, 8, 5, 3, 2, 46, -10]
# print(f'list1的長度為{len(list1)}')
# print(f... |
# 前綴為class
# attribut and methiod
# methiod's first pramater si self(js's this)
# self __init__ 內設置屬性 _代表受保護的 可以更改也可以從外面獨拿到該屬性
# __代表私有的 實例拿不到 只能在該class中修改與獲取
# 通常都使用_protect_ __private_做前綴
# 透過dir 可以拿到該實例能拿到的所有屬性 __為開頭的屬性 需要加_類的名稱 即可訪問修改
class People:
def __init__(self, name, age):
self.name = name
... |
a = 2
b = 0b1010 # 2進制
c = 0o12 # 8進制
d = 0xa # 16進制
'''
整數除法 / 精確計算 type float // type int
float做運算 結果都是float
'''
# print(type(4 / 2)) # float
# print(type(3//2)) # int
name = 'python'
age = 27
new_str = 'I am %s today %d' % (name, age) # python2
new_str_1 = 'I am {} today {}'.format(name, age) # python3 不會有... |
'''
The valid function takes a function (f) and a list (l) and
returns what items in l are valid for a given f.
'''
import math
def valid(f, l):
try:
for i in l:
f(i)
except:
del(l[l.index(i)])
valid(f,l)
return l
'''
examples:
valid(chr, [-1, 10, 123... |
# Flatten a list containing sublists
# https://stackoverflow.com/questions/17864466/flatten-a-list-of-strings-and-lists-of-strings-and-lists-in-python
def flatten_to_strings(listOfLists):
"""Flatten a list of (lists of (lists of strings)) for any level
of nesting"""
result = []
for i in listOfLists:
... |
import tkinter.messagebox as tm
import tkinter
from module import kalkulasi_persamaan
def show():
tm.showinfo(title="Hasil", message=kalkulasi_persamaan.kalkukasi_turunan(persamaan.get(), berapa_kali.get()))
root = tkinter.Tk()
tkinter.Label(root, text="Persamaan: ").grid(row=0)
tkinter.Label(root, text="Be... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/8 18:07
# @Author: yuzq
# @File : TestStocks
import csv
import pprint
from collections import namedtuple
def traverse1():
print('------------我是方法分界线起始---------------')
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/28 16:06
# @Author: yuzq
# @File : GuessNumber
import random
def guess_number():
print('I am Thinking of a number between 1 and 20')
target_number = random.randint(1, 20)
count = 0
while count < 6:
print('Take a guess')
nu... |
# 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
# 注意:答案中不可以包含重复的四元组。
# 示例 1:
# 输入:nums = [1,0,-1,0,-2,2], target = 0
# 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
# 示例 2:
# 输入:nums = [], target = 0
# 输出:[]
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com... |
# 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
#
# 说明:你不能倾斜容器。
#
# 示例 1:
#
# 输入:[1,8,6,2,5,4,8,3,7]
# 输出:49
# 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
#
# 示例 2:
#
# 输入:height = [1,1]
# 输出:1
#
# 示例 ... |
"""A Collection of useful miscellaneous functions.
misc.py:
Collection of useful miscellaneous functions.
:Author: Hannes Breytenbach (hannes@saao.ac.za)
"""
import collections.abc
import itertools
import operator
def first_true_index(iterable, pred=None, default=None):
"""find the first index position for ... |
# using INSERT IGNORE prevents duplicates in the db
def generate_insert_statement(table_name, column_name, email):
return "INSERT IGNORE INTO " + table_name + "(" + column_name + ") VALUES(\'" + email + "\');"
def generate_mysql(fn, table_name, column_name):
input_file = open("email_list_output.txt", "r")
... |
# -*- coding: utf-8 -*-
import os, sys, paramiko
def get_csv_files(path: str) -> [] :
"""
get csv files from directory
:param path: file path
:return: csv files list
"""
files = []
for f in os.listdir(path):
if (f.endswith(".csv")):
files.append(f)
return files
de... |
my_dick = {"a":1, "b":2, "c":3}
try:
value = my_dict["d"]
except IndexError:
print("This index does not exist!")
except KeyError:
print("This key is not in the dictionary!")
except
print("Some other error occurred!")
try:
x = int(input())
except ValueError:
print ("Vi vveli n... |
# ---------------------
# Imports
from person import Person
from product import Product
from db import DataBase
from classes import (Writer, Pen, Typewriter)
# # ---------------------
# # Instance Person class
# person_one = Person('Ciclano', 25)
# person_two = Person.by_birth_year('Fulano', 1996)
# # ---------------... |
'''
Question 4.1
Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
'''
class Graph:
def __init__(self):
'''
The implementation of an undirected Graph ADT with a few key features kept in mind.
'''
self.gra... |
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
#it binds the serverSocket to port number specified in serverPort variable.
#then when anybody sends anything to server IP address and serverPort the serverSocket will get it.
serverSocket.listen(1)
#s... |
age = 20
age = age + 20
# we dont need to give any datatype to the variables
# we can just write any variable and its value
price = 19.85
first_name = "Hitansh "
answer = False
# python is a k sensitive language
print(age)
print(price)
print(first_name)
print(answer) |
# Третьяков Роман Викторович
# Факультет Geek University Python-разработки. Основы языка Python
# Урок 3. Задание 3:
# Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов
def my_func(*args):
# Сортировку намеренно указываем в обратном порядке... |
import pandas as pd
def faculties_by_degree(degree):
return degree['Наименование факультета'].dropna()
def specialties_by_faculty(faculty, degree):
faculties = degree['Наименование факультета']
# faculties = faculties.fillna(method='ffill', axis=0) # заполнение объединённых ячеек
fac_specialties = []... |
# -*- coding:UTF-8 -*-
import sqlite3
class PriceDatabase:
def __init__(self, watcher):
self.watcher = watcher
self.conn = sqlite3.connect('./db/' + self.watcher.name + '.db')
def create_table(self):
self.conn.execute('CREATE TABLE tbl_price('
'id INTEGER PRI... |
from collections import defaultdict, deque
import functools
import math
import re
def part1(data):
grid, instructions = parse_data(data)
for direction, n in instructions:
new_grid = fold(grid, direction, n)
grid = new_grid
break
return len(grid)
def part2(data):
grid, instruc... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.m = {}
def maxPathSum(self, root: TreeNode) -> int:
self.setSu... |
from queue import Queue
class Solution:
def numberOfSubstrings(self, s: str) -> int:
q = Queue()
c = {
'a': 0,
'b': 0,
'c': 0
}
movingBound = -1
num = 0
for i, ch in enumerate(s):
q.put((i, ch))
c[ch] += 1
while all(c.values()):
... |
class Solution:
def capitalizeTitle(self, title: str) -> str:
parts = title.split(' ')
capitalized = []
for p in parts:
if len(p) <= 2:
capitalized.append(p.lower())
else:
capitalized.append(p.title())
return ' '.join(capitalize... |
from collections import deque
def part1(data):
nums = deque([int(i) for i in data])
for _ in range(100):
cc = nums.popleft()
sides = [nums.popleft() for i in range(3)]
nums.append(cc)
dc = (cc - 1) or 9
while dc in sides:
dc -= 1
# Wrap.
... |
x = int(input('enter an integer for which you would like the cube-root: '))
for guess in range(abs(x) + 1):
if guess **3 >= abs(x):
break
if guess**3 != abs(x):
print(x, 'is not a perfect cube.')
else:
if x < 0:
guess = -guess
print(guess, 'is the cube root of ' , x )
|
x = int(input('enter an integer for which you would like the cube-root: '))
for guess in range(x + 1):
if guess**3 == x:
print(guess, 'is the cube root of ', x)
if guess == x:
print(x, 'is not a perfect cube.')
|
i = 10
print('Hello!')
while i >= 2:
print(i)
i -= 2
|
#coding=utf-8
# 输出 9*9 乘法口诀表。
for i in range(1,10):
for j in range(1,10):
a=" "
if(j<=i):
print(j, "*", i,"=",i*j ,a,end="")
print("\n")
for i in range(1,10):
for j in range(1,10):
if j<=i:
print(i,"*",j,"=",i*j," ",end="")
pr... |
#coding=utf-8
# 输入中文你好
print("你好")
# 编写程序输入你的名字 并输出
#请写出 多行文字 并对其进行注释
"""
asdfasdfasdfas
asdfasdfasdf
"""
#一条语句如果很长,如何来实现多行语句
#字符串操作
str = 'Runoob'
# 输出第一个到倒数第二个的所有字符
# 输出字符串第一个字符
# 输出从第三个开始到第五个的字符
# 输出从第三个开始的后的所有字符
# 输出字符串两次
# 连接字符串
#做一个不换行输出
#如何查询变量所指的对象类型
#演示删除一个对象的引用
#演示 数值运算 除法,得到一个浮点数
#演示 数值运算 除法,得... |
#获取文件对象
file=open("hello.txt","w")
# strmess="""Python是非常好的 语言!
# 我们都很喜欢她
# """
print("文件名字:",file.name)
file.write("123")
file.write('\n')
file.write("456")
# 关闭打开的文件
file.close()
file1=open("hello.txt");
strreadline=file1.readline()
print("strreadline=",strreadline)
file1.close |
# Write a program that simualates the Monty Hall Problem and prove numerically why you should always switch.
# Two inputs: number of games and switch/stay
"""
Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and ... |
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
if not self.items:
print("Stack is empty")
return
def enqueue(self,item):
self.items.append(item)
def dequeue(self):
self.is_empty()
self.items.pop(0)
def size(self):
... |
from cards import Card
import random
class Game:
def __init__ (self):
self.size = 4
self.card_options = ['Add', 'Boo', 'Cat', 'Dev',
'Egg', 'Far', 'Gum', 'Hut']
self.columns = ['A', 'B', 'C', 'D']
self.cards = []
self.locations = []
for column in self.colu... |
from abc import ABCMeta, abstractmethod
class Animal(metaclass = ABCMeta):
@abstractmethod
def __init__(self, species, shape, character):
self.species = species
self.shape = shape
self.character = character
@property
def is_raptor(self):
if self.species == 'eat-meat' an... |
from board import Board
def get_row_col (initiate_board : bool = False) -> int:
row, col = -1, -1
while row == -1 or col == -1:
row, col = -1, -1
try :
row = str (input ('linha? '))
col = int (input ('coluna? '))
except:
print ('Erro na introduçao de... |
import requests
from bs4 import BeautifulSoup
class PriceBot(object):
URL = 'https://www.johnlewis.com/house-by-john-lewis-hinton-office-chair/p2083183'
def get_price(self):
r = requests.get(self.URL)
content = r.content
soup = BeautifulSoup(content, "html.parser")
element = so... |
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs) # <- Zwrócenie wartości
return wrapper_do_twice
@do_twice
def return_greeting(name):
print("Creating greeting")
return f"Hi {name}"
if __name__ == '__main__':
print(return_... |
# a = 1
# b = 2
#print(a+b)
# Przykład działania funkcji na referencji
def last_item_add1(list_a, elem_a=10):
last_elem = list_a[-1]
last_elem += elem_a
list_a.append(last_elem)
# Funkcja zwracająca wartość
def last_item_add2(list_a, elem_a):
last_elem = list_a[-1]
last_elem += elem_a
list_a... |
"""
Gettery i settery.
W OOP program powinien mieć argumenty prywatne.
Aby móc do nich dostać się z zewnątrz, potzebne są pewne metody.
Getter to metoda która pozwala nam na uzystanie wartości dla atrybutu prywatnego.
Natomiast setter pozwala na ustawienie wartości atrybutu.
"""
class CodeCouple(... |
temp_list = []
for i in range(100):
temp_list.append(i**2)
print(temp_list)
temp_list_2 = [i**2 for i in range(100)]
print(temp_list_2)
print(temp_list == temp_list_2)
|
"""
Pakiet argparse.
Ten pakiet pozwala nam nie tylko interpretować argumenty linii komend
ale także podać informację pomocniczą w razie gdyby nie wiadomo było
co trzeba wprowadzić
"""
import argparse
# Dodajemy opis programu za pomocą słowa kluczowego 'description'
parser = argparse.ArgumentParser(d... |
def isPerfect(n):
# To store sum of divisors
sum = 1
# Find all divisors and add them
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + n / i
i += 1
# If sum of divisors is equal to
# n, then n is a perfect number
return (True if sum == n... |
"""
This is the program for adding two numbers
"""
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
print("The content of file is:")
data=f.read()
print(data) |
try:
number_input_a = int(input("정수입력>"))
print("원의 반지름:",number_input_a)
print("원의 둘레:",2*3.14*number_input_a)
print("원의 넓이:",3.14*number_input_a*number_input_a)
except Exception as exception:
print("type(exception):",type(exception))
print("exception:",exception)
list_number = [52,324,534,23,... |
dic={
"name" : "7d 건조 망고",
"type" : "당절임",
"ingredient" : ["망고","설탕","메타중아황산나트륨","치자황색소"],
"origin" : "필리핀"
}
print("name:",dic["name"])
print("type:",dic["type"])
print("ingredient:",dic["ingredient"])
print("origin:",dic["origin"])
dic["name"] = "8d 건조 망고"
print("name:",dic["name"])
print("ingr... |
import sqlite3
conn = sqlite3.connect('participants_db.db')
print("Opened database successfully")
conn.execute('''CREATE TABLE PARTICIPANT_BALANCE
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
BALANCE INT NOT NULL);''')
print("Table created successfully")... |
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
self.prev_node = None
class LinkedList:
def __init__(self):
self.head = None
self.tail=None
self.size = 0
def insertBeg(self, data):
if self.head == None:
self.... |
# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
with open('file.txt', 'w') as f_text:
my_list = input('Введите предложение: ').split()
for line in my_list:
f_text.write(line + '\n')
p... |
class VMWriter:
""" todo: !!! important!!! symobl tables for operators so we can convert
todo: them easily to vm code
"""
BIN_OPS = \
{
'+': 'add',
'-': 'sub',
'&': 'and',
'|': 'or',
'<': 'lt',
'>': 'gt',
'=': 'e... |
from tkinter import *
from random import randint
root = Tk()
root.title('Password Generator by Alvin')
root.geometry("500x300")
def new_rand():
#Clear entry box
pw_entry.delete(0, END)
#Get password lenght
length = 8
#Create variable to hold our password
my_password = ''
#Loop throug... |
price = 0
avgprice = 83
import time
name = input("What is your name: ")
print("We offer 3 different sizes of pizza, 6 ince ,9 ince or 12 inch")
choice1 = input("Pizza size(inch): ")
if choice1 == "6":
price += 20
elif choice1 == "9":
price += 30
elif choice1 == "12":
price += 40
else:
price += 20
tim... |
import re
#正则表达式简介
#怎样验证一个字符串是日期YYYY-MM-DD格式?
#正则表达式:一些由字符和特殊符号组成的字符串,它们描述了重复模式,能够匹配多个字符串
def date_is_right(date):
return re.match("\d{4}-\d{2}-\d{2}", date) is not None
date1 = "2021-02-03"
date2 = "202-01-04"
date3 = "2022/05/05"
date4 = "20210707"
print(date1, date_is_right(date1))
print(date2, date_is_ri... |
# Tyrone Tong 39813123
import project5 as game
import copy
import random
import pygame
class board:
def starting_board(self) -> None:
''' This function creates the list if it is empty or has contents in it'''
user_input_lst = []
lst = []
built_row = []
contents_l... |
#!/usr/bin/python3
"""
Given a pile of coins of different values,
determine the fewest number of coins needed to meet a given amount `total`.
"""
def makeChange(coins, total):
"""
Return: fewest number of coins needed to meet `total`.
* If total is 0 or less, return 0.
* If total cannot be met... |
#! HERANÇA SIMPLES
# Conseguimos reutilizar a class Camera para um tipo espeficico de camera.
# Não é necessario criar novamente toda a classe.
# Implicitamente todas classe tem uma herança de object.
class Camera(object):
def __init__(self, marca, megapixels) -> None:
self.marca = marca
self.meg... |
'''
Metodos acessos a Campos - o objetivo principal de usar getters e setters em
programas orientados a objetos é garantir o encapsulamento de dados.
Adicionar lógica de validação em torno de obter e definir um valor.
'''
class Teste():
def __init__(self,valor):
self.valor = valor
def get_valor(self)... |
# Exercício Python #094 - Unindo dicionários e listas
#a) qtde pessoas b) media de idade c) as mulheres cadastradas d)Lista de pessoas acima da media de idade
galera = list()
pessoa = dict()
soma = media = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('\nNome: ')).upper()
pessoa['id... |
#! Utilizando TRY CATCH - TRATAMENTO de ERROS
""" try:
meses = [1,2,3,4,5,6,7,8,9,10,11,12]
print(meses[14])
except IndexError as erro:
print('\nDigite um valor válido !')
print(erro) #conseguimos verificar o erro
"""
#! 02 - Caso precise tomar ação. FINALLY SEMPRE IRA RO... |
# -=-=-=-=- Sistema de login em Python -=-=-=-=-
from os import system
from colorama import init, Fore, Back, Style
from getpass import getpass
from time import sleep
init(autoreset= True)
#criar a o menu de opções
def exibir_menu():
print(Fore.GREEN + ''' Bem Vindos ao projeto
Sistema de Logi... |
#! HERANÇA MULTINIVEL
#evitar vários niveis, cada filho adicionado mais complexidade.
#! HERANÇA MULTIPLA
#irá herdar de duas classes
class Pessoa:
nome = 'Sou uma pessoa.'
def convidar():
print('Ola sou uma pessoa, vamos sair ?')
class Profissional:
nome = 'Sou um profissional.'
def convida... |
#Emprestimo bancário - Pergunte o valor da casa, o salario do comprador e a qts anos.
#A prestação não pode passar 30% do salario
valor_casa = float(input('\n Qual o valor da casa?\n'))
salario = float(input('\n Qual o valor do seu salario ? \n'))
anos = int(input('\n Em quantos anos será o emprestimo ?\n'))
par... |
# SQL - Structured Query Language
#db.sqlite3
import sqlite3
#criar conexão no banco de dados
with sqlite3.connect('artistas.db') as conexao:
sql = conexao.cursor()
#Check se a tabela existe no banco. fetchall cria uma lista com todas as tabelas.
listofTables = sql.execute(
''' SELECT name FROM s... |
print("Este programa calcula la distancia entre dos puntos en un plano bidimencional ")
print("Por favor inserte las cordenadas del primer punto")
x1 = int(input("x1: "))
y1 = int(input("y1: "))
print("Ahora inserte las cordenadas del segundo punto")
x2 = int(input("x2: "))
y2 = int(input("y2: "))
distance = ((x2 -... |
import random
def game(n1, n2):
lim1 = n1
lim2 = n2
answer = bool()
while answer == False:
number = random.randint(lim1,lim2)
print("The number I'm thinking is: ", number)
feedback = input("The number you're thinking is: ")
feedback = feedback.lower()
... |
print(" Escriba un numero de pies\n")
unit_foots = int(input("ft: "))
yards = unit_foots/3
inches = unit_foots*12
cm = inches*2.54
meters = cm/100
print("Su numero de pies equivale a: \n", yards,"Yardas, ",inches, "pulgadas, ", cm, "Centimetros, ", meters, "metros " ) |
#program that prints out a double half-pyramid
#of a specified height, per the below.
def main():
nline = 1
while True:
height = int(input("Height: "))
if height > 0 and height < 23:
break
for i in range (height):
print(" " * (height - nline),
'#' * nline,'',... |
# This script demonstrates how to create directories
import os
# This function creates [number] directories under root
def mkdir( root, number ):
for i in range(0, number):
dirname = root + "/" + str(i)
os.mkdir( dirname )
def main():
root = "/Users/liuyuan/temp/foo/"
os.mkdir( root )
... |
"""GIVEN three positive integers representing three representatives
of a population who are, respectively, dominant homozygous, heterozygous and
recessive homozygous for an allele RETURN the probability that two randomly
selected individuals mating will produce offspring that have(and manifest) the
dominant allele""... |
import os
import sys
def removeEmptyDirectories(curPath):
dir_list = os.listdir(curPath)
if dir_list:
for i in dir_list:
dir = os.path.join(curPath, i)
if os.path.isdir(dir):
removeEmptyDirectories(dir)
if not os.listdir(curPath):
... |
class Room:
def __init__(self, name, desc):
self.name = name
self.desc = desc
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.items = []
self.hidden_items = None
self.hidden_rooms = None
self.is_dark = False
... |
'''
Initialize your list and read in the value of followed by lines of commands where each command
will be of the types listed above. Iterate through each command in order and perform the
corresponding operation on your list.
Example:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print... |
""" Find the number closest to 0
Simpler solution to the "Temperature closest to zero problem"
Sample inputs:
-40 -5 -4 -2 2 4 5 11 12 18
7 -10 13 8 4 -7.2 -12 1 -3.7 3.5 -9.6 6.5 -1.7 -6.2 7
-273
"""
import sys
try:
print("Enter the list of numbers: ")
temps = list(map(float, input().split()))
n = len(t... |
from Entity import Entity
import sys, os
clear = lambda: os.system('cls')
playerName = input("What is your name?: ")
Player = Entity(playerName)
Opponent = Entity()
PlayerControl = 1
battling = True
while(Player.health > 0 and Opponent.health > 0 and battling == True):
#Clear screen
clear()
#Print sta... |
#!python3
import os,shutil
#to append a zip file newzip = zipfile.zipfile('new.zip','a')
alpha_string='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
currentpath = 'C:\\Users\\Starkey\\Desktop'
for folderN, subfolder, filename in os.walk('C:\\Users\\Starkey\\Desktop\\folder1'):
#for i in str(filename).strip... |
'''
Created on Dec 31, 2017
@author: jghuf
'''
import time
# if number is divisible by 20 than it also is divisible by 2 etc,
divList = [11, 13, 14, 16, 17, 18, 19, 20]
def number(limit):
for num in range(limit,999999999,limit):
if all((num % i == 0) for i in divList):
return num
if __name... |
#file Exercise.py
class Exercise():
_registery = []
def __init__(self, name, time):
self._registery.append(self)
try:
if len(name) <= 1:
raise ValueError('Invalid name')
else:
self.name = name
except ValueError:
... |
import time
# Using time.sleep in a forloop does not guarantee exactly 1 sec.
t = time.time()
for i in range(100):
print("delta t:", time.time()-t)
t = time.time()
time.sleep(1)
"""
# This results in a cumulative error
zero_time = time.time()
for i in range(100):
time.sleep(1)
print("delta t:"... |
# hello world in a for loop
import time
for i in range(1,6):
print(i, "hello")
time.sleep(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.