text stringlengths 37 1.41M |
|---|
magicians=['alice','david','carolina']
for magician in magicians:
print(magician.title()+", that was a great trick!")
print("I can't wait to see your next trick,"+magician.title()+".\n")
"""
The newline("\n") in the second print statement inserts a blank line
after each pass through the loop.
"... |
def find_the_duplicate(nums):
"""Find duplicate number in nums.
Given a list of nums with, at most, one duplicate, return the duplicate.
If there is no duplicate, return None
>>> find_the_duplicate([1, 2, 1, 4, 3, 12])
1
>>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9])
9
... |
"""
Write a Python class to find validity of a string of parentheses, '(',')', '{', '}', '[' and '].
These brackets must be close in the correct order,
for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid
"""
class ValidatedParentheses:
def orderCheck(self, input_string):
open_t... |
"""
Write an if statement to determine whether a variable holding a year is a leap year.
"""
def leapYearCheck(input_year):
if (input_year % 400 == 0) or ((input_year % 4 == 0) and (input_year % 100 != 0)):
print("%d is a Leap Year" % input_year)
else:
print("%d is Not the Leap Year" % input_y... |
import turtle
clr_fondo = input("ingrese un color para el fondo ") # pregunta que color queremos para el fondo
wn = turtle.Screen() #asigna una variable para la ventana
wn.bgcolor(clr_fondo) #cambiar el color del fondo de la ventana
tess = turtle.Turtle() # invoca la tortuga por defecto es una... |
import turtle
def seq3np1(n):
""" Print the 3n+1 sequence from n, terminating when it reaches 1."""
count = 0
# print(n) # imprime n el número al que queremos evaluar
while n != 1:
if n % 2 == 0: # n es par (even)
n = n // 2
else: # n is impar (odd)... |
def suma (a):
if a == 0:
return 0
else:
return(a+suma(a-1))
print(suma(3)) |
#!/usr/bin/env python3
# Created by Ryan Chung Kam Chung
# Created in December 2020
# Program saying if an integer is positive or negative
def main():
# This function sees if the user inputed the magic number
print("Input a number and I'll tell you if it is "
"zero, negative or positive")
# I... |
#! python
import os
import sys
#### Read the file size
def fileSize ( file ,total_size):
# sanketh: minor: do we need os.path.abspath()?
if (os.path.exists(os.path.abspath(file))):
# sanketh: minor: do we need str() operators here?
# sanketh: minor: also useful to look ... |
import itertools
from typing import List
import heapq
from collections.abc import Callable
import editdistance
def levenshtein(s1: str):
def r(s2: str):
# calculate levenshtein distance between s1 and s2
dist = [[0 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)]
dist[0] = list(ra... |
from typing import List
def to_binary(s: str):
return int(s.replace('F', '0').replace('L', '0').replace('B', '1').replace('R', '1'), 2)
def run(inp: List[str]):
passes = set([to_binary(p) for p in inp])
print(max(passes))
for p in range(8, 2**10 - 8):
if p not in passes and (p+1) in passes and... |
from statistics import median
from typing import List
pairs = {
'[': ']',
'(': ')',
'{': '}',
'<': '>'
}
illegal_scores = {
')': 3,
']': 57,
'}': 1197,
'>': 25137,
}
completion_scores = {
')': 1,
']': 2,
'}': 3,
'>': 4,
}
def illegal(s):
expecteds = []
for c i... |
secret_word = 'rabbit'
guess = ''
guess_count = 0
while guess != secret_word:
if guess_count < 3:
guess = input('What is your guess?:')
if guess==secret_word:
print('You win!!!')
break
else:
print('Out of Guessess!\nGame Over!')
break
guess_count += 1... |
SECURE = (('s', '$'),('and', '&'), ('a', '@'), ('o', '0'), ('i', '1'))
def securePass(password):
for a,b in SECURE:
password = password.replace(a,b)
return password
if __name__ == '__main__':
passwd = input("Enter Your Password> ")
password = securePass(passwd)
print(f"Your Secure Pas... |
#!/usr/bin/python
"""
practicepython.org Task_9
"""
import random
MAXNO = 20
rannum = random.randint(1, MAXNO)
name = input('Enter Your Name: ')
#print(name)
print('\nHello '+ name +', This is a Game to Guess the Number.\n')
print('\nYou have 5 tries to guess the number\n')
n = 0
while True:
number = input... |
import sqlite3
import csv
import json
from tabulate import tabulate
from decimal import Decimal
# proj3_choc.py
# You can change anything in this file you want as long as you pass the tests
# and meet the project requirements! You will need to implement several new
# functions.
# Part 1: Read data from CSV and JSON i... |
class Vertex(object):
def __init__(self, key):
self.id = key
self.connectedTo = {}
def addNeighbor(self, nbr, weight=0):
self.connectedTo[nbr] = weight
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,nbr):
return self.connectedTo[nbr]
de... |
""" PROBLEM
Reverse all the words in a sentence
Implement a function for reversing the words in a string s.
"""
""" SOLUTION
Reverse the entire string. Then reverse individual words based on whitespaces.
Make sure to handle the last word.
"""
def reverse_words(s):
n = len(s)
if n == 0:
return ''.join(s)
... |
""" The 0-1 Knapsack problem
An item is in the form of a tuple (weight, value).
"""
""" SOLUTION
Create 2 cases of selecting and not selecting the current item. The case that gives the higher
value is selected.
"""
def knapsack_01(items,max_weight):
dp = [[0]*(max_weight+1) for _ in range(len(items))]
for i ... |
""" PROBLEM
Find the min and max simultaneously
"""
""" SOLUTION
Compare every pair with a step size of 2. Compute the local min and local max
for each pair and update the global min and global max.
"""
def find_min_max(A):
def min_max(a,b):
if a < b:
return a, b
else:
return b, a
if len(A) == 1:
... |
# Test if a binary tree supports BST property
from TreeNode import Node
def is_bst(root, low=float('-inf'), high=float('inf')):
if not root:
return True
if high <= root.val <= low:
return False
return is_bst(root.left, low, root.val) and is_bst(root.right, root.val, high)
root = Node(19)
root.left = Node(7... |
# Test if a binary tree is symmetric
# Write a program that checks whether a binary tree is symmetric
from TreeNode import Node
def is_symmetric(root):
def check_subtree(root1, root2):
if not root1 and not root2:
return True
if not root1 and root2:
return False
if root1 and not root2:
return False
... |
""" PROBLEM
Multiply two arbitrary precision integers
WAP that takes two arrays representing integers, and returns their representing an integer.
"""
""" SOLUTION
"""
def multiply(num1, num2):
if (num1[0] < 0) or (num2[0] < 0):
sign = -1
else:
sign = 1
num1[0], num2[0] = abs(num1[0]), abs(num2[0])
res ... |
"""PROBLEM
Identify all positions that can be attacked by rooks placed on a mxn chessboard. Rook positions are 0,
and rest of the positions are 1.
"""
"""SOLUTION
In-place solution
Find if the first row and column have rooks. If there are then all the positions in the first row and
column can be attacked. In the ohte... |
'''
https://programmers.co.kr/learn/courses/30/lessons/43164
여행경로 DFS/BFS
'''
def solution(tickets):
route = dict()
tickets.sort(reverse=True)
for start, end in tickets:
route[start] = route.get(start, []) + [end]
stack = ["ICN"]
answer = []
while stack:
top = stack[-1]
... |
def solution(str):
# sorted() : list로 반환한다
# sorted(string) -> 정렬후 list로 반환
list = sorted(str, reverse=True)
# ''.join(list) = list를 문자열로 변환
answer = ''.join(list)
return answer |
class Node:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeKthToLast(self, n):
if n < 0:
return
counter = 0
node = self
while node is not None:
counter += 1
node = node.next
if n > count... |
def StringRotation(strInput1, strInput2):
print(3/2)
if len(strInput1) != len(strInput2):
return False
for i in range(len(strInput1)):
temp = strInput1[i:] + strInput1[:i]
if temp == strInput2:
return True
return False
print(StringRotation("waterbottle", "erbottlew... |
import random
count=0
while (count<=100):
player1=input("press r to roll a dice: ")
if (player1=='r'):
r=random.randint(1,6)
count=count+r
print("the present value",count)
print("the dice value",r)
player2=input("press s to roll a dice: ")
if (player2=='s'):
s=random.rand... |
import copy
WIDTH = 4
HEIGHT = 4
WIN_NUMBER = 4
WIN, LOSE, TIE, UNDECIDED, DRAW = 'WIN', 'LOSE', 'TIE', 'UNDECIDED', 'DRAW'
PLAYER_1 = 'X'
PLAYER_2 = 'O'
EMPTY = '-'
""" Game state is saved as an array, in COLUMN-major order. E.g. in a 2x3 board:
1 2
3 4
5 6
we would store this as [1, 3, 5, 2, 4... |
print("Please Enter Your Name :")
Name=input()
print("Please Enetr Your Age")
Age=int(input())
print("Name = ",Name,"Age = ",Age)
print("Thank U")
|
# dependencies
import numpy as np
import skimage.io
def contrast(input_img, intensity=5, display=False, output_img=''):
'''
Adjust the contrast of an image, given the intensity specificication.
Works by making dark pixels much darker, and lighter pixels only slightly darker.
Input
=======... |
from open_basics import *
# here we'll run all our functions
open_read_file('order.txt')
print('////')
open_read_file_using_with('order.txt')
print('////')
item_list = ['paella', 'burgers', 'pizza']
for item in item_list:
write_to_file('order.txt', item)
|
"""
Author: Ruaa Abdulmajeed 101074335
This program will take an image and turn it into a bitmap that can be used for
an OLED screen.
"""
# from Cimpl import * # Carleton image editing library, uses PIL library
from tkinter import *
import tkinter.filedialog
from PIL import Image
import PIL.ImageTk
... |
#register
# -First_name, last_name, username, password, email
# - generate user id
# generate user account
#login
# - accountNumber and password
# user input validation
#Error Handling
#bank operations
#Initializing the system
import random
import Validation
import database
from getpass import getpass
# database =... |
'''
Created on 20 Jul 2020
@author: Alicia
'''
# def greet(person):
# print("Hello", person)
# print("How are you?")
'''
Study Unit 1 Activity 13 Page 72
'''
def main():
print("Print i in range(5)")
for i in range(5):
print(i * i)
print("\nPrint d")
for d in [3, 1, 4, 1, 5]:
... |
#-*- coding: utf-8 -*-
import AndOrNot
import SimpleOperationsMenu
import long_num_add_sub
import string_menu
def main():
exit = False
while not exit:
print 'Главное меню Калькулятора:'
print '1. Сделать что-то с числами.'
print '2. Сделать что-то со строками.'
print '3. Сделат... |
#!/usr/bin/python
#coding=utf-8
#python的语句块,使用缩进来标识,但是推荐不要用tab,而使用空格
if (1>0):print '1>0'
if(2>1):
#如果删除这个缩进,则程序不能执行
print '2>1'
if(3>2):
#实际上,只要有缩进就行,不管缩进是几个
print '3>2'
if(4>5):
print 'impossible'
elif(4>6):
print 'impossible neither'
elif(4>7):
#如果是空的代码块,必须使用pass标明什么都不做
pass
else:
print 'ne... |
class ColorSetting(object):
""" Class to hold the color setting """
color_name = ""
max_limit = 100
min_limit = 0
def __init__(self, color_name):
self.color_name = color_name
self.max_limit = 100
self.min_limit = 0
return
def set_max_limit(self, max_value):
... |
class ProgrammingLanguage:
def __init__(self, name, typing, reflection, year):
self.name = name
self.typing = typing
self.reflection = reflection
self.year = year
def is_dynamic(self):
if self.typing == "Dynamic":
return True
else:
return ... |
filename = str(input("Enter a filename: "))
try:
my_file = open(filename, "r") #problematic code
print(my_file.readlines())
x = 9 + "a"
my_file.close()
except FileNotFoundError:
print("File not found.")
except TypeError:
print("Type mismatch.")
#except: #generic except
# print("Generic excep... |
"""
Write a function that takes an integer and prints the numbers from that down to 0.
"""
def print_down(x):
for i in range(x, -1, -1):
print(i)
print_down(10)
def print_down_while(x):
while x >= 0:
print(x)
x -= 1
print_down_while(10)
def print_down_recursion(x):
print_down_... |
"""
Write a program that asks the user for their age and then prints whether it is odd or even.
The program should not crash if the user enters a non-number
The program should not allow an invalid age number (reject <0, >120)
Re-prompt until a valid number is entered
"""
# userAge = int(input("Enter your age:\n"))
# w... |
#file writing
"""
string1 = "a, b, c, d"
output_file = open("data.txt", "w")
output_file.write(string1)
output_file.close()
"""
#file reading
input_file = open("data.txt", "r")
data = input_file.readline()
for each in data:
print(each)
input_file.close()
|
from week1_demo import *
username = input("May I have your name:")
greet_someone(username)
first_num = 10.1 #this is a float
msg = "Hello 123"
msg1 = "Hello 123"
print(id(msg))
print(id(msg1))
print( msg == msg1 )
"""
Memory :
- memory pool
""" |
import functions
import Book
Books = {}
class shelfclass:
def __init__(self):
self.total=0
self.numShelves=0
self.flag=1
self.shelfName = []
self.shelfid = {}
def shelfCreation(self):
Books=functions.getDetails_shelf()
self.temp=functions.getDteails_book... |
import time
def readFile(wordSet, prefixList): #This reads the file containing all the words to reference against
f = open("words_alpha.txt","r")
for line in f:
wordSet.add(line[:-1])
for i in range(len(line)-1):
prefixList.add(line[:i])
f.close()
def findAnagram... |
# Name: Maria Roodnitsky
# Date: 5/24/2019
# Purpose: Define the vertex class
from cs1lib import *
class Vertex:
def __init__(self, vertex_name, x_position, y_position, adjacent_list): # initialize instance variables in correct
self.vertex_name = str(vertex_name) # ty... |
"""
6.5 Write code using find() and string slicing (see section 6.10) to extract the number at the end of the line below.
Convert the extracted value to a floating point number and print it out.
"""
text = "X-DSPAM-Confidence: 0.8475"
my_pos = text.find(":")
my_slice = text[my_pos+1:].strip()
my_slice = float(my_... |
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
from keras import backend as K
from matplotlib import pyplot as plt
#Tutorial followed https... |
# Golf database
"""
Class golfCourse:
variables:
courseName : String
courseRating : decimal
slopeRating : decimal
methods:
getCourseName()
getCourseRating()
getCourseSlopeRating()
"""
class golfCourse(object):
def __init__(self, name, course, slope):
self.courseName = name
self.courseRating = ... |
"""
Part One:
Given the input, the first bag contains the rest of the bags
Determine how many unique bags contain a shiny gold bag
Approach:
-Parse the bag rule and create an adjacency list with they key as the bag and the value as all the bags that that bag contains
-DFS on the graph and if a shiny gold bag is found,... |
"""
Part One: Input file of numbers. First 25 numbers are a preamble, with the 26th number and onwards being the sum of any of the two previous 25 numbers before it
The 27th element can only be the sum of two numbers between the 1st and the 26th element. Cannot use the same element twice
Find the number in the array th... |
# planet_play.py
# Zachary Mayle
# 5/29/16
from planet_constants import *
from game2d import *
from planet_models import *
import random
class Play(object):
"""An instance controls a single game of planets.
This subcontroller animates the game by moving the ship and by influencing
the ship with the ... |
""" Estrutura Condicional """
# Exemplo 1
x = 10
print('Bom dia')
if x < 0:
print('Boa tarde')
print('Boa noite')
# Exemplo 2
hora: int
hora = int(input("Digite um hora do dia: "))
if hora < 12:
print("Bom dia")
else:
print("Boa noite")
# Exemplo 3
hora: int
hora = int(input("Digite uma hora do ... |
""" Retângulo """
# Example
import math
base = float(input("Base do retângulo: "))
altura = float(input("Altura do retângulo: "))
area = base * altura
perimetro = 2 * (base + altura)
diagonal = math.sqrt(base ** 2 + altura ** 2)
print(f"AREA = {area:.4f}")
print(f"PERIMETRO = {perimetro:.4f}")
print(f"DIAGONAL = ... |
"""
Code adapted from Transformer model for language understanding example:
https://www.tensorflow.org/tutorials/text/transformer
"""
import tensorflow as tf
import tensorflow_datasets as tfds
import nltk
import matplotlib.pyplot as plt
import numpy as np
import time
import re
import random
nltk.download('punkt')
# ... |
# Usando docstrings para documentar métodos
def minha_funcao(arg1, arg2=None):
"""Minha Função que faz um print dos argumentos passados
Params:
arg1:primeiro argumento.
arg2:segundo argumento, Default: None.
"""
# Isso é uma forma de documentar o código.
print(arg1, arg2)
def ma... |
# Usando objetos defaultdict
import collections
def main():
# Definindo uma lista de itens para contar
frutas = ['maçã', 'pêra', 'laranja', 'banana',
'maçã', 'uva', 'banana', 'banana']
# TODO: Use um dicionário default para contar cada elemento
contador_frutas = collections.defaultdict(... |
def coordinate_to_tile_index(lng, lat, zoom):
import math
lat_rad = math.radians(lat)
n = 2.0 ** zoom
xtile = int((lng + 180.0) / 360.0 * n)
ytile = int((1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n)
return (xtile, ytile)
def main():
import sys
import os
args_len = len(... |
def divisors(a):
div_list = []
for i in range(1, a+1):
if a % i == 0:
div_list.append(i)
return div_list
print(divisors(int(input("Divisors for: ")))) |
"""
Here's our improved hash table implementation that uses linked list chaining to handle collisions:
Your task is create your own HashTable without using a built-in library.
Your HashTable needs to have the following functions:
- put(key, value) : Inserts a (key, value) pair into the HashTable. If the
value alre... |
def printMove(fr, to):
print('move from ' + str(fr) + ' to ' + str(to))
def Towers(n, fr, to, spare):
print 'n: '+str(n)+' start: '+str(fr) +' destnation: '+ str(to) +' aux: '+ str(spare)
if n == 1:
printMove(fr, to)
else:
Towers(n-1, fr, spare, to)
Towers(1, fr, to, spare)
... |
import math
def genPrimes():
temp = 1
while True:
temp+=1
if temp==2:
yield temp
continue
flag = False
squrt = int(math.sqrt(temp))
for i in range(2,squrt+1):
if temp%i==0:
... |
def get_subsequences(hand, length):
"""
Gets all subsequences of a given length from the hand
:param hand: total list of cards
:param length: length of subsequences to get
:param result: list of subsequences (list of list)
:param tmp_seq: current subsequence being constructed
:param idx:... |
import tkinter as tk
from background import *
from tkinter import font, messagebox, filedialog
'''--------------------------------------Utility Functions----------------------------------------'''
def framer(i, j, frameList):
'''
Function to choose the correct frame for the buttons
Args:
... |
# Déclaration de la classe Phone qui définit une catégorie de téléphones
class Phone:
"""
Le constructeur avec le mot clé __init__
Il permet de créer un objet
C'est ici qu'on définit les attributs
"""
def __init__(self, constructor, model, color, name, number):
self.constructor = constr... |
from random import randint
#help (randint)
number_to_guess = randint(1,10)
print (f"le nombre à deviner : {number_to_guess}")
has_won = False
user_propal = int(input('Rentrez un nombre entre 1 et 10 '))
while has_won == False:
while user_propal < 0 or user_propal > 10:
print ('Vous n avez pas saisi un n... |
# Les boucles en Python
# Pour
print("Boucle Pour:")
for i in range(0, 5): # pour i allant de 0 à 5 par pas de 1
print(f"--> i vaut: {i}") # je repète l'action 5 fois
print("Boucle Pour - un autre exemple:")
for i in range(1, 5, 2): # pour i allant de 1 à 5 par pas de 2
print(f"--> i vaut: {i}") # je repè... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 16 13:17:17 2021
@author: Michael
"""
adjective1 = str(input('Enter an Adjective: '))
adjective2 = str(input('Enter an Adjective: '))
bird = str(input('Enter a type of bird: '))
room = str(input('Enter a room in a house: '))
verb1 = str(input('Enter a past t... |
from tkinter import *
from tkinter.ttk import *
class vote():
bjp=0
cong=0
aap=0
tk=Tk()
tk.title("Voting app")
tk.configure(background="Black")
tk.geometry("1366x768")
tk.maxsize(1366,768)
title=Label(tk,text="Voting App",font=("Joker",50),fg="red",bg='black')
ti... |
"""
create linked lists
"""
class node(object):
"""
Nodes of linked list
Linked List Nodes store a value and points to next node
"""
def __init__(self, value):
self.value = value
self.next = None
class linked_list(object):
"""
This class is used to setup the linked li... |
#!/usr/bin/python
import argparse
import math
import string
import sys
parser = argparse.ArgumentParser("Parse optional file inputs")
parser.add_argument("-i", "--input", nargs="?", type=argparse.FileType("r"), default=sys.stdin)
args = parser.parse_args()
x = 0
y = 0
trees = set()
lines = [ x.strip() for x in arg... |
def quicksort(alist, left, right):
if left < right:
middle=partition(alist, left, right)
quicksort(alist, left,middle-1)
quicksort(alist, middle+1, right)
return alist
def partition(alist, left, right):
pivot = alist[left]
l = left+1
r = right
i=1
while (i):
... |
#!/usr/bin/env python3
# See https://docs.python.org/3.2/library/socket.html
# for a decscription of python socket and its parameters
import socket
import os
import sys
from threading import Thread
from argparse import ArgumentParser
# for the server you may find the following python libraries useful:
#import os - che... |
import math
from math import sqrt, acos
from typing import List
from common.point import Point
class DegreeStreaming:
def __init__(self, points: List[Point], tolerance: float):
"""
基于角度的轨迹压缩算法
:param points: 轨迹点
:param tolerance: 最大角度阈值
"""
self.points = points
... |
#!/usr/bin/python
from sympy import *
x,r,h=symbols("x,r,h")
r=3*x**2
h=-2*x**3
#find the minimum
dh=diff(h,x)
dh
x0=solve(dh,x)
x0
dr=diff(r,x)
dr
x0=solve(dr,x)
x0
|
import re
def RegexSearch(Password, Regex):
Search = re.compile(Regex)
if re.search(Search, Password):
return True
else:
return False
def LenghtPolicy(Password):
if len(Password) < 8:
return False
else:
return True
def VerifyPolicies(Password)... |
'''
A Recurrent Neural Network (LSTM) implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Long Short Term Memory paper: http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf
Author: Aymeric Damien
Project: https://githu... |
val=input()
list1=['a','e','i','o','u']
for i in list1:
if(val>='a' and val<='z'):
if(val==i):
m=0
break
else:
m=1
break
else:
m=2
break
if(m==0):
print("Vowel")
elif(m==1):
print("Consonant")
else:
print("Invalid")
... |
"""
Solution to Small Parsimony in an Unrooted Tree Problem.
Molecular Evolution (Bioinformatics IV) on Coursera.org
Week 3, code challenge #3
"""
import networkx as nx
import numpy as np
import wk3_02_small_parsimony as sp
def small_parsimony_unrooted(input_data):
'''
Small Parsimony in an Unrooted Tree Prob... |
"""
Solution to the Converting a Peptide into a Peptide Vector Problem.
Molecular Evolution (Bioinformatics IV) on Coursera.org
Week 4, code challenge #3
"""
import constants as co
def peptide_to_vector(peptide):
'''
Converting a Peptide into a Peptide Vector Problem.
Parameters
-----------
p... |
from time import time
m_counter=0
#complexity comparison counter
#merge function
def merge(l,au,low ,high,mid):
global m_counter
i=low
j=mid+1
k=low
#k is moving from low to high for merging operation
while( k <= high):
m_counter+=1#comparison counter is taking track of the above
... |
from time import time
#Kruskals Algorithm
first=0
#Edge Class is the data structure which is used to represent the edge which is put into the bags
#Now we have the edge with both points and weight
class edge:
def __init__(self,x,y,weigh):
self.x=x
self.y=y
self.weigh=weigh
def one_poin... |
print('Answer the following algebra question')
print('if x=8, then what is value of 4(x+3)')
da = {
'1':35,
'2':36,
'3':40,
'4':44
}
cx = 4
for v,i in da.items():
print(v,i)
choice = int(input('choice:'))
if choice == cx:
print('bingo')
else:
print(':((')
print("Estimate this answer (exact... |
print('welcome to our shop, what do you want?')
items = ['T-shirt','Sweater']
print('R')
print(*items, sep = ",")
items.append('jeans')
print('C')
print(*items, sep= ',')
items.insert(1,'skirt')
items.pop(3)
print('U')
print(*items, sep=',')
items.pop()
print('D')
print(*items, sep=',')
|
import csv
import math
min_sup = float(input("Enter minimum support"))
min_conf = float(input("Enter minimum confidence"))
min_sup_count = math.ceil(min_sup * 14)
L1 = []
outlookSet, tempSet, humiditySet, windySet, ptSet = set(), set(), set(), set(), set()
body = {"item": "",
"count": ""}
transactionList = []... |
def divide_it(x, y):
try:
out = x / y
except ZeroDivisionError:
print ' Divide by zero!'
out = None
except:
raise TypeError (' Provide a number!')
out = None
return out
DIVISION_RESULTS = {'4/2': 2, '6/3':2, '10/2':5}
|
def empty(o):
return len(o) == 0
def first(iterable):
for i in iterable:
return i
|
class Partisipant:
def __init__(self):
self.participants = list()
"""Добавление участника"""
def Adding(self, name, surname, age, email):
self.participants.append({"participant_name": name,
"participant_surname": surname,
"pa... |
print('''Fahrenheit and Celsius Calculator
''')
while True:
convert = input('''
What would you like to convert?
A) Fahrenheit to Celsius
B) Celsius to Fahrenheit
C) Exit
Enter the corrresponding letter:''')
if convert == 'C' or convert == 'c':
print("You have successfully exited")
... |
print('''Currency Conversion Calculator
''')
while True:
convert = input('''
Select a currency to convert US dollars into:
A = Indian Rupees
B = European Euros
C = Japanese Yen
D = Swiss Franc
E = Russian Ruble
F = Exit
Type in the corresponding letter: ''')
if convert == 'F' or... |
one = int(input("Give me a number: "))
two = int(input("Give me a second number: "))
print(one, '+', two, '=', (one+two))
print('''
''')
print(one, '-', two, '=', (one-two))
print('''
''')
print(one, '*', two, '=', (one*two))
print('''
''')
print(one, '/', two, '=', (one//two), 'with a remainder of', (one%two))
|
import random
def getRandNumb(start,stop,k):
return (random.sample([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80],k))
def compare ... |
"""
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
from lxml import html
import requests
import u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 16:02:12 2019
@author: lisestork
"""
import numpy as np
from math import gcd
import time
#problem 5_2:
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#
#What is the smallest positive ... |
import math
people = int(input())
capacity = int(input())
full_courses = math.floor(people / capacity)
if people % full_courses == 0:
print(full_courses)
else:
print(full_courses + 1)
|
a = int(input())
b = int(input())
c = int(input())
d = int(input())
add = a + b
divide = int(add / c)
multiply = divide * d
print(multiply) |
products = input()
res = {}
while products != "statistics":
products = products.split(': ')
prod = products[0]
quantity = int(products[1])
if prod in res.keys():
res[prod] += quantity
else:
res[prod] = quantity
products = input()
print("Products in stock:")
for k, v in res.items(... |
word = input()
for i in word:
print(i * 2, end='') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.