text stringlengths 37 1.41M |
|---|
# from tkinter import *
# root = Tk()
# root.geometry("100x100")
# btn = Button(root, text="Button1",bd= '5',command=root.destroy)
# btn.pack(side="bottom")
# root.mainloop()
# import everything from tkinter module
from tkinter import *
# create a tkinter window
root = Tk()
# Open window having dimension 100x... |
#!/usr/bin/python
import socket
WEB_HOST = socket.gethostname()
PORT = "8080"
def main():
request = "GET / HTTP/1.1\r\n" \
"Host: " + WEB_HOST + "\r\n" \
"Accept: text/html\r\n\r\n"
print(request)
s = socket.socket(
socket.AF_INET, socket.SOCK_ST... |
#User function Template for python3
import math
class Solution:
def digitsInFactorial(self,N):
# code here
if(N<0):
return 0
else:
count = 0
for d in str(math.factorial(N)):
count +=1
return count
#{
# Driver Code S... |
def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
adult=no_of_adults*37550
child=no_of_children*(37550/3)
sum=adult+child
after_tax=sum+(7*sum)/100
total_ticket_cost=after_tax-(10*after_tax)/100
return total_ticket_cost
#Provide different values f... |
def encode(s):
# changed string
newS = ""
# iterate for every characters
for i in range(len(s)):
# ASCII value
val = ord(s[i])
#if k-th ahead character exceed 'z'
if val + 5>122:
newS += chr(96 + (val - 117))
else:
newS += chr(val + 5)
print (newS)
# drive... |
list_of_airlines=["AI","EM","BA"]
airline="AI"
if airline in list_of_airlines:
print("Airline found")
else:
print("Airline not found")
|
class Solution:
def immediateSmaller(self,arr,n,x):
#return required ans
smallest = -1
for i in arr:
if(i>smallest and i<x):
smallest = i
if smallest != -1:
return smallest
return -1
... |
#Input 1:
#Enter your PlainText: All the best
#Enter the Key: 1
#Expected Output : The encrypted Text is: Bmm uif Cftu
#Explanation
#The function Caesar(int key, String message) will accept \
#plaintext and key as input parameters and returns its
#ciphertext as output.
def ceaser(text, key):
resul... |
#arr[] = {1,2,3,4,5}
#Output: 2 1 4 3 5
class Solution:
#Complete this function
#Function to sort the array into a wave-like array.
def convertToWave(self,arr,N):
#Your code here
arr.sort()
for i in range(0,N-1,2):
arr[i], arr[i+1] = arr[i+1], arr[i]
#{
# ... |
#Code1
print("code-1")
def func6(a,b,c):
res_avg=(a+b+c)/3
return res_avg
print("1st invocation of code-1")
func6(6,8,10)
print("returned value is not assigned to any variable")
print("------------------------------------------------")
print("2nd invocation of code-1")
average=func6(10,15,20)
print... |
year = int(input())
if ((year%400 == 0) or ((year%4 ==0) and (year%100 != 0))):
print("Leap year")
else:
print("Not a leap year") |
#Every character in the input string is followed by its frequency.
#Write a function to decrypt the string and find the nth character of the decrypted string. If no character exists at that positionthen then return "-1".
#For eg:- If the input string is "a2b3" the decrypted string is "aabbb".
#Note: The frequency of... |
#Given a maximum of 100 digit numbers as input,
#find the difference between the sum of odd and
#even position digits
import math
num = [int(d) for d in str(input("Enter your number: "))]
even, odd = 0,0
for i in range(0, len(num)):
if i%2 == 0:
even = even + num[i]
else:
odd = odd ... |
def function_name(name,num):
print('Hello '+name)
print(num)
function_name('name',34)
#help(function_name)
def check(str):
if 'dd' in str:
return True
else:
return False
ret = check('dd in it')
print(ret) |
def gensqre(n):
for x in range(n):
yield x**2
for x in gensqre(10):
print(x)
h="hello"
g=iter(h)
print(next(g))
print(next(g))
print(next(g))
|
def check(str):
if 'dd' in str:
return True
else:
return False
ret = check('dd in it')
print(ret)
def check2(str):
return 'dd' in str
print(check2('dd in it')) |
word="abcd"
for item in enumerate(word): #it will simply output the elemnts of the index and the index number according to the index
print(item)
#or just
for index,letter in enumerate(word):
print(index)
print(letter)
print('\n') |
def pig_atin(w):
first_letter=w[0]
if first_letter in 'aeiou' :
return w+'ay'
else:
return w[1:]+w[0]+'ay'
print(pig_atin('appale'))
print(pig_atin('ppale'))
|
from tkinter import *
root = Tk()
# code to add widgets and style window will go here
root.geometry("500x650")
root.title("Ticket Sales (Uthmaan Breda)")
root.config(bg="black")
ticket = PhotoImage(file="ticket.png")
img = Label(root, image=ticket, bg="black", fg="white")
img.place(x=120, y=5)
# create class
clas... |
#Write a program to generate 5 random integers between 1 to 20 such that numbers should be unique
import random
s = set()
while len(s)<5:
s.add(random.randint(1,20))
print(s) |
#Python Program to Check Whether a Number is Positive or Negative.
num = int(input("Enter the number"))
if num >0:
print("Positive")
else:
print("Negative")
|
#Python Program to Calculate the Number of Upper Case Letters and Lower Case Letters in a String.
str1 = str(input("Enter the string"))
L,U = 0,0
for i in str1:
if i.isupper():
U = U+1
elif i.islower():
L = L+1
else:
pass
print("No. of Upper case is ",U)
print("No. of Lower case is "... |
#Python Program to Read a number n and Compute n+nn+nnn.
n = int(input("Enter the value of n"))
nn = str(n)+str(n)
nnn = str(n)+str(n)+str(n)
n = n +int(nn)+int(nnn)
print("value of n is ",n) |
from . import opcodes
from ..java import opcodes as JavaOpcodes
class Command:
"""A command is a sequence of instructions producing a distinct result.
The `operation` is the final instruction that yields a result.
A series of other instructions, known as `arguments` will be used
to execute `operation... |
class Board:
"Creates and displays the 15x15 Matrix based gridded Scrabble board."
def __init__(self):
#Creates a 2-dimensional array to form the game board, as well as adding the premium points squares.
self.board = [[" " for i in range(15)] for j in range(15)]
self.add_premium... |
# Contains all piece classes for chess 3D
from constant import *
from utils import *
board = [[([None] * 8) for row in range(8)] for i in range(2)]
check = False
# the board keeps track of the locations of all the pieces
class Piece(object):
def __init__(self, color, modelPath, pos, node, scale=1, rotation=0):
... |
# def my_func(x, y, z):
# try:
# sorted_list = [x, y, z]
# sorted_list = sorted(sorted_list)
# return print(int(sorted_list[-1]) + int(sorted_list[-2]))
# except ValueError:
# return print('You have entered string')
#
#
# my_func(5, 2 , 1)
#записал себе для красоты
def my_func(x... |
from math import factorial
# def fact():
# global n
# n = int(input('Input number: '))
# yield factorial(n)
#
# f = fact()
#
# for i in f:
# print(i)
# c = 0
# for el in fact(n):
# if c < n:
# print(el)
# c +=1
# else:
# break
def fibo_gen():
global num, user_num
... |
from itertools import count
my_file = open('05_02.txt', 'r')
i = 1
for line in my_file:
if line == '\n':
line = line.rstrip('\n')
print(f"Line {i} doesn't contain words")
i +=1
else:
line = line.rstrip('\n')
word_count = line.count(' ') + 1
... |
#подсмотрел и добавил реализацию ошибки некорректного месяца
user_month = int(input('Insert month count: '))
month_dict = {
'spring': [3, 4, 5],
'summer': [6, 7, 8],
'autumn': [9, 10, 11],
'winter': [12, 1, 2]
}
while user_month < 0 or user_month > 12:
user_month = int(input('You have entered wron... |
class MyList:
print_list = []
# Попробуем сделать исключение как класс в классе..
@staticmethod
class NotFloatExcept(Exception):
def __init__(self, txt):
self.txt = txt
# Проверим что вновь введенная строка является числом, если да, перобразуем к числовому типу
def __is_flo... |
user_number = int(input('Insert nubmer: '))
max_figure = 0
num = user_number
while num >0:
digit = num % 10
if digit > max_figure:
max_figure = digit
if max_figure == 9:
break
num = num // 10
# max_figure = 0
# dozens = None
# units = 0
# if user_number == 0:
# max_figure =... |
#Problem 10 from Project Euler
#http://projecteuler.net/problem=10
import math
import sys
#Had to set the recursion higher otherwise the maxmum would be reached.
#Efficiency was not attempted, although it will be in the future.
sys.setrecursionlimit(7000)
#Function that returns the sum of the prime numbers under 20000... |
#Problem 15 from Project Euler
#https://projecteuler.net/problem=15
#Thanks ronbrz for suggesting I try Pascal's Triangle
#Create a size x size array filled with 0's
def initializeLattice(size):
baseLattice = [[0 for x in range(size+1)] for y in range(size+1)]
return baseLattice
#Fill the edges of the lattic... |
"""
file: run.py
autor: PC
"""
from misvariables import *
# uso de condicional simple
nota = input("Por favor ingrese la primera nota: ")
nota2 = input("Por favor ingrese la segundsa nota: ")
# Se convierte en entero las variables cadena
nota = int(nota)
nota2 = int(nota2)
# Estructuras condicional Si-Entonces
... |
import random
# Запрашивать у пользователя команду.
# В зависимости от введенной команды выполнять действие.
todos = {}
HELP = '''
* help - напечатать справку по программе.
* add - добавить задачу в список (название задачи запрашиваем у пользователя).
* show - напечатать все добавленные задачи.
* random - добавить сл... |
#!/usr/bin/env python
#--*-- coding: utf-8 --*--
#合并两个有序列表,因为是一个列表当作两个列表,所以需要注意界限
#注意mid是属于左边列表还是右边的
#注意最后按照left到right的顺序赋值回来
def merge(a, left, mid, right):
low = left
high = mid + 1
tmp = []
while low <= mid and high <= right:
if a[low] <= a[high]:
tmp.append(a[low])
l... |
#基本python规则
#第一个示例
print("Hello,world!")
#变量
a=10 #整数 十进制:21,八进制:025,十六进制:0x15
b="你好" #字符串
c=True #布尔数
d=1.2 #浮点数
f=1+1j #复数
#查看类型
print(type(a))
z=int(d) #强制类型转换 str float bool
# 1.为什么区分对象类型?
# 不同类型对象运算规则不同
# 如:整数的加法和字符串的加法含义不同
# 2.不同类型对象在计算机内表示方式不同
# 如:整数和字符串
# 3。为何区分整数与浮点数?
# 浮点数表示能力更强
# 浮点数有精度损失
# CPU... |
from turtle import Turtle,mainloop
def main():
#设置窗口信息和turtle画笔
turtle.title('数据驱动的动态路径绘制')
turtle.setup(800,600,0,0)
pen=turtle.Turtle()
pen.color('red')
pen.width(5)
#pen.shape('turtle')
pen.speed(5)
#读取数据文件到列表result中
result=[]
file=open('C:\\Users\Devil\Desktop\pytho... |
'''
Created on Sep 14, 2014
@author: melvic
It's very simple
Scissors cuts paper
Paper covers rock
Rock crushes lizard
Lizard poisons Spock
Spock smashes scissors
Scissors decapitates lizard
Lizard eats paper
Paper disproves Spock
Spock vaporizes rock
And as it always has been
Rock crushes scissors
'''
def winner... |
def number_base(n,k):
s=''
while n:
s = s+str(n%k)
#print s
n=n/k
return s[::-1]
def is_palindrome(s):
length = len(str(s))
for x in xrange(0,length):
if str(s)[x]!=str(s)[length-1-x]:
return 0
return 1
sum1 =0
n,k=map(int,raw_input().split())
for x in xrange(1,n+1):
ans1 = is_palindrome(x)
ans2 = i... |
from spy_details import spy, Spy, chat, friends #transferring data from spy_details file to main
from steganography.steganography import Steganography #To hide information in plain sight
from datetime import datetime
default_status = ["Hello! friends what's up","what a cool weather","Hanging out with music","what a bus... |
#Course:CS2302
#aAuthor:Daniela Flores
#Lab1
#Instructor:Olac Fuentes
#T.A: Dita Nath
#date of last Mod: 2/8/19
#purpose of program: in this program I had to write recursive methods that'll draw various shapes.
import matplotlib.pyplot as plt
import numpy as np
import math
#the next two methods draw circles ... |
from random import randint
class Encrypt:
def __init__(self, data, pin):
self.data = list(data)
self.pin = pin
self.ceaser = []
def build(self):
len_pre = (int(self.pin[0]) + int(self.pin[2])) \
if (int(self.pin[0]) + int(self.pin[2])) else 4
len_app = (... |
# 1 - imports / bibliotecas
import json
# 2 - Classe
# 3 - Métodos e Funções
def print_hi(name):
print(f'Oi, {name}') # a partir do Python 3
def calcular_area_do_retangulo(largura, comprimento):
return largura * comprimento
def calcular_area_do_quadrado(lado):
return lado ** 2
de... |
from bs4 import BeautifulSoup
import html
import logging
import re
def __parseHTML(page_html: str) -> dict:
"""Function to parse EDGAR page HTML, returning a dict of company info.
Arguments:
page_html {str} -- Raw HTML of page.
Returns:
dict -- Structured dictionary of company at... |
"""gör om ordet till en lista"""
def word_to_list (k):
letterno = 0
letter_list = []
while len(letter_list) != len(k):
letter_list.append(k[letterno])
letterno = letterno + 1
return letter_list
"""kollar om bokstav finns med i ordet"""
def check_letter(n, b):
letterno... |
#!bin/usr/python
class NumberConverter(object):
def __init__(self):
self.TRANSLATE = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
... |
from ticket_rule import TicketRule
import math
file = open("puzzle_input.txt", "r")
lines = [line.rstrip('\n') for line in file]
# PREPARATION
rules = []
nearby_tickets = []
section = 0
for line in lines:
if line == "your ticket:" or line == "nearby tickets:":
section += 1
continue
if line and... |
# Java 面向对象编程的
# 设计模式 -----接口
# 接口类: python原生是不支持的
# 抽象类 python 原生支持的
from abc import abstractmethod,ABCMeta
class Payment(metaclass=ABCMeta):
@abstractmethod
# class Payment():
def pay(self,money):
raise NotImplemented #没有实现此方法
class Wechat(Payment):
def pay(self,money):
prin... |
# Hangman(행맨) 미니 게임 재작(1)
# 기본 프로그램 제작 및 테스트
import time
# csv 처리
import csv
# 랜덤
import random
# 사운드 처리
import winsound
# 처음 인사
name = input("What is your name?")
print("Hi, " + name, "Time to play hangman game!")
print()
time.sleep(0.5)
print("Start Loading...")
print()
time.sleep(0.3)
# CSV 단어 리스트
words = []
... |
# 제너레이터
# iterator객체의 한 종류 (next함수호출)
# 만드는 방법 : 제너레이터 함수(function) 제너레이터 표현식(expression)
def gen_num(): # 제너레이터 함수정의
print('first number')
yield 1 # yield가 하나라도 들어가면 제너레이터가 됩니다.
print('second number')
yield 2
print('third number')
yield 3
# 제너레이터 함수를 호출해도 실행하지 않고 제너레이터객체를 만들어 변수에 담는다.
gen = ... |
import sqlite3
#On cree une connection a la bd et on cree la table si besoin
def init():
# Create db if not exist
con = sqlite3.connect('hl.db')
cur = con.cursor()
# Profile table
cur.execute("""CREATE TABLE IF NOT EXISTS profile
(id integer primary key, name text)
""")
con.commit()
|
def common_letter():
str1 = input('enter a string:')
str2 = input('enter a string:')
s1 = set(str1)
s2 = set(str2)
lst = s1 & s2
print(lst)
common_letter()
|
from board import Board
from player import Player
class Game:
def __init__(self):
self.board = Board(7,6)
self.players = []
self.turn = 0
def play_game(self):
self.players.append(Player('x'))
self.players.append(Player('o'))
while True:
self.... |
# To-do
# write a piece that throws water master out of the kingdom if he tries to input a negative number
# if there is a drought make sure that the first line has a bit that reads in the farmers who rand out of water
# add a "run the mode" option!
import random
import cs50
def print_introductory_message():
pr... |
#(1)
#Raising Exceptions
#raise Exception('This is the error message.')
#(2)
#def boxPrint(symbol, width, height):
# if len(symbol) != 1:
# raise Exception('Symbol must be a single character string.')
# if width <= 2:
# raise Exception('Width must be greater than 2.')
# if height <= 2:
# rai... |
#(1)
#printing list contents
#def printspamlist(list):
# for i in range (0,4,1):
# print(list[i])
#spam = ['cat', 'bat', 'rat', 'elephant']
#printspamlist(spam)
#print(spam[0:2])
#print(spam[0:-1])
#print(spam[:2])
#print(spam[1:])
#print(spam[:])
#print(len(spam))
#spam[1] = 'aardvark'
#print(spam[1])
#spam[... |
n = int(input())
field = []
for i in range(n):
row = []
for j in range(n):
row.append(int(input()))
field.append(row)
k = int(input())
for i in range(k):
x = int(input())
y = int(input())
field[y][x] -= 4
for j in range(n):
for m in range(n):
if (y - 1 <= j <= y... |
line = input().lower()
max_entries = 0
count = 0
for char in line:
for character in line:
if character == char:
count += 1
if count > max_entries:
max_entries = count
count = 0
print(max_entries)
|
N = int(input())
numbers = []
for i in range(N):
numbers.append(int(input()))
# Для сортировки воспользуемся алгоритмом Шелла
last_index = len(numbers) - 1
step = len(numbers) // 2
while step > 0:
for i in range(step, last_index + 1, 1):
j = i
delta = j - step
while delta >= 0 and numbe... |
M = int(input())
lessons = []
for i in range(M):
present_number = int(input())
students_present = []
for j in range(present_number):
students_present.append(input())
lessons.append(students_present)
for student in lessons[0]:
is_always_present = True
for i in range(1, len(lessons)):
... |
try :
hour = float(input('Enter Hours:'))
rate = float(input('Enter Rate:'))
except :
print('Error, please enter numeric input')
quit()
pay = None
if hour <= 40 :
pay = hour * rate
else :
pay = 40 * rate + (hour - 40) * 1.5 * rate
print('Pay:',pay) |
hour = float(input('Enter Hours:'))
rate = float(input('Enter Rate:'))
pay = None
if hour <= 40 :
pay = hour * rate
else :
pay = 40 * rate + (hour - 40) * 1.5 * rate
print('Pay:',pay) |
string1 = "he's "
string2 = "probably "
string3 = "pinning "
string4 = "for the "
string5 = "fjords"
print(string1 + string2 +string3 + string4 + string5)
print("he's ""probably ""pinning ""for the ""fjords")
print("Hello " * 5)
today = "saturday"
print("day" in today) #True; in operates a lot like the .includes() ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Module summary
Attempts to detect if a password(s) passed meets requirements according to the The National Institute of Standards and Technology
"""
#import
import re #used to replace non ascii
import sys #used to read from stdin
import argparse #create a help automag... |
import urllib.request
def download_file(download_url, filename):
response = urllib.request.urlopen(download_url)
file = open("Downloads/" + filename + ".pdf", 'wb')
file.write(response.read())
file.close()
if __name__ == "__main__":
url = "https://en.unesco.org/inclusivepolicylab/sites/default... |
import numpy as np
from datetime import date
'''
module for general purpose utility functions
'''
def string_to_value_or_nan(string_value, type):
''' convert string value to a value of type type which can be int, float or date
if string cannot be converted the value will be a np.NaN
Date format... |
from tkinter import *
from tkinter import ttk
# Tkinter using oriented-object desing
class HelloApp:
# Constroctor method
# single parameter is master, which is the main window
def __init__(self, master):
self.master = master
self.label = ttk.Label(master, text="Hello Tkinter!")
self.lab... |
print('Hello...')
L= [10,20,30,40,50,60]
try:
x = int(input('enter the first number'))
y = int(input('enter the second number'))
s = int(10)
s = 10 + 'abc'
# import sheetal
q = x/y
print(q)
print(L[1])
except ValueError:
print('I got value error')
y = int(input('enter the seco... |
# !/usr/bin/env python3
"""Foobar.py: Description of what foobar does.
__author__ = "Fu Linke"
__pkuid__ = "1800011782
__email__ = "1800011782@pku.edu.cn
"""
#定义一个铺砖函数,a,b分别为地面的长和宽,m,n分别为砖的长和宽
#由于m=n且能铺满时,铺法显然只有一种,本函数不予考虑,定义m!=n
#method代表铺法,alternative是代表地砖坐标的中间体
#ans是储存所有铺法的列表,gd是墙面/地板
def ocp(a, b, m,... |
import numpy as np
def dice_dist(n, d, p=False):
'''
returns a dictionary containing the probability distribution for a given dice combination, assuming fair dice
n = number of dice
d = number of faces on the dice
p = probability distribution of a single dice. if left blank, assumes a fair die
... |
from re import findall
##Question 1
s = "c'est Bien"
l1 = findall('[A-Z][a-z]+', s)
print(l1)
def handscape()
s = "Il Fera Beau Demain"
l1 = findall('[A-Z][a-z]+', s)
l2 = l1[0]
l3 = s.split()
print(l3)
print (l1)
print (l2)
print(l3)
s = "Onze ans déjà que cela passe vite Vous "
s += "vous étiez servis simplement d... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
iris = pd.read_csv('../input/Iris.csv')
iris.head()
# creating dependent and independent variables
X = iris.iloc[:,[1,2,3,4]]
y = iris.iloc[:,5]
# creating test and training sets
from sklearn.cross_validation import train_test_split
X_train, X_t... |
from datetime import datetime, timedelta
import time
def sort_by_start(list_of_periods):
if len(list_of_periods) == 0:
return []
if len(list_of_periods) == 1:
return list_of_periods
list_of_periods.sort(key=lambda period: period.start)
return list_of_periods
def merge(list_of_peri... |
print ("")
print ("")
print ("")
print (''' BEM VINDO A CALCULADORA DO FLAVIO 1,0v''')
ide = input("Digite seu nome: ")
print ('''
Seja bem vindo,''',ide)
nome = input (''' Por favor escolha sua operação:
-------------------
| + |
... |
#-*- coding:UTF-8 -*-
from make_shirt import get_format_name
zly = get_format_name('Li','sdd','Yunfei')
print(zly)
#列表翻转函数实现
list = ['1','2','3','4','5','6']
list.reverse()
print list
def reverse(names):
list = []
while names:
list.append(names.pop())
return list
list1=reverse(list)
print list1 |
# -*- coding: UTF-8 -*-
alien0 = {'color':'green','points':5}
print(alien0)
print(alien0.keys())
print(alien0['color'])
#添加元素
alien0['points_x'] = 0
alien0['points_y'] = 25
print(alien0)
alien1 = {'point_x':2,'point_y':25,'speed':'low'}
if (alien1['speed'] == 'low'):
x_increm = 1
y_increm = 2
elif (alien1['s... |
"""
try:
for i in ['a', 'b', 'c']:
print(i**2)
except:
print("Something went wrong")
finally:
print("I always run")
"""
"""
try:
x = 5
y = 0
z = x/y
except ZeroDivisionError:
print("You can't divide by 0")
except:
print("Something went wroong!")
finall... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: chris
#
# Created: 11-10-2017
# Copyright: (c) chris 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
from random ... |
class User:
def __init__(self, username, email_address):
self.name = username
self.email = email_address
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balan... |
import time
import random
# Heading
print("\n")
print(" *************************** ")
print(" * * ")
print(" * CHALLENGE YOUR GK * ")
print(" * * ")
print(" *************************** ")
time.sleep(... |
"""
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
"""
import re
import functools
def wordify_number(n):
... |
"""
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find... |
# a collection of functions related to prime numbers
def get_primes(n):
"""
Get all primes less than n.
>>> len(get_primes(10))
4
>>> len(get_primes(10000))
1229
>>> p_list = get_primes(1000000)
>>> len(p_list)
78498
>>> p_list[5]
13
>>> p_list[-6]
999931
"""
... |
"""
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; t... |
Idade_User= int(input("Digite sua idade:"))
Sal_User= float(input("Digite seu salrio:"))
Adicional_User= Sal_User*0.2
print("Sua idade :", Idade_User)
print("Seu salrio : R$", Sal_User)
print("Adicional: R$", Adicional_User)
print("Total: R$", Sal_User+Adicional_User) |
tentativas = 3
correto = False
while (tentativas>0) and not (correto):
user = input("Qual meu nome? ")
if user=="Caio":
print('Parabns, voc acertou!')
correto = True
else:
tentativas -= 1
print("Voc errou, suas tentativas restantes so:", tentativas) |
#集合的運算
#s1={3,4,5}#大括號
#print(3 in s1)#3在s1中? 有就印出true 沒就印出false
#print(10 not in s1)#10不在s1中
#s1={3,4,5}
#s2={4,5,6,7}
#s3=s1&s2# & : 交集 :取兩個集合中,相同的資料
#s3=s1|s2 # | : 聯集 :取兩個集合中的所有資料,但不重複取
#s3=s1-s2 # - : 差集 : 從s1中,減去和s2重疊的部分 #所以只印出3
#s3=s1^s2 # ^ : 反交集 : 取兩個集合中,不重疊的部分 #所以印出367
#print(s3)
#s=set("Hello")#把字串中的字母拆解成... |
'''
Given two directories as input (folder1 and folder2), the script will compare
the files they contain. It will:
(1) print to STDOUT the list of the files unique to folder1
(2) print to STDOUT the list of the files unique to folder2
(3) run MD5 hashing on the common files (meaning the files with the same name)
(4) d... |
#!/usr/bin/python3
def remove_char_at(str, n):
c = str
if n < 0:
return c
c = c[:n] + "" + c[n + 1:]
return c
|
#!/usr/bin/python3
""" 1-square.py
Square class
"""
class Square:
"""Square Class
Class
"""
def __init__(self, size):
"""__init__ Contructor
Contructor of class Square
Args:
size (integer): privete attribute for size Square
"""
self.__size = s... |
#!/usr/bin/python3
""" Object Square """
from models.rectangle import Rectangle
class Square(Rectangle):
""" class Square ihnertes Rectangle """
def __init__(self, size, x=0, y=0, id=None):
""" constructor """
Rectangle.__init__(self, width=size, height=size, x=x, y=y, id=id)
@property
... |
#!/usr/bin/python3
"""
My add module
add_integer: function that add two numbers
Return: the add of two intigers
"""
def add_integer(a, b=98):
""" Return the add of intigers
a and b are intigers
"""
if not isinstance(a, (int, float)) or isinstance(a, bool):
raise TypeError("a mu... |
#!/usr/bin/python3
"""0 read_file
"""
def read_file(filename=""):
"""
Keyword Arguments:
filename {file} -- text file (default: {""})
"""
with open(filename, mode="r", encoding="utf-8") as f:
x = f.read()
print(x, end="")
|
"""
agente.py
criar aqui as funções que respondem às perguntas
e quaisquer outras que achem necessário criar
colocar aqui os nomes e número de aluno:
39392, Joana Elias Almeida
39341, Nuno Miguel da Silva Coelho Fernandes
"""
import time
import math
#-----------------------------------------------------------------... |
# tuple is immmutable sequences of arbitrary objects
t = ("Norway", 4.953, 3)
print(t[0])
print(len(t))
for item in t:
print(item)
print(t + (338.0, 123e9))
print(type(t))
|
# Variable naming in Python
# Variables names must start with a letter or and underscore. Variable name may consist of letters, numbers and underscores. Variable name is case sensitive.
x = True # valid
9x = False # invalid
has_0_in_it = "Still Valid"
x=9
y=X*2 |
# Fixed XOR
# input bytes output bytes
def xorByteStrings(byteString1,byteString2):
# passing an iterable to the bytes constructor => a^b returns an integer
xordString = bytes(a^b for a,b in zip(byteString1,byteString2))
return xordString
if __name__ == "__main__":
# one way to do this is
hexStri... |
"""
Write a version of a palindrome recogniser that accepts
a file name from the user, reads each line,
and prints the line to the screen if it is a palindrome.
"""
import sys
def palindrome(word): return word == word[::-1]
def main():
file_path = input('Please enter file path:') # raw_input in Python 2
wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.