text stringlengths 37 1.41M |
|---|
mood = int(input("How do you feel? (1-10) "))
if mood == 1:
print("A suitable smiley would be :'(")
elif mood == 10:
print("A suitable smiley would be :-D")
elif (7 < mood < 10):
print("A suitable smiley would be :-)")
elif (4 <= mood <= 7):
print("A suitable smiley would be :-|")
elif (1 < mood < 4):
... |
player1 = input("Player 1, enter your choice (R/P/S): ")
player2 = input("Player 2, enter your choice (R/P/S): ")
if ((player1 == "P" and player2 == "R") or (player1 == "R" and player2 == "S") or (player1 == "S" and player2 == "P")):
print("Player 1 won!")
elif ((player2 == "P" and player1 == "R") or (player2 == ... |
# in this tutorial we learn how to use special methods to enable a logarithmic and special operations for the objects
class employee:
def __init__(self,first,last,salary):
self.first = first
self.last = last
self.email = self.first+'.'+self.last+'@gmail.com'
self.salary = salary
... |
def mirror_tree(root):
if root == None: return
# Do a post-order traversal of the binary tree
if root.left != None:
mirror_tree(root.left)
if root.right != None:
mirror_tree(root.right)
# Swap the left and right nodes at the current level
temp = root.left
root.left = root.... |
def fruits_into_baskets(fruits):
window_start = 0
max_length = 0
fruit_frequency = {}
# In this loop, we extend the range [window_start, window_end]
for window_end in range(len(fruits)):
right_fruit = fruits[window_end]
if right_fruit not in fruit_frequency:
fruit_freque... |
class stack_using_queues:
def __init__(self):
self.queue1 = deque()
self.queue2 = deque()
def push(self, data):
self.queue1.append(data)
def isEmpty(self):
return len(self.queue1) + len(self.queue2) == 0
def pop(self):
if self.isEmpty():
raise Excep... |
def can_segment_string(s, dict):
for i in range (1, len(s) + 1):
first = s[0:i]
if first in dict:
second = s[i:]
if not second or second in dict or can_segment_string(second, dict):
return True
return False
|
# Exercises for chapter 3: Problems 3.1, 3.2, 3.3, and 3.4 in Think Python
# chrisvans - Chris Van Schyndel
# 3.1
# NameError: name 'repeat_lyrics' is not defined
# 3.2
# The program runs properly. Function order does not matter, as long as it
# is defined before it is called.
# 3.3
def right_justify(s):
p... |
l=[1,2,3,3,3,4,1]
a=set(l)
#print a
b=list(a)
print b
l1=[]
for i in a:
result=l.count(i)
l1.append(result)
print l1
d=dict(zip(b,l1))
print d |
l=[]
def f():
for i in range(1,21):
l.append(i**2)
print l
print l[0:5]
t=tuple(l)
print t
f() |
import time
credit = 700
total = 1200
class Debitcard():
def debitvalue(self, count):
global total
string = raw_input("you want to pay(p),withdraw(w) and exit(e)")
if string == 'pay':
value = int(input("enter value"))
total += value
print("... |
s=raw_input()
d={"UPER CASE":0,"LOWER CASE":0}
for i in s:
if (i.isupper()):
d["UPER CASE"]+=1
elif (i.islower()):
d["LOWER CASE"]+=1
print "UPER CASE",d["UPER CASE"]
print "LOWER CASE",d["LOWER CASE"]
|
def choose(a, b):
res = 0
for i in range()
#Calculates how much one powerball ticket is worth based on EV
#These are odds as of 10/30/22
def ticket_worth(jackpot):
total_possibilities = 69*68*67*66*65*26
prizes = [jackpot, 1000000, 50000, 100, 100, 7, 7, 4, 4]
poss_for_each = [1, 25, 64, 64*25, 64*... |
class Cell():
''' This enumeration represents the possible states of a cell on the board '''
empty = 46
w = 119
W = 87
b = 98
B = 66
def isWhite(c):
return c == Cell.w or c == Cell.W
def isBlack(c):
return c == Cell.b or c... |
# 1. Letter Summary
# Write a letter_histogram program that asks the user for input, and prints a dictionary containing the tally of how many times each letter in the alphabet was used in the word. For example:
# def letter_histogram(word):
# my_letters = {}
# for letter in word:
# if letter in my_lett... |
def findSum():
with open('input.txt', 'r') as f:
array = []
for line in f:
array.append(int(line))
#print ("did a line \n")
numSum = 0
for i in range(len(array)):
numSum += array[i]
#print ("added one from array \n")
print (numSum)
findSum()
|
def sumOfSquares(num):
sums= 0
for i in range(1, num+1, +1):
sums = sums + (i*i)
return sums
def squareOfSum(num):
sums = 0
for i in range(1, num+1, +1):
sums = sums + i
squares = sums*sums
return squares
num =100
difference = squareOfSum(num) - sumOfSquares(num)
print "%... |
print('What is your name?: ')
name = input()
print('Your age please!: ')
age = int(input())
if name == 'Mary':
print('Hello Mary')
elif age < 12:
print('You are not Mary, Kiddo.')
else:
print('Stranger!')
print('Gimme your password: ')
password = input()
if password == 'swordf... |
print('Python과 Ruby공통 : ceil은 반올림,floor는 내림')
print("Python에서 복잡한 사칙연산을 할 때는 가장 위에 import math를 입력해야 함")
print("Python에서는 'math ceil(2.24)'와 같은 형식으로 입력해야 함")
print('Ruby에서는 "puts(2.24.floor())"와 같은 형식으로 입력해야 함')
print('hello '+'world')
print('python '*3)
print('hello' [1], '<-hello의 2번째 문자 추출. []를 이용해서 특정 문자를 추출할 수 있음... |
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def add(self):
return self.v1 + self.v2
def subtract(self):
return self.v1 - self.v2
def setV1(self, v1):
if isinstance(v1, int):
self.v1 = v1
def ... |
print(type('har'))
name = 'har'
print(name)
print(type(['har', 'new year', 'korean']))
names = ['har', 'new year', 'korean', 33, True]
print(names[4])
names[1] = 2019
print(names)
|
a = int(input("Enter the 1st Number :- "))
b = int(input("Enter the 2nd Number :- "))
c = int(input("Enter the 3rd Number :- "))
if a>b and a>c:
print("A is Greater than B and C .")
if b>a and b>c :
print("B is greater than A and C .")
if c>a and c>a:
print("C is greater than A and B .")
|
import os
# operating system
# get file names in a folder in Python
# get the files from here
# https://s3.amazonaws.com/udacity-hosted-downloads/ud036/prank.zip
def rename_files():
#(1) get file names from a folder
file_list = os.listdir("/Users/bp/Documents/takeBreakProgram/prank")
# for windows os.listdir(r"c:\oo... |
from math import sqrt
from time import time
primes = [2]
def new_square(old_n):
n = old_n + 1
square = n ** 2
return square, n
def inner_loop(num, base_in):
for x in primes:
if num % x == 0:
return False
if x >= base_in:
return True
start = time()
square, ... |
# https://en.wikipedia.org/wiki/United_States_presidential_election
# This Wikipedia page has a table with data on all US
# presidential elections. Goal is to scrape this data
# into a CSV file.
# Columns:
# order
# year
# winner
# winner electoral votes
# runner-up
# runner-up electoral votes
# Use commas as delimi... |
def reverse(i,word):
j=len(i)
k=len(word)
x=0
y=0
flag=0
while x<j:
if (i[x]==word[0]):
while(k>y):
if(i[k]==" ")and(i[k]!=word[y]):
break
k=k-1
y=y+1
else:
flag=1
... |
def swap(x,y):
temp=x
x=y
y=temp
x=2
y=3
swap(x,y)
print("x is",x)
print("y is",y)
|
def fib(n):
if (n==0)or(n==1):
return n
else:
r=fib(n-1)+fib(n-2)
return r
terms=int(input("enter an integer"))
for i in range(terms):
f=fib(i)
print(f)
|
num=int(input("enter a number"))
k=""
while num>0:
remainder=num%2
num=num//2
k=str(remainder)+k
print(k)
|
a,b,c,d=int(input("enter 4 numbers")),int(input()),int(input()),int(input())
if(a>b):
if(a>c):
if(a>d):
print(a,"is te greatest number")
else:
print(d,"is the greatest number")
elif(c>d):
print(c,"is the greatest number")
elif(b>c):
if(b>d):
... |
a=int(input("enter a number"))
if(a>=0):
print(0-a)
elif(a==0):
print(0)
else:
print(0-a)
|
def sum1(n):
if n<=1:
return n
else:
return n+sum1(n-1)
print(sum1(6))
|
x=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(x[0])):
x[i][j]=int(input("ente
for k in x:
print(k)
|
items = [float, list, 5, 3, 4, 234,4435,34, 34, 2,3,32]
for item in items:
if str(item).isnumeric() and item>6:
print(item) |
#Faulty calculator
# 45 * 3 =555, 56 + 9 = 77, 56/6 = 4
N1 = int(input("Enter first number: "))
print("What to do? +,-,/,*")
operator = input()
N2 = int(input("Enter second number: "))
if N1==45 and N2==3 and operator=="*":
print("N1","*", "N2", "=" , 555)
elif N1==56 and N2==9 and operator=="+":
print... |
"""Finds the maximum product of adjacent numbers."""
from operator import mul
def _load_grid(file_name):
"""Loads a grid of numbers from a file.
Args:
file_name - Name of the grid file.
Returns:
List of lists of ints.
"""
grid = list()
with open(file_name, 'r') as grid_file:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 14:19:30 2020
@author: mboodagh
"""
""" The purpose of this program is to read and write data related to the behavior of a Racoon named George based on the given instructions"""
#import required modules
import math
##### Required functions sect... |
# Solution of Question2
# No any input validations.
# Usage: $python3 question2.py
# Enter number of strings you will entered in the first line.
# Enter strings line by line starting from the second line.
# =============
# Example input:
# Number of strings you will entered: 2
# ababaa
# aa
# =============
# getPrefixe... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
self.total = 0
def sum_left(node, is_left ... |
#!/usr/bin/python3
# -*- conding:utf-8 -*-
import sys
import pygame
from Button import Button
from register_window import register_window
from login_window import login_window
from success_window import *
#小程序的main函数,调用登录和注册两个函数
def run_game():
pygame.init()
while True: #main loop for the game
pygame... |
"""
This file implements diffusion of a bunch of particles
put in a bath. the system description id given in diffusion_models.py
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from diffusion_models import *
step = infinite_surface # check diffusion_models.py for more
N =... |
'''
This is an animation showing a standing wave in a cavity
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
n = 2
a = 10
E0 = 5
c = 3
x = np.linspace(0,a,100)
t = np.linspace(0,10,100)
E = E0*np.sin(n*(np.pi/a)*x)
fig = plt.figure()
ax = fig.add_subplot(111,xlim=(... |
"""
Student Naam: Wouter Dijkstra
Student Nr. : 1700101
Klas : ??
Docent : frits.dannenberg@hu.nl
"""
class ListNode:
def __init__(self,data, next_node):
self.data = data
self.next = next_node
def __repr__(self):
return str(self.data)
class MyCircularLinkedList:
... |
"""
Student Naam: Wouter Dijkstra
Student Nr. : 1700101
Klas : ??
Docent : frits.dannenberg@hu.nl
"""
"""
Description
-----------
Takes an integer n to return all the prime numbers from 2 to n
Parameters
----------
n : integer
amount of numbers to check
Return
------
primes : list
list of... |
def convert_to_binary_from_decimal(n):
'''Argument should be an integer'''
arr = []
while(n!=0 and n!=1):
k= n%2
arr.append(str(k))
n = int(n/2)
arr.append("1")
arr.reverse()
return str("".join(arr))
def convert_to_decimal_from_binary(n):
'''Argument can be in both ... |
"""
Exple from ChaseMathis
https://www.youtube.com/watch?v=qNlKO0L4gMI
https://github.com/ChaseMathis/Speech-Recognition
"""
import webbrowser
import string
import speech_recognition as sr
# obtain audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Hello, what can i help you find?[Player lookup,... |
#binary string to int
def btoi(str_to_bin):
# count = len(str_to_bin) -1
# value = 0
# for char in str_to_bin:
# value += int(char) * (2 ** count)
# count -= 1
# return value
return int(str_to_bin,2)
#gray string to bin striny
def gtob(gray):
binary = gray[0] #msb always sam... |
"""List utility functions part 2."""
__author__ = "730385108"
def only_evens(x: list[int]) -> list[int]:
"""This function will print the even numbers in the list."""
i: int = 0
evens = list()
while (i < len(x)):
if x[i] % 2 == 0:
evens.append(x[i])
i += 1
else... |
# encoding: utf-8
"""
@version: python3.5.2
@author: kaenlee @contact: lichaolfm@163.com
@software: PyCharm Community Edition
@time: 2017/7/19 17:14
purpose:
"""
from itertools import chain
ch = chain([1, 2, 3], ["a", "b"], range(3))
print(list(ch))
def myChain(*x):
for i in x:
for j in i:
... |
#!/usr/bin/env python
#coding:utf-8
"""
Author: kaen.lee--<lichaolfm@163.com>
Purpose:
Created: 2017/2/9
Version: python3.5.2
"""
import unittest
class montyHall:
#----------------------------------------------------------------------
def __init__(self, choice, montyopen):
""""""
sel... |
# coding=UTF-8
'''
#Created on 2016年7月12日@author: kaen
'''
'''===================================文件模式
r: 读模式
w: 写入模式
a: 追加模式
+(可组合): 读/写模式
b(可组合): 二进制模式,处理声音剪辑,图片,就需要,’rb‘,用来读取一个二进制文件
'''
'''==================================缓冲
第3个参数为缓冲参数 0/False;无缓存直接对硬盘数据进行读写,比较慢
1/true; 缓存,使用flush/close才会对硬盘数据更新,程序运行较快
'''
f = open(... |
# Objective
# In this challenge, we learn about conditional statements. Check out the Tutorial tab for learning materials and an instructional video.
# Task
# Given an integer, , perform the following conditional actions:
# If N is odd, print Weird
# If N is even and in the inclusive range of 2 to 5, print Not Weird
... |
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
# initialize global variables used in your code
num_range = 100
secret_num = 0
guesses_left = 0
# helper ... |
'''
Mainīgais dictionaries
a = {1:1,2:2,3:3}
'''
#Elementiem var būt dažādi datu tipi
#Teksts
pirmais = {'atsl1':'vertiba1','atsl2':'vertiba2'}
print(pirmais)
#Skaitļi int,float
otrais = {'atsl1':2, 'atsl2':2.5}
print(otrais)
#Lists
tresais = {'atsl1':[1,2,3], 'atsl2':[4,5,6]}
print(tresais)
#Dictionary
ceturtais =... |
import math
class TCircle:
def __init__(self, r, x, y):
self.r = r
self.x = x
self.y = y
def S(self):
return self.r**2 * math.pi
def R(self, n, m):
return (self.x - n) ** 2 + (self.y - m) ** 2 == self.r ** 2
def __add__(self, other):
return TCircle(ot... |
# Implement a receipt function that takes as an input a cart with items
# and their corresponding prices, tax and promos and returns the total
def calculate(cart):
net = 0
tax = 0
promo = 0
total = 0
for items in cart:
net += cart[items]["net"]
tax += cart[items]["tax"]
pro... |
if __name__ == '__main__':
a = [0]
pos = 0
step = 359
n = 2017
for val in range(1,n+1):
#val is also the length of a at top of loop
pos = (pos+step)%val
a.insert(pos+1, val)
pos += 1
final_index = a.index(n)
answer_index = (final_index+1)%len(a)
print(a[a... |
import math
class Circle(object): # new-style classes inherit from object
'An advanced circle analytics toolkit'
'''
- When you are going to create many instances of the Circle class,
you can make them lightweight by using the flyweight design pattern.
- The flyweight design pattern suppresse... |
# ECE-467 Project 1
# Layth Yassin
# Professor Sable
# This program is an implementation of the CKY algorithm as a parser.
import re
# function returns the grammar rules (A -> B C or A -> w) in a dict where the keys are the non-terminal A, and the items are
# either a list of tuples (B, C) or a list of string... |
'''
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end].
Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
'''
'''查找字符串,仅在需要返回索引时调用,否则使用in'''
print('sssSSS'.find('SS'))
print('SS' in 'sssSSS')... |
'''
Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:
>>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Gu... |
'''
str.lower()
Return a copy of the string with all the cased characters [4] converted to lowercase.
'''
'''将字符串中的字母转化为小写'''
print('123'.lower())
|
'''str.encode(encoding="utf-8", errors="strict") '''
'''Return an encoded version of the string as a bytes object.
Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme.
The default for errors is 'strict', meaning that encoding errors raise a UnicodeError.
Other possible values are '... |
def hello():
name = input("Enter name: ")
month = input("Enter month: ")
print("Happy birthday " + name)
if month.lower() == "august":
print("Happy birthday " + month)
hello() |
import math
"""
Uwaga: Proxy i Calculator powinny dziedziczyć z tej samej klasy-matki
"""
class Proxy:
def __init__(self):
self.memory = {}
def square_equation(self, a, b, c):
try:
print(str(a) + "x^2 + " + str(b) + "x + " + str(c))
print("Szukam rozwiązania w proxy.... |
# input the sentences file and output a pickle file, meanwhile display first three output
# Run by: python BrownCluster.py input.txt output.txt
import csv
import nltk
import pickle
import sys
# Load the Twitter Word Clusters into a dictionary
def get_cluster_dic(file):
f = open(file)
cluster_dic = {}
csv_f = csv.rea... |
import numpy as np
class Ant():
def __init__(self, board, rules, startPosition=None):
self.rules = rules
self.board = board
if startPosition:
self.position = np.array(startPosition)
else:
self.position = np.array([0, 0]) # x, y tuple (or NP array)
s... |
print("This is a hello application");
name = input("Write your name: ");
age = input("Enter your age: ");
print("Hello", name, "you are", age, "years old");
|
def oddoreven(a):
if a%2 is 0:
print("This number is even.")
else:
print("This number is odd.")
oddoreven(int(input("Enter a number: ")))
|
from math import ceil
minute = int(input("Enter parking time in minutes: "))
print(f"Parking fee is {ceil(minute/60)*25} baht.")
|
#=========== answer =================
def decrypt(msg):
return "".join(list(msg.replace('G','d').replace('D','o').replace('O','g').upper())[::-1])
"""
#for debuging
msg = msg.replace('G','d')
msg = msg.replace('D','o')
msg = msg.replace('O','g')
msg = msg.upper()
msg = list(msg)
msg.reverse(... |
class Solution:
def isMatch(self, s, p):
s_len = len(s)
p_len = len(p)
f = [[False for i in range(s_len)] for j in range(p_len)]
if s_len == 0 and p_len == 0:
return True
if s_len == 0:
res = True
for i in range(p_len):
if p... |
prive_of_house = 1000000
down_payment = (prive_of_house - 200000)
goof_credit = ()
bad_credit = ()
if goof_credit == True:
print("your payment is; ", (prive_of_house - 100000))
elif bad_credit == True:
print("Yuor down payment will be:", down_payment)
else:
print("you dont ahve enough credit") |
# AI Car
# import the pygame module, so you can use it
import pygame
# define a main function
def main():
screen_width = 900
screen_height = 900
# initialize the pygame module
pygame.init()
pygame.display.set_caption("minimal program")
# create a surface on screen that has the size of 240 x ... |
import string
def text_analyzer(text = None):
''' This function counts the number of upper characters, lower characters,
punctuation and spaces in a given text. '''
if text == None:
text = input("What is the text to analyze ?\n")
while (len(text) == 0):
text = input("What is the text to analyze ?\... |
import sys
if len(sys.argv) == 2 and sys.argv[1].isdigit():
if sys.argv[1] == 0:
print("I'm Zero")
elif int(sys.argv[1]) % 2 == 0:
print("I'm Even")
else:
print("I'm Odd")
else:
print("ERROR")
|
def inversa(array):
for i in range(len(array)):
print(array[0][i])
lista = ["amor"]
array = lista[0]
print(enumerate(array))
inversa(lista)
#print() |
mascotas = {'gato': {'Maria', 'Luis'},
'perro': {'Maria', 'Karen', 'Ana'},
'rana':set(),
'conejo': {'Maria', 'Karen', 'Juan'}}
test = (mascotas['perro'] & mascotas['conejo']) - mascotas['gato']
print(test)
mascotas['rana'] = "pollas"
print(mascotas)
var = list("ba127342b598d6ea5aba28109bc8dc57")
var2 =... |
import sys
if len(sys.argv) > 3:
print("Input error: too many arguments")
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
if len(sys.argv) < 3:
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
if sys.arg... |
palindromo = input("Introduce una palabra\n")
j = 1
for i in palindromo:
if (i == palindromo[-j]):
ispa = True
j += 1
else:
ispa = False
break
if ispa:
print("Es un palíndromo")
else:
print("No es un palíndromo") |
val = input().split()
N = int(val[0])
M = int(val[1])
def BackTrack(stack, num, currHeight):
stack[currHeight] = num
if currHeight == M:
answer = ''
for i in range(1, M + 1):
answer += (str(stack[i]) + ' ')
print(answer)
else:
for i in range(1, N + 1):
... |
import sys
# BFS
class Queue:
queue = []
def enqueue(self, x):
self.queue.append(x)
def dequeue(self):
val = self.queue[0]
del self.queue[0]
return val
def getSize(self):
return len(self.queue)
val = sys.stdin.readline().split()
S = int(val[0]) # Start
D = int... |
"""
File: cooling.py
Copyright (c) 2016 Krystal Lee
License: MIT
<find cooling rate of tea of every minute>
"""
t = 0 #minutes
T_tea = 100 #degrees C, temperature of the tea
T_air = 20 #degrees C, temperature of the room
k = 0.055
# - k(T_tea - T_air) #the rate of cooling; after 1 min the tea temp will be k(T_tea-... |
def _sanitize_char(input_char, extra_allowed_characters):
input_char_ord = ord(input_char)
if (ord('a') <= input_char_ord <= ord('z')) \
or (ord('A') <= input_char_ord <= ord('Z')) \
or (ord('0') <= input_char_ord <= ord('9')) \
or (input_char in ['@', '_', '-', '.']) \
or (i... |
# -*- coding:utf-8 -*-
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if len(ss)==0:
return []
temp = itertools.permutations(ss)
temp = [''.join(i) for i in temp]
temp = list(set(temp))
temp = sorted(temp)
return temp... |
## queue
class Queue ():
def __init__(self):
self.songs = []
def isEmpty(self):
return self.songs == []
def enqueue(self, song, userid, url):
if self.isEmpty():
self.songs.append((0, song, [], url))
else:
if (self.search(song) == -1):
self.songs.append((1, song, [userid], url))
self.sort(... |
import sys
def get_key(dic, search_value):
for k,v in dic.items():
if v == search_value:
return k
def get_state(capital):
if len(capital) != 1:
exit()
else:
if get_key(capital_cities,capital[0]) != None:
print(get_key(states,get_key(capital_cities,capital[0])))
else:
print("Unknown capital city")... |
#Funciones para la base de datos
import sqlite3
"""has(userid int, ingredient varchar(20), PRIMARY KEY(userid, ingredient)) """
""" recipes (recid int, name varchar(20), n int, ingredients varchar(255), pic varchar(20), PRIMARY KEY(recid))''') """
'''users (userid int, username varchar(20), password varchar(20), PRIMA... |
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who h... |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import sqlite3
'''
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print... |
#!/usr/bin/python3
"""Script to print a square
Attributes:
size(int): is the size of the square
if it fails raise a error
Example: ./4-main.py"""
def print_square(size):
"""print the a square
:argument
size(int): is the size of the square
:return
No return nothing"""
if type(si... |
#!/usr/bin/python3
def uppercase(words):
for word in words:
if ((ord(word) >= 97) and (ord(word) <= 122)):
word = chr(ord(word) - 32)
print("{}".format(word), end="")
print("")
|
#!/usr/bin/python3
def update_dictionary(a_dictionary, key, value):
for a_key in a_dictionary:
if a_key is key:
a_dictionary[a_key] = value
return a_dictionary
a_dictionary.update({key: value})
return a_dictionary
|
#!/usr/bin/python3
for word in range(ord('a'), ord('z')+1):
if ((word is not 113) and (word is not 101)):
print("{:c}".format(word), end="")
|
#!/usr/bin/python3
"""simple script"""
def add_attribute(Class_v, class_att, fill_atr):
"""this functio track how many t"""
if isinstance(Class_v, type):
setattr(Class_v, class_att, fill_atr)
else:
raise Exception('can\'t add new attribute')
# class_v.counter = getattr(class_v, "coun... |
#!/usr/bin/python3
"""Test if the object is inherent of a class"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Square(BaseGeometry):
""" it seems is a figure that it will be a sum of an operatiom"""
def __init__(self, size):
self.__size = super().integer_validator("size", size)
... |
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
if not a_dictionary:
return a_dictionary
new_dict = a_dictionary.copy()
for a_key in new_dict:
new_dict[a_key] = new_dict[a_key] * 2
return new_dict
# new_dic = {doub: v * 2 for doub, v in a_dictionary.items()}
|
r"""test_emails.txt
$"""
import re
re.findall(pattern, string)
re.search()
# matches the first instance of a pattern in a string, and returns it as a re match object.
# we can’t display the name and email address by printing it directly.
# Instead, we have to apply the group() function to it first.
# We’ve printed b... |
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board:
for i in range(len(board)):
if board[i][0]=='O':
self.bfs(board,i,0)
if board[i][l... |
class Solution:
def twoSum(self, nums, target):
"""
The function inputs are list of integers and an target integer
Function then scan an array for numbers wich will add up to make a target integer
Output is a list of indices of those numbers in a list
"""
numbers = {}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.