text stringlengths 5 121k |
|---|
dict1 = {
'name': 'Tom',
'age': 20,
'gender': '男'
}
for key in dict1.keys():
print(key)
for val in dict1.values():
print(val)
for item in dict1.items():
print(item, item[0], item[1])
for key, value in dict1.items():
print(f'{key}:{value}')
|
import pandas as pd
names = ['Bob','Jessica','Mary','John','Mel']
grades = [76,83,77,78,95]
GradeList = zip(names,grades)
df = pd.DataFrame(data = GradeList, columns=['Names', 'Grades'])
get_ipython().run_line_magic('matplotlib', 'inline')
df.plot()
import matplotlib.pyplot as plt
df.plot()
displayTex... |
import random
class AI:
RANDOM = "RANDOM"
def __init__(self, strategy):
self.strategy = strategy
def random(self, actions):
"""
Randomly select an action.
:param actions: A list of valid actions a player can make.
:return: A single action.
"""
retu... |
class Billing:
"""metodo que devuelve el billing id de la tabla purchase"""
def getBillId(self):
return self.__billId
def setBillId(self, billId):
self.__billId = billId
"""metodo usado para obtener el nombre de un producto para ser mostrado en el billing detail"""
def getProdNam... |
class Solution:
def hIndex(self, citations: List[int]) -> int:
if not citations: return 0
index = len(citations)
count = 0
citations.sort()
while index > 0:
if index <= citations[count]:
re... |
class Solution:
def isPalindrome(self, x: int) -> bool:
temp = x
p = 0
if x<0:
return False
while x != 0:
p =p*10 + x%10
x=x//10
if p == temp:
return True
else:
return False ... |
def validate_date(date):
try:
day = int(date.split(".")[0])
month = int(date.split(".")[1])
year = int(date.split(".")[2])
except:
return False
if day>31:
return False
if month>12:
return False
if month == 2 and year % 4 !=0 and day>28:
return... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
... |
class Pilha:
def __init__(self):
self.lista_filmes = []
def tamanho(self):
return len(self.lista_filmes)
def pop(self):
return self.lista_filmes.pop()
def push(self, item):
return self.lista_filmes.append(item)
gisele = Pilha()
gisele.push("A lagoa Azul")
gis... |
def func(a, b):
n = len(a)
m = len(b[0])
y = [[0 for y in range(m)] for x in range(n)]
for i in range(n):
for j in range(m):
s = 0
for k in range(i):
s = s + a[i][k] * y[k][j]
y[i][j] = b[i][j] - s
x = [[0 for y ... |
a = input("Введите число: ")
b = int(input("Из какой системы счисления конверировать? "))
c = int(input("В какую систему счисления? "))
def convert_base(num, to_base=10, from_base=10):
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
alphabet = "0123456789ABCDE... |
class CaesarCipher:
"""シーザー暗号"""
def __init__(self, plain_text, key=3):
self.plain_text = plain_text
self.key = key
self._check_input()
def _check_input(self):
if len(self.plain_text) == 0:
print("入力エラー。英字小文字a-zを入力してください")
exit()
for s in ... |
"""
Line 1 produced random integers between and including 5 and 20.
Line 2 produced random odd integers between 3 and 10. It would not produce a 4.
Line 3 produced a random number of 15 decimal places between 2.5 and 5.5.
"""
import random
print(random.randrange(1, 101))
|
class BankAccount:
def __init__(self, int_rate=0, balance=0):
self.int_rate=int_rate
self.balance=balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance += amount
return self
def display_acc... |
import subprocess
import optparse
import re
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="Interface to change its MAC Address")
parser.add_option("-m", "--mac", dest="mac_address", help="New Mac Address that ... |
import spacy
import operator
from collections import Counter
def sumbasic(doc, sum_length = 1):
""" Implementation of sumbasic text summarization algorithm. Picks representative sentences based on high word frequencies.
Args:
doc (spacy.tokens.doc.Doc): spacy document to summarize
sum_length (... |
import plotly.express as px
import csv
import numpy as np
import pandas as pd
def data():
temp = []
sales = []
with open("icecreamdata.csv") as data:
df = csv.DictReader(data)
for row in df:
temp.append(float(row['Temperature']))
sales.append(float(row['I... |
from Faixa import faixa,salvar,ler
musica = input('Informe o nome da Musica \n')
artista = input('Informe o nome do Artista \n')
album = input('Informe o nome do Album \n')
faixa = faixa(musica,album,artista)
salvar(faixa)
lista_ler = ler()
for faixa in lista_ler:
print(f"{faixa['musica']} | {faixa['a... |
import turtle
t=turtle.Turtle()
t.shape('turtle')
n=int(input('몇각형을 그리시겠어요?(3-6):'))
for i in range(n):
t.fd(100)
t.lt(360/n)
|
from tkinter import *
window=Tk()
btnList=[None]*3
for i in range(0,3) :
btnList[i]=Button(window, text='버튼'+str(i+1))
for btn in btnList :
btn.pack(side=TOP, fill=X, ipadx=30, ipady=30, padx=10, pady=10)
window.mainloop()
|
class student:
def details(self,name,age):
self.name=name
self.age=age
print('the name is {} age is {}'.format(name,age))
s=student()
name=input('Enter name ')
age=int(input('enter the age'))
s.details(name,age) |
from tkinter import *
root = Tk()
def printname():
print('Welcome')
frame = Frame(root,width=300, height=300)
frame.pack()
button1=Button(root,text='click here', command=printname)
button1.pack()
root.mainloop()
|
import pandas as pd
class ToxicComments:
"""
Creating list of toxic comments from default file
"""
@staticmethod
def read_file(file_name=None):
"""
Reading default file
:param file_name: file with toxic comments
:return: read file
"""
fixed_df = p... |
def binary_search(x, sorted_list):
if len(sorted_list) == 1:
return False
half = len(sorted_list)//2
if x == sorted_list[half]:
return half
if x < sorted_list[half]:
return binary_search(x, sorted_list[:half])
if x > sorted_list[half]:
return half + binary_search(x... |
cars = 100
space_in_the_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_the_car
average_passengers_in_the_car = passengers/cars_driven
print("There are", cars, "cars available")
print("There are only", drivers, "drivers available")... |
def desenha(largura, altura):
while (largura > 0):
n = altura
while n > 0:
if (n == largura) and (largura > 1 or n > 1):
print(" ")
else:
print("#", end = "")
n = n - 1
print()
largura = largura - 1
... |
def vogcons(n):
vogal = ["a" , "e", "i", "o", "u", "A", "E", "I", "O", "U"]
if n in vogal:
print("Vogal")
else:
print("Consoante")
x = input("Digite uma letra: ")
vogcons(x)
|
def sort_selection(user_input):
l = len(user_input)
for i in range(l-1,0,-1):
max = 0
for j in range(1,i+1):
if user_input[j]>user_input[max]:
max = j
user_input[max],user_input[i] = user_input[i],user_input[max]
return user_input
if __name_... |
'''
This code checks whether the Climaduino parameters should be changed based on
day of the week and time of day.
It will be triggered at regular intervals. The code will not check for the exact time,
but will rather adjust for whatever the interval it is using is. So, if a 5 minute interval
is being used, it is 11:0... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
pinList = [27]
for i in pinList:
GPIO.setup(i, GPIO.OUT)
try:
GPIO.output(27, GPIO.LOW)
print ("ON")
except KeyboardInterrupt:
print (" Quit")
GPIO.cleanup()
|
def get_neighbors(state_matrix, x, y):
"""
For a given cell, computes the neighbors, check if they are valid and returns a list.
:param state_matrix: Matrix containing the state of the game
:param x: x coordinate of cell of interest
:param y: y coordinante of cell of interest
:return: List of va... |
def FindCost(C, Height, N):
Height = list(Height)
C = list(C)
total_cost = 0
for i in range(N-1):
if Height[i]>=Height[i+1]:
total_cost += 0
else:
total_cost += C[i]
return total_cost
N = int(input())
Height = map(int, input().split())
C = map(int, input(... |
input_string = input()
reverse_string = input_string[::-1]
if input_string == reverse_string:
print('YES')
else:
print('NO')
|
x = int(input("Give a number: "))
if x == 5:
print("The number is 5")
elif x == 6:
print("The number is 6")
else:
print("The number is neither 5 or 6")
|
def fibonacci_list(num_items):
numbers = []
a, b = 0, 1
while len(numbers) < num_items:
numbers.append(a)
a, b = b, a+b
return numbers
def fibonacci_gen(num_items):
a, b = 0, 1
while num_items:
yield a
a, b = b, a+b
num_items -= 1
if __name__ == '__ma... |
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
self.trie["value"] = False
def find(self, h, key):
try:
ans = h[key]
except:
return 0
else:
return ans
de... |
name = input("Enter the String:")
x, y = 0, 0
l = len(name)
mylist=list()
tup =('A', 'E', 'I', 'O','U')
for i in range(l):
for j in range(i+1, l+1):
s=name[i]
mylist.append(s)
if s[0] in tup:
x = x + 1
else:
y = y + 1
if x > y:
print("Vowel", x... |
n = int(input('Enter Number of rows :'))
for i in range(0, n):
for j in range(n, i, -1):
print(' ', end='')
for k in range(0,i+1):
print('* ', end='')
print()
|
n = int(input("Enter Number of rows :"))
for i in range(0, n):
for j in range(1, n-i+1):
print(j, end=' ')
print()
|
try:
xrange
except NameError:
xrange = range
for i in xrange(1, 101):
print(i if i % 5 else "Buzz") if i % 3 else (
"Fizz" if i % 5 else "FizzBuzz")
|
def count_character(string, target):
total = 0
for ch in string:
if ch == target:
total += 1
return total
print(count_character("bonobo", "o"))
|
ROWS = 6
COLUMNS = 7
EMPTY = '.'
PLAYER_ONE = 'B'
PLAYER_TWO = 'R'
board = [[EMPTY for _ in range(COLUMNS)] for _ in range(ROWS)]
def print_board():
print()
print(' '.join([str(n) for n in range(COLUMNS)]))
for row in board:
print(' '.join(row))
def get_input():
while True:
col = input("Wh... |
import pyinputplus as pyip, time
costs = {
'wheat': 0.20,
'white': 0.10,
'sourdough': 0.30,
'tofu': 0.10,
'turkey': 0.20,
'chicken': 0.30,
'ham': 0.40,
'cheddar': 0.10,
'swiss': 0.20,
'mozzarella': 0.30,
'mayo': 0.10,
'mustard': 0.10,
'lettu... |
import csv
vegetables = [
{"name": "eggplant", "color": "purple"},
{"name": "tomato", "color": "red"},
{"name": "corn", "color": "yellow"},
{"name": "okra", "color": "green"},
{"name": "arugula", "color": "green"},
{"name": "broccoli", "color": "green"},
]
with open('vegetables.csv', 'w') as f:
writer = cs... |
"""
Given a list of coin denominations, determine the fewest number of coins needed
to make a given amount.
"""
def makeChange(coins, total):
"""
Determine the fewest number of coins needed to make a given amount.
Arguments:
coins: list of coin denominations
total: total amount to make
... |
"""
Created on Sun Jul 11 22:13:41 2021
@author: ssing
"""
fn= input("Input the Filename: ")
f = fn.split('.')
print ("The extension of the file is : " + f[-1]) |
PI = 3.1416
radius = raw_input('enter radius of circle(meters):')
area = PI * float(radius) ** 2
print("\narea of circle = %.2f sq. meters" % area) |
'''
Description: The aim of this code is to identify if a given numer is a power of 2.
The program requires user input.
The method keeps bisecting the number by 2 until no further division by 2 is possible.
'''
def check_power_of_two(a, val):
if (a <= 0):
print("Number is zero!")
... |
'''
This is an example for showing different types of random number generation for quick reference.
'''
import os
import random
random1 = random.random()
print(f"\nRandom floating value value between using random.random() = {random1}\n")
random2 = random.uniform(1, 5)
print(f"Random floating vlaue between 1 and... |
"""
Created on Mon May 28 17:16:29 2018
@author: cdh66
"""
class Node:
def __init__(self,item):
self.val = item
self.next = None
class LinkedList:
def __init__(self,item):
self.head = Node(item)
def add(self,item):
cur = self.head
while cur.next i... |
import stdio
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
if ((a % b == 0) and (b % a == 0)):
stdio.writeln('Both')
elif ((a % b == 0) or (b % a == 0)):
stdio.writeln('One')
else:
stdio.writeln('Neither')
|
import stdio
import sys
stdio.writeln('Prepare to enter the original matrix.')
stdio.write('How many rows? ')
n = stdio.readInt()
stdio.write('How many columns? ')
m = stdio.readInt()
original = [[stdio.readInt() for i in range(m)] for j in range(n)]
transposed = [[row[x] for row in original] fo... |
import sys
import stdio
def add(x, y):
"""
Returns the addition of two floats
"""
return float(x) + float(y)
def sub(x, y):
"""
Returns the subtraction of two floats
"""
return float(x) - float(y)
def mul(x, y):
"""
Returns the multiplication of two floa... |
def display_result(winner, score, **other_info):
print("The winner was " + winner)
print("The score was " + score)
for key, value in other_info.items():
print(key + ": " + value)
display_result(winner="Real Madrid", score="1-0",
overtime ="yes", injuries="none",... |
import os
def card_has_errors():
region = os.environ.get('CARD_TYPE', 'Europe')
if region == 'China':
num = card_has_errors_china()
else:
num = card_has_errors_europe()
return num
def card_has_errors_china():
temp_num = []
while True:
if len(temp_num) == 3:
... |
import webbrowser
class Movie():
""" This class provides a way to store movie related information
Args:
movie_title (str): Title of movie
movie_storyline (str): Brief description of the story line of the movie
poster_image (str): URL of an image to be used for the movie ie poster
... |
def BruteForce(p, t):
i = 0
j = 0
while j < len(p) and i < len(t):
if t[i] != p[j]:
i = i - j
j = -1
i = i + 1
j = j + 1
if j == len(p):
return i - len(p)
else:
return -1
print(BruteForce("is", "This is a book~!"))
def Bmoore(pt, test... |
from Lab3 import MyQueue
def EnDe(mode,code,text):
FinalText = MyQueue()
if (mode == 'E' or mode == 'e'):
for i in text:
if(i != ' '):
num = ord(i) + code.deQueue()
if num > ord('z') and ord(i) >= 97... |
from graphics import *
def main():
win = GraphWin("Triangles", 500, 500)
click_prompt = Text(Point(250, 250), "Click three times")
click_prompt.draw(win)
click_prompt.setSize(20)
click_prompt.setFill("blue")
pt1 = win.getMouse()
circ1 = Circle (pt1, 5)
circ1.draw(win)
... |
def is_balanced(root):
if root == None or (root.l_child == None and root.r_child == None):
return True
if root.l_child == None:
l_height = 0
else:
l_height = count_height(root.l_child, 1)
if root.r_child == None:
r_height = 0
else:
r_height = count_height(root.r_child, 1)
return is_balanced(root.l_chil... |
def set_zeros(matrix):
for i, row in enumerate(matrix):
for j, element in enumerate(row):
if element == 0:
for k in row:
k = 0
for row1 in matrix:
row1[j] = 0
|
def checkInput(myinput) :
while (myinput.isnumeric() == False) :
print('Invalid input, must be a number greater than 0')
myinput = input('Enter number: ')
return int(myinput)
print('This will print the Fibonacci sequence up to the desired number.')
intinput = checkInput(input('Enter number: '))
whi... |
tup = ('Hello','World')
print(tup)
numbers = (1,)
print(numbers)
print(len(numbers))
names = tuple(('test','test'))
print(names.count('test'))
print(names.index('test'))
superstars = ['Tom','Jerry']
names = (superstars,'Spike')
print(names)
names[0].append('Mike')
print(names)
for name in names:
print(name) |
s = 'Hello, Word!'
s = 'hello, Word!'
print(s[0])
print(s*3)
print(s[4:8])
print('He' in s)
print(s.capitalize())
print(s.center(20,'-'))
print(s.count('o'))
print(s.endswith('!',0,13))
print(s.find(',',10,13)) |
import socket
my_socket = socket.socket()
address = input('Enter IPv4 address of server: ')
port = int(input('Enter port number of server: '))
host = socket.gethostname()
my_socket.connect((address,port))
print(my_socket.recv(1024))
my_socket.close()
|
fruit = input('Enter a string: ')
index = len(fruit)
while index > 0:
letter = fruit[index-1]
print (letter)
index = index - 1 |
"""
Mingyang Xue, Coco Cheng
CSE 163 AG, AF
This file implements test functions for the final project.
"""
import pandas as pd
import matplotlib.pyplot as plt
import q1CleanData
import q1
import q2
def testq1Num(dt, num):
"""
Takes in the cleaned dataset dt and the num from q1
Tests q1 by calculating t... |
from collections import deque
graph = {}
graph["you"] = ["bob","claire","alice"]
graph["bob"] = ["anuj","peggy"]
graph["claire"] = ["thon","jonny"]
graph["alice"] = ["peggy"]
graph["anuj"] = []
graph["peggy"] = []
graph["thon"] = []
graph["jonny"] = []
graph["peggy"] = []
def is_seller(name):
return name[-1] ==... |
numbers = ((1, 7), (2, 0), (4, 5))
plus = []
minus = []
devide = []
cubic = []
for x in range(len(numbers)):
plus.append(list(numbers[x]))
minus.append(list(numbers[x]))
devide.append(list(numbers[x]))
cubic.append(list(numbers[x]))
for y in range(len(numbers[x])):
plus[x][y] += 2
m... |
squares = [x**2 for x in range(10) ]
print("squares are: " + str(squares)) |
x = ["kiatu", "shuka", "kitabu", "kitanda"]
indx = [i for i, k in enumerate(x) if k == "kitabu" ]
print("index: " + str(indx[0])) |
n=int(input())
sum=0
if n>0:
for i in range (1,n+1):
sum=sum+i
print ('the sum is',sum)
|
class Clase():
def __init__(self, atributo=0):
self.atributo = atributo
def get_atributo(self):
return self.atributo
def set_atributo(self, value):
self.atributo = value
if __name__ == "__main__":
objeto1 = Clase(1)
objeto2 = Clase(2)
... |
d = int(input())
Dictionary = []
Text = []
result = []
for i in range(d):
Dictionary.append(input().lower())
l = int(input())
for k in range(l):
List = [i for i in input().lower().split()]
Text.extend(List)
for i in range(len(Text)):
if Text[i] not in Dictionary and Text[i] not in result:
re... |
i=1
while i<=4:
b=1
while b<7:
print(" ",end="")
b=b+2
k=1
while k<=4:
print("*", end="")
k=k+2
print()
i=i+1
|
friends = ["mochi", "bori", "ally", "brandon", "max"]
print(friends[1:])
print(friends[1:3])
friends[1] = "fox"
print(friends[1])
|
name = input("Enter your name: ")
print("Hellow " + name + "!")
age = input("Enter your age: ")
print("you are " + age + " years old") |
"""
Created on Sun Sep 6 08:08:51 2015
@author: WangS
"""
from __future__ import unicode_literals
import os
os.chdir("/Users/genius/Desktop/LOOK/PulsarResult_WS")
f = open("findReapetResults.txt","w")
checkList=[]
mayRepeat = open('mayRepeat.txt', 'r')
i = 0
for line in mayRepeat.readlines()... |
from sympy import Matrix
dim_v=3
a=Matrix([[1,-1,0],[2,0,1],[1,1,1]])
r=a.rank()
b=a.rref()
print(f'Range Space of A is Spanned by First {r} Rows of:\n',b[0])
a_nullspace=a.transpose().nullspace()
print('Nullspace of A is Generated by the Columns of:',a_nullspace)
lhs= r+len(a_nullspace)
rhs=dim_v
print('Rank of A: ',r... |
class Marsrover:
def __init__(self, xcoor, ycoor, facing):
self.x = xcoor
self.y = ycoor
self.facing = facing
def return_coordinates(self):
return [self.x, self.y, self.facing]
def movement(self, commands):
for i in commands:
if (i == 'f'):
... |
class ContactList(list):
def search(self, name):
'''return all contacts that contain the search value in their name'''
self.matching_contacts = []
for contact in self:
if name in contact.name:
self.matching_contacts.append(contact)
return self.matching_contacts
class Contact:
all_contacts = Con... |
"""AlertTransport class."""
import abc
import smtplib
class AlertTransportInterface(object):
"""Abstract class definition."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def send(self):
"""Send an alert."""
pass
class AlertTransportMail(AlertTransportInterface):
"""Implem... |
import random
random_num = 5
print("I am thinking of a number between 1 and 10. ")
user_input = int(input("Please guess a number? "))
correct_guess = False
limit_guess = 3
while correct_guess == False:
if user_input == random_num:
print("Yay you won!!!")
ask_to_play = input("Would you lik... |
for number in range(1, 10):
print(number, 'X', number ,'=', number * number) |
"""
---------------------------------
Assignment 3 "Linked list"
Student Name: Michael Reinhart
Student Number: 20001556
Date Modified : March 17 2017
---------------------------------
"""
import urllib.request
def readHtml():
toDoList = None
response = urllib.request.urlopen("http://research.cs.queensu.ca/... |
import pygame
pygame.init()
gameDisplay=pygame.display.set_mode((500,500))
pygame.display.set_caption("my second game")
x=50
y=50
width=40
height=60
vol=5
run=True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys=pygame... |
class Figure:
def __init__(self, color):
self.color=color
def get_color (self):
return self.color
def info (self):
print("Figure")
print("Color:"+self.color)
class Rectangle(Figure):
def __init__(self, color,width=100, height=100):
super().__init__(... |
def selectionSort(list):
for fillslot in range(length-1,0,-1):
GreatestPosition = 0
for location in range(1,fillslot+1):
if list[location]>list[GreatestPosition]:
GreatestPosition = location
temp = list[fillslot]
list[fillslot] = list[GreatestPosition]
li... |
def parse_file_as_array(file, delimiter=None):
with open(file, 'r') as fileHandler:
read_data = [(line) for line in fileHandler.readlines() if is_blank_or_comment(line) == False]
if delimiter is None:
file_array = read_data
else:
file_array = "".join(read_data).split(del... |
print ("hi")
def check_parity(n):
if n % 2 == 0:
return "even"
else:
return "odd"
def test():
if check_parity(0) == "odd":
print("error in function check_parity")
if check_parity(1) == "even":
print("error in function check_parity")
|
file = open("./data/rosalind_revc.txt", "r")
input_str = file.read()
print(input_str)
reverse_str = input_str[::-1]
def getComplement(bp):
switcher = {
"A": "T",
"T": "A",
"C": "G",
"G": "C"
}
return switcher.get(bp, "nothing")
COMP_STR = ''
for x in reverse_str:
if... |
class Property:
def __init__(self) -> None:
self._my_value = None
@property
def my_value(self) -> int:
return self._my_value*5
@my_value.setter
def my_value(self, my_value: int) -> None:
self._my_value = my_value*3
if __name__ == '__main__':
_property ... |
def repeater(value):
while True:
yield value
def repeat_three_times(value):
yield value
yield value
yield value
if __name__ == '__main__':
obj = repeater('hey')
print(obj.__next__())
print(next(obj))
for x in repeat_three_times('hou'):
print(x) |
class MyClass:
def method(self):
return 'instance method called', self
@classmethod
def class_method(cls):
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
if __name__ == '__main__':
my_class = MyClass()
print... |
from abc import ABCMeta, abstractmethod
class Base(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
@abstractmethod
def bar(self):
pass
class Concrete(Base):
def bar(self):
pass
def foo(self):
pass
if __name__ == '__main__':
concrete = Concret... |
import random
print('Create secret code!')
colours = [ 'R', 'Y', 'G', 'B', 'K', 'W' ]
def create_code():
return random.choices(colours, k=4)
def calculate_score(code, guess):
correct = 0
included = 0
indexes = []
for index, element in enumerate(guess):
if code[index] == element:
... |
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Lovely\Desktop\Open_CV\Resources\lena.png', 0)
kernel = np.ones((5, 5), np.uint8)
imgCanny = cv2.Canny(img,150,200)
img_dilation = cv2.dilate(imgCanny, kernel, iterations=1)
img_erosion = cv2.erode(img_dilation, kernel, iterations=1)
cv... |
import turtle
def draw_square():
square_size = 100
turtle.forward(square_size)
turtle.right(90)
turtle.forward(square_size)
turtle.right(90)
turtle.forward(square_size)
turtle.right(90)
turtle.forward(square_size)
def draw_circles():
turtle.back(60)
turtle.left(90)
turtl... |
import gym
import numpy as np
env = gym.make("MountainCar-v0")
env.reset()
print(env.observation_space.high)
print(env.observation_space.low)
print(env.action_space.n)
DISCRETE_OS_SIZE = [20] * len(env.observation_space.high)
discrete_os_win_size = (env.observation_space.high-env.observation_space.low) / DISCRET... |
import csv
budget_csv = 'budget_data.csv'
def print_file(statement, file_pointer) :
print (statement)
file_pointer.write(str(statement) + "\n")
with open('myfile.txt',"w") as f :
with open(budget_csv, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.