text stringlengths 37 1.41M |
|---|
dict1 = {"Key1":1, "Key2":2}
dict2 = {"Key2":2, "Key1":1}
print(dict1 ==dict2)
|
#Python script to hold functions generally useful for plotting
import numpy as np
import matplotlib.pyplot as plt
#Python function to return color map for contour plots that is blue for negative numbers and red for positive numbers.
#data_min and data_max are the minimum and maximum of the data respectively.
def get_... |
"""
Data analysis
"""
print("~="*20)
print("{:^20}".format("Análise dados de Entrada"))
print("~="*20)
numbersName = ("primeiro", "segundo", "terceiro", "último")
numbers = tuple(int(input(f"Entre com o {numbersName[i]} numeros: ")) for i in range(4))
pairNumbers = []
for number in numbers:
if number % 2 == 0... |
"""
Data Analysis
"""
print("~="*20)
print(f"{'Análise de Dados':^40}")
print("~="*20)
numbers = []
while True:
number = int(input("Digite um valor: "))
numbers.append(number)
print("-"*40)
continuos = str(input("Deseja continuar [s/n]: ")).lower()
print("-"*40)
if continuos in "n":
... |
"""
Radom numbers in grew order
"""
print("~="*20)
print(f"{'Números aleatórios em ordem crescente':^40}")
print("~="*20)
numbers = []
while True:
number = int(input("Digite um valor: "))
while number in numbers:
print(f"\033[0:30:41mValor {number} já adiciona!\033[m")
number = int(input("... |
X = " Hey Bro"
print(X)
print(X *4 +X +" How are you?")
X=X.swapcase()
print(X)
|
myf = open('myfile.txt')
print(myf.read())
print(myf.read())
print(myf.seek(0))
print(myf.readlines())
print(myf.seek(0))
print(myf.readlines())
print(myf.seek(0))
print(myf.readline())
myf.close()
myf = open('myfile.txt',mode='r+')
myf.write('\nWrote a line')
print(myf.read())
MyFile = open('test.txt', mode ='w')
My... |
# -*- coding: utf-8 -*-
"""
Created: Apr 15 2021
@author: Ryan Clement
Day #1: String manipulation.
"""
print("Day 1 - String Manipulation")
print('String Concatination is done with the "+" sign.')
print('e.g. print("Hello " + "world")')
print("New lines can be created with a backslash and n.")
|
# -*- coding: utf-8 -*-
"""
Created: Apr 15 2021
@author: Ryan Clement
Day #2: BMI Calculator.
"""
print("Welcome to the Body Mass Index (BMI) Calculator.")
height = float(input("Enter your height in meters (m): "))
weight = float(input("Enter your weight in kilograms (kg): "))
print("\nBMI = ",int(weigh... |
# -*- coding: utf-8 -*-
"""
Created: Apr 28 2021
@author: Ryan Clement
Day #8: Prime Number Checker.
"""
def prime_checker(number):
max = number//2 + 1
for i in range(2,max):
if number%i == 0:
print(f"{number} is not a prime number.")
return
print(f"{number}... |
# -*- coding: utf-8 -*-
"""
Created: Apr 18 2021
@author: Ryan Clement
Day #3: Leap Year.
"""
print("Welcome to the Leap Year checker!")
year = int(input("Please enter a year: "))
n = "\n"
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
print(n,year,"is a leap year.")
... |
class Coord:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def distance(self):
return abs(self.x) + abs(self.y)
def __repr__(self):
return f"({self.x}, {self.y})"
class LineSegment:
def __init__(self, start, end):
self.start = start
self.end = end... |
#!/usr/bin/env python
ip_addr = raw_input("Please enter IP address: ")
my_list = ip_addr.split(".")
my_list[-1]= "0"
".".join(my_list)
print my_list
octet1 = my_list[0]
octet2 = my_list[1]
octet3 = my_list[2]
octet4 = my_list[3]
o1 = int(octet1)
o2 = int(octet2)
o3 = int(octet3)
o4 = int(octet4)
o1 = bin(o1)
o2 = bin(... |
from utils.utils import swap
def quicksort(a, p, r):
if (p < r):
q = partition(a, p, r)
quicksort(a, p, q-1)
quicksort(a, q+1, r)
return a
def partition(a, p, r):
x = a[r]
i = p-1
for j in range(p, r):
if (a[j] <= x):
i = i+1
s... |
# post = "Once upon a time there was a boy named Ali Neaz. He was very stupid and still he is a stupid"
post = input("Enter the post: \n")
if "Ali Neaz" in post or "ali neaz" in post:
print("they are talking about Ali Neaz")
else:
print("they are not talking about Ali Neaz")
|
#Write a Python program to read specific columns of a given CSV file and print the content of the columns.
import csv
f=open('D:\just\jj.csv','r')
reader=csv.reader(f)
for column in reader:
print(column)
f.close() |
class bank:
def __init__(self,anumber,name,taccount):
self.anumber=anumber
self.name=name
self.taccount=taccount
self.balance=0
def dep(self):
amount=int(input("Enter the amount to deposit:"))
self.balance+=amount
print("The balance is:",self.bala... |
#Program to find sum of two integers
print("Enter the frist number:")
a=int(input())
print("Enter the second number:")
b=int(input())
s=a+b
print("The sum is:")
print(s)
|
#Write a Python program to write a Python dictionary to a csv file. After writing the CSV file
#read the CSV file and display the content.
f=open('D:\just\jj.txt','a')
import json
thisdict={"brand":"ford","company":"Mustang"}
result=json.dumps(thisdict)
f.write(result)
f.close()
f=open('D:\just\jj.txt','r')
... |
# Задача №1
# list_with_8 = []
# for dct in users:
# if dct['phone'][-1] == '8':
# list_with_8.append(dct['name'])
# print(*sorted(list_with_8), sep=' ')
# Задача №2
# Решение курильщика:
# lst = []
# for dct in users:
# if 'email' not in dct.keys():
# lst.append(dct['name'])
# el... |
from libs.primelib import Prime
import time
import math
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def main():
print('... |
from tkinter import *
import tkinter.messagebox
# 메인화면
myfile = open("person_Info.txt","a+")
win = Tk()
win.title('가천배달이 made by 태현,승건')
win.geometry('800x550+100+100')
win.resizable(False,False)
main = Frame(win,bg="#12EAFF",relief="solid",width=800,height=800)
register = Frame(win,bg="#12EAFF",relief="soli... |
import turtle
from random import *
def generate():
number = "0x"
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
for i in range(0, 6):
number = number + digits[randint(0, len(digits)-1)]
return number
def make_darker(color):
new_color = max(0, int... |
# Implementation of classic arcade game Pong
#Travis 3/22/15 python 1 class
#http://www.codeskulptor.org/#user39_mrXeadaGHl_0.py
import simplegui
import random
import math
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
PAD_WIDTH = 8
PAD_HEIGHT = 80
''... |
import csv
import sys
def remove_duplicates(new_csv, old_csv):
new_urls = []
old_urls = []
with open(new_csv, 'r') as file:
csv_reader = csv.reader(file)
for csv_row in csv_reader:
new_urls.append(csv_row[0])
print(f"No of urls in new csv :{len(new_urls)}")
with open(... |
# Create the empty list: baby_names
baby_names = []
# Loop over records
for row in records:
# Add the name to the list
baby_names.append(row[3])
# Sort the names in alphabetical order
for name in sorted(baby_names):
# Print each name
print(name)
|
# Create the empty set: baby_names_2011
baby_names_2011 = set()
# Loop over records and add the names from 2011 to the baby_names_2011 set
for row in records:
# Check if the first column is '2011'
if row[0] == '2011':
# Add the fourth column to the set
baby_names_2011.add(row[3])
# Fin... |
# Import necessary modules
from collections import defaultdict
from datetime import datetime
# Create a dictionary that defaults to a list: locations_by_month
locations_by_month = defaultdict(list)
# Loop over the crime_data list
for row in crime_data:
# Convert the first element to a date object
date = datet... |
import sys
longest = 4
teams = sys.stdin.readlines()
for team in teams:
team = " ".join(team.split()[1:-8])
if len(team) > longest:
longest = len(team)
print("{:3s} {:<{}s} {:>2s} {:>3s} {:>3s} {:>3s} {:>3s} {:>3s} {:>3s} {:>3s}".format("POS", "CLUB", longest, "P", "W", "D", "L", "GF", "GA", "GD", "PTS"))
... |
#MAQUINA DE TURING
import sys
import time
ar = open("Datos12.txt", "w")
import random
from tkinter import*
from random import randint
arc = open("Datos12.txt", "w")
print("MAQUINA DE TURING:")
op = input("¿Qué modo desea utilizar? 1)Manual 2)Automático\n")
if op == "1":
cadena = input("Ingrese la cadena deseada: ")... |
frase = "Essa sera a Primeira turma de tecnicos em Informatica do IFSUL"
print(frase)
print("---------------------------------------------------------")
print(frase[21:53])
print("---------------------------------------------------------")
print(frase[42:])
print("---------------------------------------------... |
#2.15
#Faça um programa que escreva a seguinte frase
#“Feirão de automóveis: Toda linha FIAT com desconto de 25 % nos
#modelos Siena, Idea e Uno 2,10! Promoção valida até Sexta feira”
#A Marca, o desconto , os modelos preço e o dia limite da promoção
#devem ser informado.
#Imprima a frase formatando a string
... |
from tkinter import *
janela=Tk()
cor = StringVar(janela)
cor.set("black")
l = Label(background=cor.get())
l.pack(fill='both',expand=True)
def pinta():
l.configure(background=cor.get())
janela.title("Radiobutton Exemplo")
janela.geometry("300x300+600+200")
for txt,val in (("preto","black"), ("vermelho","r... |
class person:
def __init__(self,v1,v2,v3,v4):
self.nome = v1
self.rg = v2
self.idade = int(v3)
self.endereco = v4
def listar(self):
print ("")
print("Nome: ",self.nome,
"| RG: ",self.rg,
"| Idade: ",self.idade,
... |
#3.2- Crie uma função que receba como parâmetro uma lista , com
#valores de qualquer tipo .
#A função deve imprimir todos os elementos da lista numerando-os .
L = [5, 7, 2, 9, 4, 1, 3]
def numerar (lista):
lista.sort()
return lista
print(L)
print("-----------------------------------------------"... |
frase = "O pinto pia, a pipa pinga. Pinga a pipa e o pinto pia. Quanto mais o pinto pia mais a pipa pinga"
print(frase)
print("")
x = frase.count("pinto")
print("O pinto apareçe", x, "vezes na mensagem")
print("")
p=0
while(p>-1):
p=frase.find("pinto",p)
if p>=0:
print("Posição: %d" % p)
... |
senha = "o"
def password (senha):
if len(senha) != 8:
return "Senha não foi aceita! Senha deverá ter 8 digitos"
elif senha.islower()==False:
return "Senha não foi aceita! Letras Somente minúsculas"
elif senha.isalpha():
return "Senha não foi aceita! Ter letras e numeros"
... |
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
secret_number = 0
set_range = 100
remain_count = 0
# helper function to start and restart the game
def new_game():
"... |
import numpy as np
def get_image_matrix(images):
"""Converts a list of [H,W,C] images to a single image matrix by concatenation"""
rows = int(np.sqrt(len(images)))
cols = rows
image_rows = []
for i in range(rows):
image_rows += [np.concatenate(images[i*cols:(i+1)*cols], axis=1)]
image_... |
from tkinter import *
from tkinter import messagebox
import banco
def bt_Sair():
login.destroy()
def criar_Cadastro():
# Formulario de Registro
register.place(x=1000)
enter.place(x=1000)
estado.place(x=50, y=125)
estadoF.place(x=100, y=125)
user.place(x=50, y=75)
userF.plac... |
#!/usr/bin/env python
import time # sodass wir "sleep" zum warten benutzen können
import RPi.GPIO as io # importieren die GPIO library die wir installiert haben, aber nenne sie "io"
## setze GPIO mode auf BCM
## der Befehl nimmt GPIO number anstatt pin number
io.setmode(io.BCM)
## wir haben GPIO 23 genommen. Falls ... |
class Student:
def __init__(self, nombre):
self.nombre = nombre
self.__notas = []
def get_nota(self, indice):
nota = self.__notas[indice]
if nota > 11:
return nota
else:
raise Exception("Usted no puede ver esta nota")
def set_nota(self, ... |
class User:
def say_hello(self):
# 인사 메시지 출력 메소드
print(f"안녕하세요! 저는 {self.name}입니다!")
def login(self, my_email, password):
# 로그인 메소드
if(self.email == my_email and self.password == password):
print("로그인 성공, 환영합니다")
else:
print("로그인 실패, 없는 아이디거나 잘못된 ... |
# 계산기 클래스 (속성이 없는 메소드만 있는 클래스 )
class SimpleCalculator:
@staticmethod
def add(first_number, second_number):
return first_number + second_number
@staticmethod
def subtract(first_number, second_number):
return first_number - second_number
@staticmethod
def multiply(first_number,... |
class Solution:
def rotate(self, nums, k):
"""
:param nums: : List[int]
:param k: : int
:return: -> None
"""
"""
Do not return anything, modify nums in-place instead.
"""
# 方法1:三次反转
# n = len(nums)
# k %= n
# def revers... |
import itertools
# Objects included in this file:
# None
# Functions included in this file:
# # pairwise
def pairwise(iterable):
"""See: https://docs.python.org/3/library/itertools.html#recipes
s -> (s0,s1), (s1,s2), (s2, s3), ...
"""
a, b = itertools.tee(iterable)
next(b, None)
return list(... |
x = 250
y = 50
def euclidsAlgorithm(x,y):
if y == 0:
return x
else:
return euclidsAlgorithm(y, x % y)
print(euclidsAlgorithm(x,y))
|
import sqlite3
if __name__ == '__main__':
print("\nWelcome to Question 1")
print("Enter (1) for 'domestic shorthair'")
print("Enter (2) for 'british shorthair'")
print("Enter (3) for 'bobtail'")
stop = False
while (not stop):
userInput = input("Select one of the following breeds: ")
... |
from datetime import datetime, timezone
import humanize
def humanize_datetime(iso_string: str = None):
"""
From the iso-8601 formatted timestamp, Get a string representing the local time to the user
and a time delta like '2020-12-24 15:28:44 MST (28 seconds ago)'
:param iso_string: ISO-8601 formatted... |
import metodos as a
print("Ingrese el primer número")
n1 = int(input())
print("Ingrese el segundo número")
n2 = int(input())
res = a.sumar(n1,n2)
print("La suma es: " ,res)
res1 = a.restar(n1,n2)
print("El resta es: " ,res1)
res2 = a.dividir(n1,n2)
print("La división es: " ,res2)
res3 = a.multiplicar(n1,n2)
p... |
import playsound as ps
import numpy as np
import re
class Main_Menu:
def displayWelcomeMessage():
print("Thank you so much for your willingness to test our program!! This is a beta build of the HowToStudyKorean Listening Program.")
print("\nWhile a fancy interface undergoes development, we'll be utilizing ... |
"""
This module processes an input file and generates a list of all drugs, the total number of UNIQUE individuals
who prescribed the medication, and the total drug cost.
Input file:
The input file is in the following format:
id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost
1000000001,Smit... |
from keras.datasets import mnist
from keras.models import load_model
import numpy as np
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Вывод тестового изображения
print("Тестовое изображение")
for i in x_test[0]:
show = "".join(f"{j:3}" for j in i)
print(show)
# Загрузка сохраненной модели
model ... |
def max(x, y):
if (x < y):
return y
elif (x == y):
return ("the numbers are equal")
else:
return x
print(max(3, 4))
|
def unique_list(l):
x =[]
for i in l:
if i not in x:
x.append(i)
return x
print(unique_list([1,2,2,3,3,3,4,4,5,6])) |
from nltk import word_tokenize
def get_words(string, language='english'):
return word_tokenize(string, language=language)
def count_words(string, language='english'):
return len(get_words(string=string, language=language))
def count_english_words(x, vocabulary, case_sensitive=False):
if isinstance(x, (list, tu... |
print("Enter your hour: ")
hour=int(input())
min=str(hour*60)
print(min+" minute") |
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
ret... |
# Thenea Sun
# Sept. 19th
# assignment_two
# This is my second project, which I created a chat bot with codes, in order to get all the information that is
# required in the rubric
print("Hello! I am the artificial intelligence you are going to talk to in the next five minutes!")
print("My name is San!")
name_of_user... |
"""multiple arguments/argumnet ,here we can give multiple actual argument as a list and collect by using one formal argument by default it will take as list """
def mylist(integers):
s=0
for i in integers:
s+=i
print(s)
mylist([10,22,33,4,5,6,7,77])
|
"""method overloading"""
class student:
def function(self,name=None):
if name==None:
print("none came")
else:
print("hi")
s1=student()
s1.function() |
input = raw_input('Enter String: ')
count = 1
resultantStr = str()
finalStr = str()
length = len(input)
comparator = input[0]
lst = list()
for alphabet in input:
lst.append(alphabet)
for item in lst[1:length]:
if item == comparator:
count=count+1
else:
resultantStr = resultantStr + comparato... |
#1 when additional data structure is allowed:
str = raw_input('Enter the string to test: ')
if len(str) == len(set(str)):
print 'string has unique characters'
else:
print 'string has repeating characters'
#2 when additional data structure is not allowed: O(n) runtime
str = raw_input('Enter the string to test: ... |
# First Python Script
# By EG Miller
## Basic Python Things
my_integer = 3
my_decimal = 3.0
my_string = '3'
my_list = [1,2,'apple',19,-2.353,"..."]
my_dictionary = {'key':'value', 'lookup_key':'find_value'}
print("Hello world!")
## adding a few more lines to make a point
|
import numpy as np
poly=[float(x) for x in input().split()]
x=float(input())
print(np.polyval(poly, x))
|
i=1
sum=0
while i<=5:
sum=sum+i
i=i+1
print(sum)
|
# Total Sum: 417 print kara hai. Yeh isiliye print kia hai kyunki 10+16+9+10+56+78+98+43+21+76
# ka sum 417 hai.
i=1
sum=0
while 1<=10:
num=int(input("enter the number"))
sum=sum+num
i=i+1
print(sum) |
n=int(input("enter the number:"))
i=0
while i<=n:
print(i,end=" ")
i+=1
|
# all table.
num=int(input("enter the number"))
i=1
while i<=num:
j=1
while j<=10:
print(i,"*",j,"=",j*i)
j=j+1
print()
i=i+1 |
variable = input("State your name: ")
print("Hello " + variable + " !")
|
def number_coroutine():
while True:
x = (yield)
print(x)
co1 = number_coroutine()
next(co1)
co1.send(1)
co1.send(2)
co1.send(3)
# ------------------------------
def sum_coroutine():
total = 0
while True:
x = (yield total)
total += x
co2 = sum_coroutine()
print(next(co2... |
class Robot:
''' Robot Class ''' # Robot.__doc__
# class attribute
population = 0
__total_price = 0
def __init__(self, name, price):
self.name = name
self.price = price
Robot.population += 1
Robot.__total_price += price
print("name: {}, price: {}".format... |
def sorting(lis):
# using sort() to sort the list
lis.sort()
# displaying list after sorting
print ("List elements after sorting are : ")
for i in range(0, len(lis)):
print(lis[i])
return()
#output:
sorting([1,1,0,1,0,1,0])
List elements after sorting are :
0
0
0
1
1
1
1
or
# functio... |
import math
def sumto42():
while True:
t=0
for s in range(5):
s=input('enter the value')
t = t+s
print t
if t==42:
break
else:
print('try again')
... |
#A reminder on string multiplication
def string_mul():
res=('start|' + '_'*10 + '|end')
res1=('spam'*3)
return res, res1
#write a function named rwpos (start ,nsteps):
import random
def rwpos(start, nsteps):
comp = random.choice(range(start-nsteps, start+nsteps))
if comp == start:
... |
def sq(x):
return x**2
def sq1(x):
return [sq(x) for x in range(5)]
def sqmd(x):
return x%4
def sqmd1(x):
return [sqmd(x) for x in range(5)]
def mini(x):
return (x / 4.0)
def mini1(x):
return[mini(x) for x in range(4)]
#output:
>>> sq1(5)
[0, 1, 4, 9, 16]
>>> sqmd1(5)
[0, 1, 2, 3, 0]
>>> ... |
import random
def rwpos(a, b):
compgs = random.choice(range(a-b, a+b))
if compgs == a:
print("start is", compgs)
return 1
else:
print("start is", compgs)
return 1 + rwpos(a, b)
#output:
>>> rwpos(40, 4)
('start is', 39)
('start is', 43)
('start is', 42)
('star... |
def erdosIter(n):
count=0
count = count + 1
# a = []
if n == 1:
return ' '
if n%2 == 0:
n = (n/2)
#print n
#count=count+1
print n
#a.append(n)
#print a,
... |
#Countdown numbers game
import sys, random, itertools, time, cProfile, argparse
start = time.time()
parser = argparse.ArgumentParser(description="Solve the countdown numbers game")
parser.add_argument("-n", "--number_of_cards", type=int, default=6, choices=range(3,10), help="The number of cards drawn at random from t... |
import sys
def palidrome_check(n, N):
s = str(n)
if (len(s) != N):
s = "0" * (N - len(s)) + s
return s == s[::-1]
def dist_to_next_pali(n):
i = 0;
N = len(n)
n = int(n)
while not palidrome_check(n + i, N):
i+=1
return i
if __name__ == "__main__":
i = input()
wh... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 11:34:57 2014
@author: pruvolo
"""
# you do not have to use these particular modules, but they may help
from random import randint
import Image
import math
def build_random_function(min_depth, max_depth):
""" Creates a function with a set minimum and maximum dept... |
# -*- coding: utf-8 -*-
import sys
import random
def generate(degree, n_tests):
f = open('input', 'w')
f.write(str(degree) + ' ')
for i in xrange(degree + 1):
x = 0
while x == 0:
x = random.randint(-10,10)
f.write(str(x) + ' ')
f.write('\n')
f.write(str(n_tests) + '\n')
for i in xrange(n_tests):
... |
import numpy as np
import pandas as pd
import sys
import matplotlib.pyplot as plt
def plot_1(x, y, year):
fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(111)
ax1.set_ylabel('Rain Fall (mm)')
ax1.set_xlabel('Month')
ax1.set_title(f'Average Rain fall in Taipei in {year}')
... |
def main()
print ("This Program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1:"))
y = eval(input("Enter a 2nd number between 0 and 1:"))
t = eval(input("How many chaotic iterations do you want? "))
print ("Value # 1 | Value #2")
for i in range(t)
x ... |
# https://cs50.harvard.edu/x/2020/psets/7/houses/
'''
In import.py, write a program that imports data from a CSV spreadsheet.
Your program should accept the name of a CSV file as a command-line argument.
- If the incorrect number of command-line arguments are provided, your program should print an error and exit.
- Y... |
players = ['Jose', 'Abe', 'Hein', 'Roger']
print("Here are the first three players on my team:")
for player in players[ :3]:
print(player.title())
# Here are the first three players on my team:
#Jose
#Abe
#Hein
#PS C:\Users\joseu\Tutorials\Python>
|
# File ini digunakan untuk Tugas Latihan 1 pada materi Praktikum 3
n=int(input("Masukkan Nilai N : "))
import random
for x in list(range(1, n+1, 1)):
print(f"Data ke: {x} ->",random.uniform(0, 0.5))
print()
print("==============================")
print("= Nama : Abdul Aziz Anaoval =")
print("= NIM : 3120100... |
class Person(object):
def __init__(self,name,age,taste):
self.name = name
self._age = age
self.__taste = taste
def showperson(self):
print(self.name)
print(self._age)
print(self.__taste)
def _work(self):
print('工作')
def __away(self):
print(... |
def quiz():
ret = {'number_of_code_lines': 'unknown',
'member': 'unknown',
'paid_member': 'unknown'}
number_of_code_lines = raw_input('Hany sor kodot irtal az evben? ')
if not number_of_code_lines.isdigit():
print('Egesz szam megadasa kotelezo')
return ret
ret['n... |
class Human():
# __private - переменная
__privateVar = "this is __private variable"
def __init__(self):
self.className = "Human class constructor"
self.__privateVar = "this is redefined __private variable"
# public - доступен везде
def showName(self, name):
self.n... |
import unittest
import a0
class TestA0Classes(unittest.TestCase):
def test_rectangle(self):
"""Provided test for is_rectangle in starter code."""
tri_1 = a0.Polygon(3, [3, 4, 5])
self.assertEqual(tri_1.is_rectangle(), False)
rect = a0.Polygon(4, angles=[90, 90, 90, 90])
... |
import math
import numpy as np
from matplotlib import pyplot as plt
def func(x):
if x<=-2:
print("Minus inside the square root")
return None
if x==1:
print("You are dividing by zero")
return None
a=(((x/(1-x))*math.sqrt(6/(2+x)))-0.05)
return a
def graph_plot():
x=n... |
# Assume s is a string of lower case characters.
# Write a program that prints the number of times the string 'bob' occurs in s.
# s = 'azcbobobegghakl'
s = 'aqbobboboobobbbobobboobfobobobboboboboboobobbsbobbobobool'
#turn string into an array
#if i == b go to the next index if it == o do the same and if that inde... |
from math import *
y=int(input("Enter a year "))
if(y%4==0 and y%100!=0):
print("Yes, it is a leap year" )
elif(float(y%400)==0):
print("Yes, it is a leap year" )
else:
print("No, it is not a leap year" )
|
# File: Queens.py
# Description: HW 15
# Student Name: Melanie Sifen
# Student UT EID: ms69768
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 3/29
# Date Last Modified: 4/1
class Queens (object):
# initialize the board
def __init__ (self, n = 8, numOfBoards = 0):
self.board = []
... |
print("hello")
age =input("what is you current age")
age_as_int= int(age)
year=90-age_as_int
month=year*12
days=year*365
week=year*52
result=f"you have {year}year,{week}weeks,and {days}days,{month}months left.to survive"
print(result) |
studenten = {'Ahmad': 11.0, 'Giedo': 9.0, 'Abed': 10.5, 'niek': 12.0, 'mohammad': 8.0, 'Dj': 7.0, 'Nael': 4.5, 'Sudo': 3.0}
for student in studenten:
if studenten[student] > 9:
print('{:10}{}'.format(student,studenten[student])) |
a=int(input('primul nr '))
b=int(input('al doilea nr '))
c=int(input('al treilea nr '))
if a%2==0:
print(a,' par')
else:
print(a,' impar')
if b%2==0:
print(b,' par')
else:
print(b,' impar')
if c%2==0:
print(c,' par')
else:
print(c,' impar')
|
def remove_duplicates(word):
numbers_game = "".join(sorted(dict.fromkeys(word)))
return (numbers_game, len(word) - len(numbers_game))
print (remove_duplicates('aaabbbac'))
print (remove_duplicates('a'))
print (remove_duplicates('thelexash')) |
# Hello World program in Python
print "Hello World!\n"
def reverse(input):
size = len(input)
result = []
for i in range(0,size):
result.append(input[size-i-1])
continue
return result
print (reverse("92489014")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.