text stringlengths 37 1.41M |
|---|
"""
I made this application because I cannot use GIMP that well.
In fact it was the most iritating experience for me, trying to make tileset of 50 images.
One pixel mistake and you can do it again.
That is why I created this.
It creates a tileset.png out of all png files located in \tiles\ directory.
"""
from PIL impor... |
import sqlite3
#Cria as databases que serão manipuladas pela main.
conn = sqlite3.connect('nome_aluno.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS nome_aluno (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL
);
""")
conn = sqlite3.connect('resposta.db')
cursor = c... |
def fact(n): # recursive function to calculate the factorial of a given input
if n==1:
return 1
else:
j= n*fact(n-1)
return j
k=int(input("Enter the input")) # getting input from the user
n=fact(k)
print(n) |
def pivotIndexOptimized(nums):
if len(nums) <= 2:
return -1
left_sum, pivot, right_sum = 0, 0, sum(nums[1:])
if left_sum == right_sum:
return pivot
for i in range(len(nums) - 1):
left_sum += nums[pivot]
pivot += 1
right_sum -= nums[pivot]
if left_sum == ri... |
a=input("Enter the first binary string :")
b=input("Enter the second binary string : ")
a= int(a,2)
b= int(b,2)
c= bin(a+b)
c=c[2:]
print(c)
# k=max(len(a),len(b))
# l=min(len(a),len(b))
# addZero=k-l
# print(addZero)
# if len(a)>len(b):
# for z in range(addZero):
# b='0'+b
# else:
# for z in range(addZ... |
class Solution :
def searchInsert(self,nums,target):
i=0
if(nums[0]>target) :
return 0
elif(nums[-1]<target):
return len(nums)
else :
while(i<len(nums)):
if(nums[i]==target):
return i
elif(nums[i]... |
def findPattern(pattern,str):
str = str.split()
dict = {}
for k in range(len(pattern)):
if dict[pattern[k]]==str[k]:
print("ok")
elif dict[pattern[k]]!=str[k] and pattern[k] not in dict.keys():
dict[pattern[k]]=str[k]
else:
return False
return ... |
def sort(prices):
if not prices:
return 0
arr.sort()
profit = arr[-1] - arr[0]
return profit
arr=[]
for i in range(1,6):
arr.append(int(input("Enter the %d price : "%i)))
k=sort(arr)
print(k)
|
lst = list()
while (True):
inp = raw_input("Enter a number: ")
if inp == "done" : break
if inp == 'Done': break
inp = float(inp)
lst.append(inp)
#print "Debug:", lst
print max(lst)
print min (lst)
|
def primes_until_n(n):
noprimes = [j for i in range(2, int(n ** (1 / 2)) + 1)
for j in range(i * 2, n + 1, i)]
return [x for x in range(2, n + 1) if x not in noprimes]
def give_n_primes(n):
return [p for p in [a for a in range(1, (n ** 2 + 1)) if all([(a % b != 0) for b in range(2, ... |
def staircase(n):
for i in range(n): print(' '*(n-i-1)+'#'*(i+1))
'''
for i in range(1,n+1): print(' '*(n-i)+'#'*(i))
for i in range(1,n+1):
print(' '*(n-i)+'#'*i)
for i in range(1,n):
print(" "*(n - i - 1),"#"*i)
print("#"*n)
for i in range(n,0,-1):
... |
import json
myfile = json.load(open('TestDuplicateFile', 'r'))
uniq = set()
for p in myfile:
if p in uniq:
print "duplicate : " + p
del p
else:
uniq.add(p)
print uniq |
'''
--- Day 3: Spiral Memory ---
___,@
/ <
,_ / \ _,
? \`/______\`/
,_(_). |; (e e) ;|
\___ \ \/\ 7 /\/ _\8/_
\/\ \'=='/ | /| /|
\ \___)--(_______|//|//|
\___ () _____/|/_|/_|
/ () \ `----'
... |
'''
Spiral primes
Problem 58
Starting with 1 and spiralling anticlockwise in the following way,
a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
It is interesting to note tha... |
'''
Permuted multiples
It can be seen that the number, 125874, and its double,
251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x,
contain the same digits.
'''
def st2set(n):
'''stevke da v mnozico'''
assert n... |
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
# def je_deljivo_s_katerim_od(n, seznam):
# if seznam == []:
# return False
# else:
# return n % seznam[0] == 0 or je_deljivo_s_katerim_od(n, ... |
'''
Truncatable primes
The number 3797 has an interesting property. Being prime itself,
it is possible to continuously remove digits from left to right,
and remain prime at each stage: 3797, 797, 97, and 7. Similarly
we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes ... |
"""
singly-linked list
"""
class ListNode(object):
def __init__(self):
self.val = None
self.next_node = None
class LinkedList_handle:
def __init__(self):
self.cur_node = None
def add(self, data):
"""add a new node pointed to previous node"""
node = ListNode()
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 17 10:34:56 2017
@author: nielton
"""
def ler_numeros(n):
lista = []
for i in range(n):
numero = int(input("Digite um número!"))
lista.append(numero)
return lista
|
from tkinter import *
from TableTester import *
def show_result():
resulttext.delete(1.0, END)
resulttext.insert(INSERT, EpisodeFromShow(e1.get()))
window = Tk()
window.title("Random Episode Generator")
label = Label(window, text="Enter your show:")
label.grid(row=0, sticky=W)
e1 = Entry(window, width=22)
e1.... |
# Project Euler 15 - Lattice Paths
def latticePaths(rows, columns):
grid = list(list(1 for _ in xrange(columns+1)) for _ in xrange(rows+1))
for x in xrange(1, columns+1):
for y in xrange(1, rows+1):
grid[y][x] = grid[y-1][x] + grid[y][x-1]
return grid[len(grid)-1][len(grid[0])-1]
def main():
print latticePat... |
# 20 - Factorial Digit Sum
from math import factorial
def main():
print sum(int(d) for d in str(factorial(100)))
if __name__ == '__main__':
main()
|
while(True):
try:
texto = list(input())
i, b = False, False
for n in range(len(texto)):
if(texto[n] == '*' and not b):
texto[n] = "<b>"
b = True
pass
if(texto[n] == '*' and b):
texto[n] = "</b>"
... |
testes = int(input())
while (testes > 0):
numeros = input().split()
num1, num2 = numeros[0], numeros[1]
if(len(num1)>= len(num2)):
if(num1[len(num1)-len(num2):] == num2[:]):
print("encaixa")
pass
else:
print("nao encaixa")
else:
print("nao enca... |
testes = int(input())
while testes>0:
alfabeto = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'.split()
frase = input()
for i in frase:
for j in alfabeto:
if (i==j):
alfabeto.remove(j)
break
pass
pass
pass
if(... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import math as m
a= input ("Ingrese un numero : ")
b= m.sin(a)
c= m.cos(a)
print ("El seno es ")(b)
print ("El coseno es ")(c)
|
# Recursion - function calling itself
def f():
print("f")
def g():
print(g)
f()
# g() # RecursionError depth exceeded
print("END")
g() # error commented out
# Control recursion with depth
def controlled(depth):
print("recursion depth", depth)
if depth > 0:
controlled(depth ... |
'''
Searching problems (25pts)
Complete the following 3 searching problems using techniques
from class and from the notes and the textbook website.
Solutions should use code to find and print the answer.
'''
import re
def split_line(line):
# uses regular expressions to split line of text into word list
return... |
import numpy as np
from board import Board
import random
class State():
# Initializing state (0 wins and games by default)
def __init__(self, board, parent, children, play):
self.set(board, parent, children, play, 0, 0)
# board - game board
# parent - parent State object
# children - arr... |
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += ... |
pomo = 25
rest = 5
mult_pomo = [25,50,75,100,125,150,175]
ideal = int(input("how many minutes do you want to work for?"))
total = (ideal/pomo*rest)+ideal
goal = ideal/pomo+rest
#clock = x/pomo+rest
mult_goal = [4,8,12,16,20]
#intro
print("goal:", ideal, "minutes and", ideal/60, "hours")
print( "total required time:",... |
#!/usr/bin/python3
nums = { 21, 11, 42, 29, 22, 71, 18 }
print(nums)
print("Number of elements: {0}".format(len(nums)))
print("Minimum: {0}".format(min(nums)))
print("Maximum: {0}".format(max(nums)))
print("Sum: {0}".format(sum(nums)))
print("Sorted elements:")
print(sorted(nums)) |
# Difficult challenge no. 2
import time
def main():
pass
def timer():
print('Timer will start when you press enter.')
input('Press enter to continue: ')
t0 = time.time()
print('Timer has started.')
print('Timer will stop when you press enter.')
input('Press enter to continue:... |
# Challenge 29 Easy
# https://www.reddit.com/r/dailyprogrammer/comments/r8a70/3222012_challenge_29_easy/
def pal(test):
f = list(str(test))
b = f[::-1]
if f == b:
print('{} is a palindrome!'.format(test))
else:
print('{} is not a palindrome.'.format(test))
|
# Challenge 26 Intermediate
# Harder than expected. Sorta works
import csv
# Entry must be a list format
# Sheet is CSV you want to add to
# Entry is data you want to add to the CSV
def writedata(sheet, entry):
sheetdata = []
# reading the CSV and storing the info
with open(sheet, 'r') as cs... |
import random, string
def main():
pass
def create_pw():
qty = int(input('How many passwords would you like to generate? '))
print('Algorithm will generate {} passwords.'.format(qty))
length = int(input('How long should the passwords be? '))
print('The passwords will be {} letters long.'.f... |
# DailyProgrammer Challenge 8 Easy
# write a program that will print the song "99 bottles of beer on the wall."
def ninetynine():
for n in range(99,2,-1):
print('{} bottles of beer on the wall, {} bottles of beer. Take one down, pass it around, {} bottles of beer on the wall.'.format(n, n, n-1))
... |
# 1. дефиниция на класа
class Point:
# Конструктор на класа
def __init__(self):
print('object constructor')
# Данни на класа
self.x = 10
self.y = 20
# Методи на класа
def draw(self):
print(f'draw point at:({self.x}, {self.y})')
if __name__ == '__main__':
... |
# 1. дефиниция на класа
class Point:
# данни на класа (статична променлива)
label = 'A'
# Конструктор на класа
def __init__(self, x = 0, y = 0, *args, **kwargs):
print('object constructor')
# Данни на обекта
self._x = x
self._y = y
Point.label = 'M'
# Мето... |
# глобална променлива
# def first_element(el):
# return el[1]
if __name__ == '__main__':
sq = lambda a: a ** 2
pw = lambda a: a ** 2 if a % 2 else a ** 3
# 1.
# print(f'4 ^ 2 = {sq(4)}')
# print(f'pw(3) = {pw(3)}')
# print(f'pw(4) = {pw(4)}')
items = [('A', 5, 7), ('D', 2, 6), ('B'... |
from datetime import datetime
import pandas as pd
def getdatenow():
return datetime.today()
def stringtodatetime(str="20210101"):
# from datetime import datetime
# datetime_str = '09/19/18 13:55:26'
datetime_object = datetime.strptime(str, '%Y%m%d')
# print(type(datetime_object))
return dat... |
mylist = ["a","b","c","d","a","a"]
mylist = list(dict.fromkeys(mylist))
print(mylist)
#copy list
thislist = ["Gayu","Digu","divya","Yash"]
copylist = thislist.copy()
print(copylist) |
from array import *
array_num = array('i',[7,8,5,4,8,6,2,8,9])
print('Original Array :' +str(array_num))
print('Remove the first occurance: ')
array_num.remove(8)
print('New Array :' +str(array_num)) |
#def small_num(items):
# smallest_number = 0
#print("smallest number is :", min([5,3,2]))
def smallest_num(items):
multi_numbers = items[0]
for x in items:
if x < multi_numbers:
multi_numbers = x
return multi_numbers
print(smallest_num([5,5,2,-9])) |
from logics.classes.propositional import Formula
class PredicateFormula(Formula):
"""Class for representing predicate formulae.
Extends the propositional class ``Formula``, but has some differences:
* Atomics are now of the form ``['R', 'a', 'x']``
* When the terms are applied function symbols, they... |
import numpy as np
class Vector:
"""Vector represents translation and stores 3 values
Attributes
----------
x
The x value
y
The y value
z
The z value
"""
def __init__(self, x, y, z):
"""
Parameters
----------
x
The x... |
import sys, getopt, io
def my_argument_function(argv):
"""Get the CLI argument into a python dictionary
The dictionary that is used in My_Logger_Class is called argu
and commes with already predefined arguments such as freq=5.
The Try usese the getopt to get the opt/arguments from the user... |
class Person:
def __init__(self,name,age,enrollno,branch):
self.name=name
self.age=age
self.enrollno=enrollno
self.branch=branch
p1 = Person("Riddham" , "21" , "0832cs15128","cse")
print("Name is "+p1.name)
print("Age is "+p1.age)
print("Enrollno is "+p1.enrollno)
print("Br... |
"""
Linear Regression
"""
import random
import numpy as np
import matplotlib.pyplot as plt
# this function generates random data
#sigma -> varience
#n -> total number of instances
#m -> number of columns
def genrate_data(sigma, n, m):
# e is unexplained error, it is normally distributed with mean = 0 and varience = ... |
#tuples
tuple1 = ("disk", 10, 1.5)
print(tuple1)
#tuple index
print(tuple1[0])
print(tuple1[1])
print(tuple1[2])
#tuple negative index
print(tuple1[-3])
print(tuple1[-2])
print(tuple1[-1])
#tuple line
print(tuple1[1:3])
#tuple sixe
print(len(tuple1))
#tuple sort
tuple2 = (1, 3, 5, 8, 2)
print(sorted(tuple2))
# ... |
"""
Ejercicio 1. Programa que Evalua la Función:
y(x) = Σ [mi * e^(γ(x - xi)^2)] de i = 1 -> k
Donde:
x, xi ∈ a los ℝ^n
mi ∈ ℝ
r ∈ ℝ > 0
Creado por: José Fragoso, 22/03/2019.
TODO: - Revisar el cambio que se hizo en la creación de arreglos.
- Generar una mejor impresión en la terminal.
"""
import n... |
#Let’s say I give you a list saved in a variable:
#a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
#Write one line of Python that takes this list a and makes a new list that has only the even
#elements of this list in it.
a = [1,4,9,16,25,36,49,64,81,100] # example list
a = [a for a in a if a % 2 == 0] # list comprehen... |
class Employee():
def __init__(self, first, last, pay, car, shirt):
self.first = first
self.last = last
self.pay = pay
self.car = car
self.shirt = shirt
self.email = f"{first}.{last}@yahoooooo.com"
def description(self):
print (f"{self.first} {self.last} makes ${self.pay} dollars a year and drive a {s... |
"""
Ask the user for a number. Depending on whether the number is even or odd, print
out an appropriate message to the user.
Hint: how does an even / odd number react differently when divided by 2?
"""
num = int(input("Please enter a number:"))
if num % 2 == 0: #modulus op will see if there are any dividedends to... |
# 给定两个数组,编写一个函数来计算它们的交集。
# 示例
# 1:
# 输入:nums1 = [1, 2, 2, 1], nums2 = [2, 2]
# 输出:[2]
# 示例
# 2:
# 输入:nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
# 输出:[9, 4]
# 说明:
#
# 输出结果中的每个元素一定是唯一的。
# 我们可以不考虑输出结果的顺序。
# class Solution(object):
# def intersection(self, nums1, nums2):
# """
# :type nums1: List[int]
... |
# 206. 反转链表
# 反转一个单链表
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->NULL
# 进阶:
# 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
# Definition for singly-linked list.
# 没懂啊啊哈哈哈
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
class Solution:
... |
"""Strategy randomly picks a slot machine to run."""
from random import randint
from random import random
from bandits import Environment
def random_strategy_calculator(number_of_machines: int, number_of_trials: int,
means: list, gaussian=False, ):
"""
Calculate value gained u... |
import csv
def get_questions():
get_questions = []
with open('data/questions.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
skip = False
for row in csv_reader:
if (skip):
get_questions.append(row)
else:
skip =... |
def create_question(title, body, body_format, pseudocode, course):
with open("seeds.rb", "a") as myfile:
question_body = """
question""" + title + """text = %q{""" + remove_new_line(body) + """}
"""
pseudocode_body = """
question""" + title + """pseudocode = %q{""" + pseudocode + """}
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 8 21:15:58 2018
@author: Darshan
"""
#!/usr/bin/env python2
import sys
from datetime import datetime
# Count # of pieces in given row
def count_on_row(board, row):
return sum( board[row] )
# Count # of pieces in given column
def count_on_col(board,... |
import os, pickle, sys, struct
# ----- FUNCTIONS ----- #
# --- Read File Function --- #
def hpwc(filename):
"""
Reads a binary file and prints the content to the stout
in utf-8 coding
"""
with open(filename, 'rb') as inFile:
str_ser = pickle.load(inFile)
string = ... |
import sys
import os
import time
# Python 3 program to find Majority
# element in an array
# Guardamos los argumentos con los que llamamos al programa en arg
arg = sys.argv
#Comprobamos si tenemos que mostrar el resultado
if "-do" in arg:
out=1
else:
out=0
# Function to find Majority
# element in an array... |
# Q1
a = int(input("Enter first number:"))
b = int(input("Enter second number:"))
print("Sum of the two given numbers is:%s"%(a+b))
# Q2
name = input("Please enter your name:")
TP = input("Please enter your TP number:")
marks = input("Please enter your marks:")
grade = input("Please enter your grade:")
CGPA = input("P... |
def HR():
again = "Yes" or "yes"
while((again == "Yes")or(again == "yes")):
print("Menu:")
print("1.Create a Lectruer's profile")
print("2.Create a Academic Leader's profile")
print("3.Check the lecturer's profile")
print("4.Check the employee leave status")
print... |
import time
def upload_holiday():
""" HR's Function that used for Uploading Public and University Holidays,
and store the holidays in dictionary of list data type afterward write it to plain text file.
Note: Dictionary Key is holidays name and the value is a list consisting of only start date and end date... |
"""Lecturer
1. Can apply for leave.
2. Can check the status of the leave application.
3. Can view all public and University Holidays, also University’s Leave Policies."""
import time
while True:
lec_login_id = input("Enter login id:") #create user input
lec_password = input("Enter password:")
if lec_login... |
def fibo(n):
a=0
b=1
d=0
while d<n:
c=a+b
a+=1
b+=1
print(c)
#test
x=int(input("enter no.:"))
fibo(x)
|
"""
deferred
Deferred action wrapping
Hans Buehler 2022
"""
from .util import fmt_list
from .logger import Logger
_log = Logger(__file__)
class Deferred(object):
"""
Defer an action such as function calls, item access, and attribute access to a later stage.
This is used in dynaplot:
fig = figure()... |
#!/usr/bin/env python
#wypelnienie list:
lista1 = [x**2 for x in range(1,100000)]
lista2 = [x**3 for x in range(1,50000)]
#print(lista1, lista2)
#print("dlugosc listy pierwszej to {}, a drugiej to {}".format(len(lista1), len(lista2)))
#zadeklarowanie list
wspolna = []
pierwiastki = []
#wypisywanie wspolnych ele... |
import numpy as np
import random
import math
import matplotlib.pyplot as plot
def SampleExp(rate):
u = random.random()
return - np.log(u) / rate
def PoissonPmf(rate, t, limit):
result = []
for k in range(limit):
result.append(np.exp(-rate * t) * ((rate * t) ** k) / math.factorial(k))
ret... |
countries = {"Austria": "Vienna", "Croatia": "Zagreb", "Spain": "Madrid", "Slovenia": "Ljubljana"}
correct = 0
incorrect = 0
for k in countries: # k stands for "key" in the dictionary, while the other thing is its "value" (v)
capital = countries[k]
print("\nWhat is the capital of:", k) ... |
import requests
from bs4 import BeautifulSoup
#connecting to the website and creating the beautiful soup object
source = requests.get("https://www.dictionary.com/e/word-of-the-day/", timeout=5)
#testing to see if connection can be established
if source.status_code !=200:
print("Couldn't connect to the website")
exi... |
"""This program is designed to take a csv formated spreadsheet of soccer
players and distribute them evenly among three teams, ensuring that each
team has the same number of experienced players. It then, based on a
template file, generates form letters to the parents/guardians of each
player, informing them of the tea... |
from linkedlist.linkedlist import Node, LinkedList
def test_zipLists():
num=LinkedList()
num.insert('1')
num.insert_after('1','3')
even_num=LinkedList()
even_num.insert('2')
even_num.insert_after('2','4')
num.zipLists(even_num)
assert str(num) =="{1} ->{2} ->{3} ->{4} ->Null"
|
from typing import Counter
from stack_queue.stack_queue import Stack
def validate_brackets(string):
ls=[]
open=Stack()
for i in string:
if i in ["(", "{", "[" ,")", "}", "]"]:
ls.append(i)
print(ls)
for i in ls:
if i in ["(", "{", "["]:
open.push(i)
else:
if open.is_empty():
... |
nombres=["juan", "ana", "marcos", "carlos", "luis"]
cantidad=0
x=0
while x<len(nombres):
if len(nombres[x])>=5:
cantidad=cantidad+1
x=x+1
print("Todos los nombres son")
print(nombres)
print("Cantidad de nombres con 5 o mas caracteres")
print(cantidad)
|
import random #importa un conjunto de datos aleatorios
#=======================LISTA1============================================================
lisX=[] #definimos la lista
#=========INGRESO DE VALORES==============================================================
for x in range(10): #usamos el ... |
import sqlite3
from tkinter import *
from tkinter import messagebox
# PROGRAMADOR: JUAN PABLO MEZA GAZABÓN
# -----------------------------------------FUNCIONES------------------------------------------
def limpiarCampos():
miId.set("")
miNombre.set("")
miApellido.set("")
miEmail.set("")
miTelefono... |
# Ejercicio Herencia POO
# Archivo 1
class vehiculo:
def __init__(self):
self.nombre = input('Digite nombre de vehículo: ')
self.marca = input('Digite la marca del vehículo: ')
self.velocidad = int(input('Digite la velocidad del vehículo: '))
self.color = input('Digite el color del ... |
#============Definir las listas============
listAlum=[] #lista de alumnos
listPes=[] #lista de pesos
listAlt=[] #lista de alturas
listGen=[] #lista de generos
#==========Ingreso de valores=============
for x in range(3): #usamos el ciclo for para repertir las instrucciones siguientes 5 veces
nom=input("Ing... |
import multiprocessing
import time
#시작시간
start_time = time.time()
#멀티쓰레드 사용 하는 경우 (20만 카운트)
#Pool 사용해서 함수 실행을 병렬
def count(name):
for i in range(1,50001):
print(name," : ",i)
num_list = ['p1', 'p2', 'p3', 'p4']
if __name__ == '__main__':
#멀티 쓰레딩 Pool 사용
pool = multiprocessing.Poo... |
#Generator 예제2
#list comprehension 사용 리스트 생성
my_nums3 = [x for x in [1, 2, 3, 4, 5]]
#타입 확인
print (type(my_nums3))
#for문 사용 출력
for i in my_nums3:
print (i)
#List comprehension 사용 제네레이터 생성
my_nums4 = (x for x in [1, 2, 3, 4, 5])
#my_nums4 = [x for x in [1, 2, 3, 4, 5]] #리스트 생성
#타입 확인
print (t... |
def BMI(h, w):
bmi = w/((h/100)**2)
return bmi
bmi = BMI(180, 75)
print("%.2f" % bmi)
bmi = BMI(150, 30)
print(bmi)
bmi = BMI(160, 50)
print("%.3f" % bmi)
|
# num = (input('Enter a list of numbers: ')).split(' ')
#
# list_num = list(num)
# print(list_num)
a = (input('Enter a list of numbers: ')).split(' ')
list_a = list(a)
even = 0
odd = 0
for i in range(0, len(list_a)):
if i % 2 == 0:
even += 1
else:
odd += 1
print("Even: %d, odd: %d" % (even,... |
nombre = input("¿como te llamas?")
edad = int(input("que edad tiene?"))
print("Hola", nombre)
print("edad", edad) |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 18:38:53 2019
@author: jakej
"""
repeat = 6
while repeat == 6:
string = input("Please enter a word or phrase: ")
string = string.replace(" ","")
string = string.lower()
string = string.replace('?','')
string = string.replace('!','')
string = str... |
def calc(expr):
array = expr.split()
if len(array) == 0:
return 0
index = 0
while index < len(array):
if array[index] in "+-*/":
num1 = float(array.pop(index-2))
num2 = float(array.pop(index-2))
index -= 2
result = 0
if array[i... |
class Lift(object):
direction = 0
capacity = 0
people = []
floor = 0
floorsToVisit = []
listOfVisitedFloors = []
@classmethod
def __init__(cls, capacity):
cls.direction = -1 # "1" for up and "-1" for down. it is assigned -1 at the beginning because we treat as if Lift just arriv... |
class Pong:
def __init__(self, max_score):
self.max_score = max_score
self.scores = [0, 0]
self.paddle_length = 7
self.current_player = 0 # 0 and 1 for 1st and 2nd player respectively
def play(self, ball_pos, player_pos):
print self.scores
solution = ""
i... |
#Various Data Types:
#int - integer data type, only whole nos with no decimal
#float - a number with decimals
#str - string or combining all character like abc, blah
a = 2 #integer variable
b = 2.5 #float variable
c = 'two' #string variable
print (a, type(a))
print (b, type (b))
print (c, type(c))
#Type... |
guests_1 = [ "Bethaney Bain", "Kacey Johns", "Manpreet Saunders" ]
guests_2 = [ "Elwood Curtis", "Diya Griffin", "Kacey Johns" ]
guests_3 = [ "Tobey Weiss", "Kadie Barnes", "Diya Griffin" ]
guests_total = guests_1 +guests_2 + guests_3
for x in sorted(set(guests_total)):
print(x) |
"""
This file contains some
useful binary_search questions
"""
def find_the_first_equal(sorted_list, search_val):
"""
find the fist equal value
:param sorted_list:
:param search_val:
:return:
"""
left = 0
right = len(sorted_list) - 1
while left <= right:
mid = left + ((righ... |
# Question 20
# Define a class with a generator which can iterate the numbers,which are divisible by 7, between a given range 0 and n.
# Hints:
# Consider use yield
# https://docs.python.org/3/reference/expressions.html?highlight=yield
#Solution:
from audioop import reverse
def putNumbers(n):
i = 0
while i <... |
# importing tkinter
from tkinter import *
root = Tk()
root.title("Tkinter calculator") # adding title
# getting input from user
num_input= Entry(root,width=45, borderwidth= 2)
num_input.grid(row =0 , column =0, columnspan=4,pady=10,ipady=8)
global input_operator
ip_op = '+'
global first_number
f_num=0
... |
import tkinter as tk
import traceback
from tkinter import *
from tkinter import messagebox
from datetime import date
from Budget import Budget
# TODO: create GUI for budgets after creation
# TODO: functionality for entering paycheck
# TODO: delete budget
class GUI(tk.Frame):
def __init__(self, master=None):
... |
#!/bin/python3
def displayShopItems():
print("""
1. Cool Sword (100g)
2. Cool Spear (150g)
3. Cool Shield (210g)
4. Cool School (1000g)
5. Cool Armour (200g)
6. Cool Glock 19 (500g)
7. Cool Roger (1g)
""")
def buyItem(number):
global totalMoney
number = int(number)
if number == 1 and totalMoney >= 100:
... |
from tkinter import *
from dice import DiceSet
from score_pad import ScorePads
def read_int(prompt):
while True:
print("%s: " % prompt, end='')
try:
value = int(input())
except:
pass
else:
if value >= 0:
return value
... |
class my_defaultdict:
def __init__(self, **kwargs):
self.elements = dict(kwargs)
def __repr__(self):
return str(self.elements)
def __getitem__(self, key):
return self.elements[key]
def __setitem__(self, key, elem):
self.elements[key] = elem
if __name__ == '__main__':
test = my_defaultdict(a = 1, b = 2... |
import math
def main():
print("This program approximates pi by summing the terms of a series.")
print()
n = int(input("How many terms should be used? "))
total = 0.0
sgn = 1.0
for denom in range(1, 2*n, 2):
total = total + sgn * 4.0/denom
sgn = -sgn
print("Approximation t... |
def main():
print("Fill in the words to play MadLibs!")
noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adverb = input("Enter a adverb: ")
place = input("Enter a place: ")
print("The", noun, "needed to", verb, adverb, "into the", place)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.