text stringlengths 37 1.41M |
|---|
print('Hello, welcome to trivia!')
ans = input('Are you ready to play (yes/no): ')
score = 0
total_q = 20
if ans.lower() == 'yes':
ans = input('1. Which Jamaican runner is an 11-time world champion and holds the record in the 100 and 200-meter race? ')
if ans.lower() == 'usain bolt':
score += 1
... |
#***URI 1010*** calculo de compra
c1 = input()#compra 1
c2 = input()#compra 2
lisC1 = []
lisC2 = []
lisC1 = c1.split(' ')#passando a string cortada a uma lista
lisC2 = c2.split(' ')
codP1 = lisC1[0]#usando os dados agora por unidade
nP1 = lisC1[1]#num de pecas 1
vP1 = lisC1[2]#valor do produto 1
codP2 = lisC2[0]
nP2 = ... |
print('================')
print('Calcula Salários')
print('================')
func = input('Digite o nome do funcionário: ')
salario = float(input('Digite o salário atual de {}: '.format(func.title())))
dep = input('{}, possui dependentes?[S/N] '.format(func.title()))
if dep.upper() == 'N':
salario = salario+sala... |
#***URI 1013*** saber qual e o maior numero entre tres
num = input()#guardando os tres em unica linha
lisNum = []
lisNum = num.split(' ')#separando-os
a = lisNum[0]#usando individualmente
b = lisNum[1]
c = lisNum[2]
num1 = int(a)#agr sao int
num2 = int(b)
num3 = int(c)
maiorN1N2 = (num1+num2+abs(num1-num2))/2#operacao ... |
import contextlib, csv, dataclasses, dataclassy, pathlib
from .dataclasses import MetaDataAnnotation, MyDataClass
from .misc import dummylogger
from .units.dataclasses import DataClassWithDistances
def readtable(filename, rownameorclass, *, extrakwargs={}, fieldsizelimit=None, filter=lambda row: True, checkorder=Fals... |
nome = input("O nome: ")
if "silva" in nome.lower():
print("Esse tem")
silv = nome.lower().find("silva")
if silv > -1:
print ("Esse nome contem Silva")
else:
print("Esse não é da família Silva") |
import sys
import os
import hmac
import hashlib
import json
import datetime
def generate_license():
if not os.path.exists('key.txt'):
print('No key text was found!')
input('Press Enter key to exit.')
sys.exit()
hid = None
with open('key.txt') as f:
hid = f.read()
... |
#problem set #1 part one
#
#A program that computes the credit card balance for one year
#Ezechukwu James I. - 10/11/2014
#Duration: about 3hours
#get variables from user
Card_Bal = float(raw_input("Enter the outstanding balance on your credit card: "))
Annual_Int_Rate = ((float(raw_input("Enter annual interest rate... |
# Solution to Queue problem with Threading
from queue import Queue
from time import sleep
from numpy import random
import threading
def main():
tasks_que = Queue(5)
item = tasks_que.get
i = 0
while True:
if not tasks_que.full():
tasks_que.put(threading.Thread(target=_new_functio... |
count = 0
def isVowel(char):
if char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u':
return True
return False
for var in s:
if isVowel(var):
count += 1
print("Number of vowels:" + " " + str(count)) |
import numpy as np
import pandas as pd
def AU_features(path,step):
"""
path = file path of a single AU file for a single subject example : AU_features('300_CLNF_AUs.txt')
returns pandas dataframe with the following info :
Data columns (total 25 columns):
AU01_r 6486 non-null float64
AU02_... |
# The classifier takes two lists of labels extracted by the labeler and decided whether they belong to the same news story or not.
# To do:
# - figure out a good weight assignment
# - !! false negatives are better than false positives !!
class Classifier():
entitiesWeight = 3
topicsWeight = 1
score = 0
... |
"""This module contains the main game game_loop and rendering for the game
"""
#imports
import pygame
import sys
from animation import *
pygame.init()
pygame.key.set_repeat(10, 10)
#constants
DISPLAY_SURF = pygame.display.set_mode([DISPLAY_WIDTH, DISPLAY_HEIGHT])
#classes
class Game():
def __init__(self):
... |
#! /usr/bin python3
# _*_ coding:utf-8 _*_
# Author: hujiaming
"""
这是一个用于测试使用Python连接MySQL数据库的文件
"""
import pymysql
conn = pymysql.Connect(host="127.0.0.1", port=3306, user="hujiaming", passwd="123456",db="hujiaming")
cursor = conn.cursor()
# cursor有三个属性:
# cursor.fetchone() “将结果集中的第一条取出“
# cuosor.fetchall() ”将所有的结果取出,... |
def get_start_state(g):
for n in g[0]:
if n.is_start_state==True:
return n
return -1
def get_accept_states(g):
l=[]
for n in g[0]:
if n.is_accept_state==True:
l.append(n)
return l
def print_graph(g):
nodes=g[0]
edges=g[1]
accept_states=[]
print ("vertices are: ")
for i in nodes:
if (i.is_accept... |
import datetime
day = datetime.date.today().strftime("%A")
month = datetime.date.today().strftime("%B")
day_of_month = datetime.date.today().strftime("%d")
year = datetime.date.today().strftime("%Y")
print("Today is %s, %s %s, %s" % (day, month, day_of_month, year))
'''
from datetime import datetime
print(datetime.... |
d = {"a": 1, "b": 2, "c": 3}
d = dict((k, v) for k, v in d.items() if v <= 1)
print(d)
|
#Write a script that iterates thorugh each of the 26 text files, checks if the letter inside the text
#file is in string "python" and puts the letter in a list if the letter is a character of "python".
import string
python_list = []
for letter in string.ascii_lowercase[0::]:
with open(letter + ".txt", "r") as file:
... |
#Print out the countries that have an area greather than 2,000,000 in the database.db file
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute('SELECT country FROM countries WHERE area > 2000000;')
rows = c.fetchall()
for row in rows:
print row[0]
conn.close()
'''
conn = sqlite3.co... |
#Create a program that aska the user to input values separated by commas and those values will be
#store in a separate line each in a text file
data = input("Enter values: ")
data_b = data.split(",")
with open("95.txt", "a+") as file:
for i in data_b:
file.write(i+"\n")
|
#It is also possible to indicate alignment and width within the format string.
# For example,
# if you wish to indicate a width to be left for a placeholder whatever the actual value supplied,
# you can do this using a colon (':') followed by the width to use.
# For example to specify a gap of 25 characters which c... |
some_string = 'Hello World'
print('String conversions')
print('-' * 20)
print('some_string.upper()', some_string.upper())
print('some_string.lower()', some_string.lower())
print('some_string.title()', some_string.title())
print('some_string.swapcase()', some_string.swapcase())
print('String leading, trailing spaces'... |
from math import *
cateto_1 = int(input("Primeiro cateto: "))
cateto_2 = int(input("Segundo cateto: "))
hipotenusa = int(input("Hipotenusa: "))
if(cateto_1 > 0 and cateto_2 > 0):
semiperimetro = (hipotenusa + cateto_1 + cateto_2) / 2
area_total = sqrt(semiperimetro * (semiperimetro - hipotenusa) * (semiperime... |
#!/usr/bin/python3
'''Learning to properly code'''
def main():
'''Main function'''
distance = "far away"
print("Over the hills")
print("and")
print(" far away")
for singleletter in distance:
print(singleletter)
if __name__ == "__main__":
main()
|
from SinglyLinkedList import Node
from SinglyLinkedList import LinkedList
class Stack:
'''
Inherits from the LinkedList class.
'''
def __init__(self):
LinkedList.__init__(self)
def __len__(self):
return LinkedList.__len__(self)
def _isEmpty(self):
return Li... |
import re
def is_polindrome(s):
# iterate through string like though array
# i didn't guess about 2 while loops(tried to do something with continue/break)
# i didn't guess about while loop condition!!!! and what does intersection mean
# incorrect: while i< len(s) and j > 0:
# i was also shy abou... |
#We decided to keep everything within the function so no data needed to be called
#in from outside the function, and it allowed us to minimize repeated code.
def within_budget():
name = None
#We applied a loop, so if no data is inputed (false) than the code will not continue until data is provided (true)
... |
def countingValleys(steps, path):
sealevel = valley = 0
for i in path:
if i == "U":
sealevel += 1
else:
sealevel -= 1
if i == "U" and sealevel == 0:
valley += 1
print(valley)
'''
Test case 1:
8
UDDDUDUU
expected output : 1
Test case 2:
12
D... |
a=int(input("enter a number"))
b=int(input("enter a number"))
c=int(input("enter a number"))
def max():
if a>b and a>c and c>a:
print(a,max)
if b>a and b>c and c>b:
print(b,max)
else:
print(c,max)
max()
|
def new_list():
list1 = [1, 342, 75, 23, 98,75,23,98,12,10,1]
i=0
new_list=[ ]
while i<len(list1):
j=i+1
index=0
while j<len(list1):
if list1[i]==list1[j]:
index=index+1
j=j+1
if list1[i] not in new_list and index>0:
new... |
#导入tkinter
import tkinter as tk
#定义全局变量,控制显示隐藏
on_hit = True
#定义按钮点击后执行的函数,必须定义在按钮的前面
def hit_me():
#函数内给全局变量赋值,需要使用global
global on_hit
''' 直接改变label的text值
if on_hit:
l['text'] = 'you hit me'
on_hit = False
else:
l['text'] = ''
on_hit = True
'''
# 将label的text设置为变量
if on_hit:
var.set('you hit me')
o... |
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))
if n1 >= n2 and n2 >= n3:
print(f'O maior número é: {n1}')
elif n2 >= n3:
print(f'O maior número é: {n2}')
else:
print(f'O maior número é: {n3}')
if n1 <= n2 and n2 <= n... |
cigarros = int(input('Digite a quantidade de cigarros por dia: '))
anosFumando = int(input('Digite a quantidade de anos fumando: '))
totalCigarros = anosFumando * 365 * cigarros
dias = totalCigarros / 1440
print(f'Fodeu você perdeu {dias:.1f} dias de vida')
|
import math
import random
from colorama import init, reinit, deinit
from colorama import Fore, Back, Style
class Pocket:
''' Class that imitates the spots in a roulette wheel'''
def __init__(self, number, number_type, color):
self.number = number
self.number_type = number_type
self.color = color
def __iter_... |
#greedy algorithm technique
#code repetiton, here function is not used
num = [5,7,3,9,1,9]
l = []
largest = None
for item in num:
if item >= largest:
largest = item
l.append(largest)
index_find = num.index(largest)
num.pop(index_find)
print num
#2
largest = None
for item in num:
if item >= la... |
import os
os.system('cls')
import time
def cls():
os.system('cls')
def menu():
while True:
try:
choice = int(input("1)Login 2)Register 3)Quit --> "))
return choice
except ValueError:
print("Please choose a whole number either 1, 2 or 3")
def ... |
print("em que ano você nasceu?")
nascimento=input()
nascimento=int(nascimento)
print("em 2025 você tera",2025-nascimento,"anos")
|
import random
import math
class player(object):
def __init__(self, name, age, gender):
self. name = name
self.age = age
self.gender = gender
def taunt(self, message):
print message
def burp(self):
print ("sorry guys, i need to get some tea")
kennedy = player("ke... |
#create a class called Car. In the __init__(), allow the user to specify the following attributes: price, speed, fuel, mileage.
#If the price is greater than 10,000, set the tac to be 15%. Otherwise, set the tax to be 12%.
class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = pr... |
import os
CARPETA = 'contactos/' #Carpeta de contactos
EXTENSION = '.txt' #Extension de los archivos
# Contactos
class Contacto:
def __init__(self, nombre, telefono, categoria):
self.nombre = nombre
self.telefono = telefono
self.categoria = categoria
def app():
#Revisa ... |
def ReverseComplement(Pattern):
rev= Reverse(Pattern)
revComp = Complement(rev)
return revComp
# Copy your Reverse() function here.
def Reverse(Pattern):
rev = ""
for i in range(len(Pattern)):
rev = rev + Pattern[len(Pattern) -i -1]
return rev
# Copy your Complement() function here.
de... |
def find_all(a_string, sub):
result = []
k = 0
while k < len(a_string):
k = a_string.find(sub, k)
if k == -1:
return result
else:
result.append(k)
k += 1 #change to k += len(sub) to not search overlapping results
return result
|
from sys import argv
from Bio.SubsMat import MatrixInfo as matlist
"""
CODE CHALLENGE: Solve the Middle Edge in Linear Space Problem (for protein strings).
Input: Two amino acid strings.
Output: A middle edge in the alignment graph in the form "(i, j) (k, l)", where (i, j) connects to (k, l).
To comput... |
"""
Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
with open("text.txt", "w") as f_obj:
while True:
temp_input = input("Введите строку")
if temp_input == "":
break
... |
num_01 = input("Enter a natural number: ")
for i in num_01:
if num_01.count(i) > 1:
print("There are same digits")
break
else:
print("There are not same numbers")
# num_02 = input()
#
# if len(num_02) == len(set(num_02)):
# print("There are not same digits")
# else:
# print("There are... |
s = "word"
try:
print(s[3])
1/2
int("2")
except ValueError:
print("error ValueError")
except ZeroDivisionError:
print("Undividable on zero")
except NameError:
print("Invalid name")
except Exception: # almost highest hierarchy
print("Error")
except LookupError: # hierarchy h... |
"""
From to
1 2 3 3 2 1
4 5 6 6 5 4
7 8 9 9 8 7
"""
import array
def swap(array_2d, i, j):
temp = array_2d[i]
array_2d[i] = array_2d[j]
array_2d[j] = temp
def mirrored_2d_array(array_2d):
array_2d = []
for array in array_2d:
for i in range(len(array_2d) // 2):
... |
x = y = [1, 2, 3]
x[2] = 100
print(x)
print(y)
arr = [[]] * 2
print(arr)
arr[0].append(5)
print(arr) |
"""Expression comprehension"""
list = [1, 3, 5, 8, 12]
my_expr = sum(i for i in list if i % 2 == 0) # only works for 1 TIME!!!
print(my_expr)
|
a = []
n = int(input("Please enter row quantity: "))
m = int(input("Please enter column quantity: "))
for i in range(n):
b = []
for j in range(m):
b.append(int(input("Please input element of matrix: ")))
a.append(b)
print(a)
|
def say_hello():
print("hello")
print("hello again")
print("hello and again")
say_hello()
def squared(x):
print(f"{x} squared is equal to {x**2}")
for i in range(1, 11):
squared(i)
|
dict = {"name": {"name_01": "Sasha", "name_02": "Dima"}}
print(dict["name"]["name_01"])
|
def sq_perimeter(x, y):
return x*y, 2*(x+y)
square, perimeter = sq_perimeter(2, 10)
print(square, perimeter)
|
import re
import functools
with open("input.txt", "r") as file:
data = file.read().strip()
def parse(data):
sections = data.split("\n\n")
#parse the rules first
fields = {}
for field in sections[0].split("\n"):
match = re.match("([\w\s]+): (\d+)-(\d+) or (\d+)-(\d+)", field).gr... |
from functools import cmp_to_key
def larg(num1, num2):
if str(num1)+str(num2) < str(num2)+str(num1):
return 1
elif str(num1)+str(num2) == str(num2)+str(num1):
return 0
else:
return -1
def largest(numbers):
x = sorted(numbers, key=cmp_to_key(larg))
x = [str(itm) ... |
class Grid():
def __init__(self):
self.cells = []
for i in range(35):
self.cells.append([])
for j in range(27):
self.cells[i].append([])
def remove(self, follower, x, y):
if x > 0 and x < len(self.cells) and y > 0 and y < len(self.cells[0]):
... |
# -*- coding: utf-8 -*-
"""
CS141
HW1
@author:
"""
import math
import statistics
import numpy as np
import random
"""Given two list of numbers that are already sorted,
return a single merged list in sorted order.
"""
sortedListA = [1, 2, 3, 4, 5]
sortedListB = [2, 4, 5, 6, 8, 9]
listofNums = [4, 5,... |
print ( 'This works for even numbers')
mini = input('enter a minimum number : ')
maxi = input('enter a maximum number : ')
mini = int(mini)
maxi = int(maxi)
mini+= 1
while mini <= maxi:
print (mini)
mini += 2
print ( '\nThis works for odd numbers')
mini = input('enter a minimum number : ')
maxi = input('en... |
sandwich_order = []
sandwich_order.append('tuna')
sandwich_order.append('beef')
sandwich_order.append('pastrami')
sandwich_order.append('chicken')
sandwich_order.append('pastrami')
sandwich_order.append('fish')
sandwich_order.append('cheese')
print(sandwich_order)
finished_sandwiches = []
while sandwich_order:
sandwic... |
def describe_city(city,country):
"""function to print a simple sentence"""
print (city.title() + " is in " + country.title()+ "." )
describe_city ('lagos','nigeria')
describe_city ('new york','nigeria')
describe_city ('frankfurt','nigeria')
|
numbers = [5,2,5,2,2]
for num in numbers:
num *= "x"
print(f"{num}")
numbers = [5,2,5,2,2]
for num in numbers:
print (f"{'x' * num}")
"""nested loop"""
numbers = [1,1,1,5]
for num in numbers:
output = ""
for nu in range(num):
output += 'x'
print(output)
|
number = list(range(2,20,2))
print (number)
for nu in range(2,20,2):
print (nu)
squares = []
for value in range(2,20,2):
square = value**2
squares.append(square)
print (squares)
squares = []
for value in range(2,20,2):
squares.append(value**2)
print(squares)
min(squares)
|
def make_shirt(size,text):
"""summarise the size of a shirt with a catchy text for advertisment"""
print("The shirt is " + size + " sized, with " + text.title() + " text.")
make_shirt('medium','consistency is key')
make_shirt(size='large',text='be the best')
|
names = ['adex','seun','nick','VIC','Bim','admin','nut']
name = ['vic','dayo','nick','tim','bim']
for i in name:
if i.title() in names or i.upper() in names or i.lower() in names:
print (i+' You will need to enter a new username.')
else:
print(i + ' is available.')
|
"""
**Quiz Maker** - Make an application which takes various questions form a file, picked randomly, and puts together a quiz for students.
Each quiz can be different and then reads a key to grade the quizzes
"""
import random
import sys
#Open file and get question
def getQuestion(random_question):
with open('questi... |
""" Iterador Concreto """
from Iterador import Iterador
class IteradorEquipoA(Iterador):
def __init__(self, jugadores):
super(IteradorEquipoA,self).__init__()
self.pos = 0
self.jugadores = jugadores
#Override
def primero(self):
self.pos = 0
jugador = self.jugadores[self.pos]
return jugad... |
#!usr/bin/env python3
#coding=utf-8
#游戏异常类
class GameException(Exception):
def __init__(self, _error_code, _message):
self.message = _message
self.error_code = _error_code
print(self)
def __str__(self):
return "GameException: " + self.message + "Code: " + self.error_code |
# Create node class
class Node:
count=0
def __init__(self,data):
self.data=data
self.next=None
self.previous=None
# increment by 1 when create object
Node.count+=1
# Create CircularDoublyLinkedList
class CircularDoublyLL:
# Initialize head and tail with None
def... |
def minheap(arr,n,parent_index):
smallest_index=parent_index
left_index=2*parent_index+1
right_index=2*parent_index+2
if left_index<n and arr[left_index]<arr[smallest_index]:
smallest_index=left_index
if right_index<n and arr[right_index]<arr[smallest_index]:
smallest_index=right_i... |
def bubble_sort(arr):
length=len(arr)
# If the length less or equal than 1
if length<=1:
return arr
else:
step=0
for l in range(length-1):
is_swapped=False
for c in range(length-1-l):
if arr[c]>arr[c+1]:
arr[c],arr[c+1... |
while True:
amountItems = int(input("Number of items: "))
if amountItems < 0:
print('Invalid number of items!')
else:
totalPrice = 0
for i in range(1, amountItems + 1):
while True:
priceItem = float(input("Price of item: "))
if priceItem < ... |
#!/usr/bin/python3
##### NEED TO DO:
##### clean up text
##### graphics
##### win condition
##### death handling
from playergame import *
from itemsgame_OO import *
from itemsgame import *
from gameparser import *
import random
from mapgame import rooms
from enemies import *
from enemies_OO import *
from questions... |
from room import Room
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, currentRoom, items=[]):
self.name = name
self.currentRoom = currentRoom
self.items = items
def __str__(self):
return f'Hey there, my... |
# -*- coding: utf-8 -*-
''' @author : majian'''
import os, re, sys
import time
''' This method is used by Event grade judge '''
class Event:
def __init__(self):
self.returns = ""
'''
Grade :
5: level 5 event
4: level 4 event
3: level 3 event
2: level 2 event
1:... |
def alphanumeric(s):
for i in range(len(s)):
if s[i].isalnum():
return True
break
return False
def alphabetical(s):
for i in range(len(s)):
if s[i].isalpha():
return True
break
return False
def digits(s):
for i in range... |
def computepay(h,r):
if h > 40.0 :
extra_hours = h - 40.0
extra_pay = extra_hours * (r * 1.5)
pay = (40.0 * r) + extra_pay
else :
pay = h * r
return pay
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
h = float(hrs)
r = float(rate)
total = computepay(h,r)
print(tota... |
import csv
import os
def _map():
""""Разбиваем csv файл на строки"""
with open('temp.csv', newline='') as File:
reader = csv.reader(File)
next(reader)
for row in reader:
yield row
def _reduce():
for i in (_map()):
try:
os.makedirs(i[3])
... |
from pygame import Vector2
from random import uniform
class Ball():
def __init__(self, x_pos, y_pos, radius, speed):
self.x_pos = x_pos
self.y_pos = y_pos
self.radius = radius
self.speed = speed
self.is_colliding = False
self.is_crashing = False
self.velocity = self.random_velocity()
def set_x_pos(sel... |
#package imports
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import KFold
from sklearn import linear_model
import numpy as np
#read the test and train sets
train_df= pd.read_feather('../input/kernel318ff03a29/nyc_taxi_data_raw.feather')
test_df = pd.read_feather('../input/kernel3... |
import argparse
import json
def parse_line(line):
"""Parses line for Hamiltonian term information.
Arguments:
line {string} -- String, delimited with the " | " symbol, with information
Returns:
dict -- nested dictionary in "terms" standard
"""
# OPS CONVERSION TABLE
# [I, X,... |
letters = ["a", "b", "c"]
matrix = [[0, 1], [2,3]]
# it pritns the 0 5 times
zeros = [0] * 5
print(zeros)
print('\n')
# we can join to lists and save it to another string
combined = zeros + letters
print(combined)
print('\n')
# myName = ['Vahid '] * 100
# print(myName)
numbers = list(range(20))
print(numbers)
pri... |
# how to sum the list values
# when we pass an * befor the argument the python will
# compile this as an tuple
def sum(*list):
total = 0
for number in list:
total += number
return total
print(sum(10,10,10,10,10))
def multiply(*list):
total = 1
for number in list:
total *= number
... |
letters = ['a','b', 'c', 'd', 'e', 'f']
# Finding the the index of an item
print(letters.index('e')) |
list1 = [2,3,8,4,9,5,6]
list2 = [5,6,10,17,11,2]
list3 = list1 + list2
print(list3) #不去重只进行两个列表的组合
print(set(list3)) #去重,类型为set需要转换成list
print(list(set(list3))) |
'''
Date: 2021-06-28 10:22:11
LastEditors: Liuliang
LastEditTime: 2021-06-28 10:29:58
Description:
'''
def sift(list,low,high):
i = low
j = 2 * i + 1
tmp = list[low]
while j <= high:
if j + 1 <= high and list[j] > list[j+1]:
j = j + 1
if tmp > list[j]:
list[i] =... |
#!/usr/bin/env python3
from datetime import datetime
import random
import re
import sys
class MineSweeperGame():
"""
Minesweeper Game
"""
def __init__(self, *args):
"""
initializes MineSweeper game solver
"""
self.init_vals_and_verify_game_inputs(args[0])
def tokeni... |
def get_info(settings_file=True):
"""
Retrieves all necessary information from either the user through prompts or from a previously saved settings
file.
:param settings_file: bool - assumes there is a file available unless the file is not found and then get_info is
called recursively with this p... |
# principal.py
#
# DESCRIPCION: Programa que determina la primalidad de un entero n>1 dado. \
# Para ello se puede hacer la verificacion a traves de alguno de los siguientes \
# 3 algoritmos: División por Tentativa, Aleatorizado basico y Solovay-Strassen.
#
# Autores:
# Br. Jose Barrera y Br. Alfredo Cruz.
#
# Ultima ... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
if not root:
return True
q =[]
q.append(root)
q.append(root)
while len(q)>0:
node1 = q.pop(... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTilt(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
def myhelp(root):
... |
'''
题目要求顺时针旋转矩阵90度,可以分解为两步。先对矩阵做转置,再做左右对称互换。
即 1 2 3 1 4 7 7 4 1
4 5 6 -> 2 5 8 -> 8 5 2
7 8 9 3 6 9 9 6 3
'''
def rotate(matxir):
l = len(matxir[0])
x=0
for i in range(l):
for j in range(x,l):
temp = matxir[i][j]
matxir[i][j] = matxir[j][i... |
def canConstruct(ransomNote, magazine):
r = sorted(ransomNote)
m = sorted(magazine)
if len(r) > len(m):
return False
for i in range(len(r)-1,-1,-1):
for j in range(len(m)):
if r[i] == m[j]:
r.pop(i)
m.pop(j)
break
if i+1... |
def findDisappearedNumbers1(nums):
res = [0] * len(nums)
for i in nums:
res[i - 1] = i
for i in range(len(res) - 1, -1, -1):
if res[i] != 0:
res.pop(i)
else:
res[i] = i+1
return res
def findDisappearedNumbers(nums):
for i in nums:
temp = abs(i... |
class Solution:
def addDigits(self, num: int) -> int:
while num >=10:
k = 0
for i in str(num):
k += int(i)
num = k
return num
class Solution:
def addDigits(self, num: int) -> int:
return (num-1)%9+1 if num !=0 else 0 |
# Draw a dragon curve fractal
# https://en.wikipedia.org/wiki/Dragon_curve
import pygame
MAXLEVEL = 15 # recursion max depth
# Define the shape of the curve
# Those divisors offset the new point from the current segment
# Both 1: standard dragon curve with new line segments built at right angles
# Values ... |
import re
pattern = re.compile(r'\d+')
# findall() is to scan the whole string and return all matched substrings in list
result = re.findall(pattern, "sdjia23023sdj231mdks02313kdm321")
if result:
print result
else:
print "fail to match" |
# implementation of card game - Memory
import simplegui
import random
tlx=0
tly=0
blx=0
bly=100
brx=50
bry=100
trx=50
trz=0
l=[]
val=[]
state=0
cards=[-1,-1]
deck1=range(8)
deck2=range(8)
turn=0
# helper function to initialize globals
def new_game():
global l,val,state,turn,cards
cards=[-1,-1]
state=0
... |
from unittest import TestCase
import datetime
import HW6_Refactored
today = datetime.date.today()
d1 = datetime.date(2000, 1, 1)
d2 = datetime.date(2016, 10, 3)
class TestDiff_between_dates(TestCase):
def test_dates_diff(self):
self.assertLess(d1, today, str(d1) + " Provide date before current d... |
import tkinter
window =tkinter.Tk()
window.geometry('350x70')
import tkinter
window = tkinter.Tk()
window.title("KK agrawal")
window.geometry('350x70')
label=tkinter.Label(window,text="Hello ! Kk Agrawal").pack()
bt = tkinter.Button(window,text="Enter")
bt.pack()
window.mainloop()
'''
from tkinter impor... |
def prime(a):
for i in range(2,a):
k=0
for j in range(2,i):
if(i%j==0):
k=1
if(k==0):
print(i,end=" ")
n=int(input("Enter any number to print between prime numbers"))
prime(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.