text stringlengths 37 1.41M |
|---|
import asyncio
import time
import threading
# @asyncio.coroutine # 会把一个生成器标记为coroutine类型
# def hello():
# print("Hello world! (%s)" % threading.currentThread())
# # 异步调用asyncio.sleep(2):
# yield from asyncio.sleep(2)
# print("Hello again! (%s)" % threading.currentThread())
# 请注意,async和await是针对coro... |
from tkinter import *
import sys
root = Tk()
label_1 = Label(root, text="Values:")
input = Entry(root)
addition = Button(root, text=" Add ")
subtract = Button(root, text="Subtract")
multiply = Button(root, text="Multiply")
division = Button(root, text="Divide")
equal = Button(root, text=" = ")
output ... |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array,... |
from Tkinter import *
window = Tk()
ps2_canvas = Canvas(window, width=500, height=500)
ps2_canvas.grid(row=0, column=0)
# These next four statements are the ones you should play with for your
# program. LEAVE EVERYTHING ELSE (apart from the comments) ALONE
# draw the face
ps2_canvas.create_oval(100, 100, 400, 40... |
#Problem Set 5, Part II
#Kim, Matthew
# you might want to use one of the functions you defined in the previous part
# of this pset. This is why we're importing that file here. If you want to use
# the list_sort function in the other file, you should use the dot notation,
# i.e., listops.list_sort(....) Make sure thi... |
#Problem Set 1
#Kim, Matthew
#Collaborators:Jeremy Lim
#Part I
import math
def golden_ratio():
g_ratio = (1 + math.sqrt(5))/2
return g_ratio
print golden_ratio ()
#Part II
def is_even (input_int):
lol = int(input_int) % 2
return lol == 0
print is_even(20)
print is_even(3)
#Part III
import math
def ... |
class Line(object):
def __init__(self,p1, p2):
p1 = Point(p1)
p2 = Point(p2)
def getp1(self):
return self.p1
def getp2(self):
return self.p2
def setp1(self,p1):
self.p1 = p1
def setp2(self,p2):
self.p2 = p2
def __str__(self)... |
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input())
tip = meal_cost * (tip_percent / 100)
tax = meal_cost * (tax_percent / 100)
total_cost = int(round(meal_cost + tip + tax))
print(total_cost)
|
import onetimepad
from tkinter import *
root = Tk()
root.title("Chryptography App")
def encryptMessage():
a = var.get()
ct = onetimepad.encrypt(a,"saikumar")
print("Working",ct)
e2.delete(0,END)
e2.insert(END,ct)
def dycrptMessage():
a = var2.get()
ct = onetimepad.decrypt(a,"... |
# Contains basic utility functions.
class Utility:
def __init__(self):
pass
@staticmethod
def str_to_list_converter(str_val=''):
# Converting string to list
# Input : 'a,b,c' or '[a,b,c]' or '1,2,3' or '[1,2,3]'
# Output : ['a','b','c'] or [1,2,3]
if str_val[0] is ... |
from arrays import *
arr1 = array("i",[1,2,5,4,3])
def searchelement(array,value):
for i in array:
if i == value:
return array.index(value)
return "The element does not exist"
searchelement(arr1,5)
|
from arrays import *
arr1 = array("i",[1,2,3,4,5,6,7,8])
print(arr1)
def tranversearray(array):
for i in array:
print(i)
traversearray(arr1)
def accessElement(array,index):
if index >= len(array):
print("There is not any element in this index")
else:
print(array[index])
accessElem... |
# student1 = "Tarkek"
# student2 = "Chris"
# student3 = "Michael"
# def Students():
# print(f"{student1} {student2} {student3}")
# Students()
# student1 = "Glen"
# Students()
# class Students:
# def PrintStudents():
# print("Tarek Chris Michael")
#Students.PrintStudents()
# class Students:
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
if len(sys.argv) < 1:
exit()
#def line_split_by_label_vecgtor(line):
def line_split(line):
sents_split = line.strip().split(" ") #['ラベル', 'a:x', 'b:y', ...]
label = sents_split[0] #ラベル
#print(label)
sentence = sents_split[1:] #ラベル以外... |
# to check if the selected path valid path (not 0 (wall), and the path hasn't been travelled yet)
def isValidPath(maze, row, col, solutions):
if (maze[row][col] != 0) and \
((row >= 0 and row < len(maze)) and (col >= 0 and col < len(maze[0])) ) and \
solutions[row][col] == 0:
re... |
'''
Created on Oct 2, 2017
@author: jwang151@stevens.edu
Pledge: I pledge my honor that I have abided by the Stevens Honor System
'''
def helper(l):
if l == [] or l[1:] == []:
return []
return [l[0]+l[1]] + helper(l[1:])
def pascal_row(n):
'''The pascal row function takes a singl... |
# Two Sum
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sort_nums = sorted(nums)
l = 0
r = len(sort_nums)-1
while r > l:
summ = sort_nums[l] + sort_nums[r]
if summ > target:
r -... |
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
sort_nums = sorted(nums)
l = 0
r = len(sort_nums)-1
while r > l:
summ = sort_nums[l] + sort_nums[r]
if summ > target:
r -= 1
... |
'''
REINFORCE Monte Carlo Policy Gradient AI Player
Author: Lei Mao
Date: 5/2/2017
Introduction:
The REINFORCE_AI used REINFORCE, one of the Monte Carlo Policy Gradient methods, to optimize the AI actions in certain environment. It is extremely complicated to implement the loss function of REINFORCE in Keras. Tensorfl... |
def is_triangle(func):
"""Tests, if given 3 sides, they make up a triangle.
For a shape to be a triangle at all, all sides have to be of length > 0,
and the sum of the lengths of any two sides must be greater than or equal
to the length of the third side.
Input: list with 3 integers
... |
def prime_factors(natural_number):
"""Prime factorisation of an integer
"""
prime_factors = []
i = 2
while natural_number > 1:
if natural_number % i == 0: # check if i is a factor
if is_prime_number(i): # if i is a factor, check if i is a prime
... |
#!/usr/bin/env python
"""
Ask for a string and print the lenght of that string.
"""
#import
__author__ = "Stijn Janssen"
__email__ = "stijn.janssen@student.kdg.be"
__status__ = "Development"
def main():
#Ask for a word
word = input("Give me a word.\n")
#Give the lenght of the word
print(len(word))
... |
#!/usr/bin/env python3
"""
each layer should be given the name layer
"""
import tensorflow as tf
def create_layer(prev, n, activation):
"""
prev: is the tensor output of the previous layer
n: is the number of nodes in the layer to create
activation: is the activation function that the layer should use... |
def cal_room(people):
room6=0
room4=0
room2=0
total_price=10000
for room6_num in range(0,6):
for room4_num in range(0,8):
for room2_num in range(0,14):
if((room6_num*6+room4_num*4+room2_num*2)>=people):
num=room6_num*120+room4_num*10... |
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("I am", self.name, " And"," I am", self.age )
class Student_Sport(Student):
def sport(self):
print(self.name," likes Swimming !!!")
maidou = Student("Maidou"... |
def isprime(y):
isprime=True
#print(y)
if y == 0:
return False
if y == 1:
return True
for a in range(2,y):
if y%a==0:
isprime=False
break
return isprime
#x=int(input("input a number"))
y=int(input("input a number"))
for a in range(y):
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def remainder() :
evenList = [x for x in range(1, 21) if x % 2 == 0 ]
return evenList
def oddNumber() :
oddList = [ x for x in range(1, 21) if x % 2 != 0]
return oddList
def divisible(num1 , num2) :
if isNumber(num1) and isNumber(num2):
return num1 % num2 =... |
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который результат спортсмена составит не менее b километров.
# Программа должна принимать значения парамет... |
# Реализовать программу работы с органическими клетками, состоящими из ячеек.
# Необходимо создать класс Клетка. В его конструкторе инициализировать параметр,
# соответствующий количеству ячеек клетки (целое число). В классе должны быть реализованы методы перегрузки арифметических операторов:
# сложение (__add__()), вы... |
# 2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
person_time = int(input('Введите время в секундах: '))
hours = person_time // 3600
minutes = person_time // 60 - hours * 60
seconds = person_time - 3600 * hours - 6... |
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чис... |
def isBalanced(mystring):
result = mystring.count("(") == mystring.count(")")
print(result)
return(result)
isBalanced("a(bcd)d")
isBalanced("(kjds(hfkj)sdhf")
isBalanced("(sfdsf)(fsfsf")
isBalanced("{[]}()")
isBalanced("{[}]")
with open("input.txt", 'r') as f:
inputArray = []
for line in f:
... |
import unittest
from .game import Game
class TestGameResults(unittest.TestCase):
def testResults(self):
data = [[2, 13, 8, 'RYGPBRYGBRPOP', 'R,B,GG,Y,P,B,P,RR', 'Player 1 won after 7 cards.'],
[2, 6, 5, 'RYGRYB', 'R,YY,G,G,B', 'Player 2 won after 4 cards.'],
[3, 9, 6, 'QQQ... |
class Language:
en="english"
ua="українська"
ru="русский"
de="deutsche"
class Human:
def __init__(self, name, age, language):
self.name = name
self.age = age
self.language = language
def __str__(self):
return "Name: {:>10}, age:{:3}, language:{}".format(self.nam... |
def text_year(old):
# для чисел, которые заканчиваются на 11,12,13,14 - пишется "лет"
year = old%10
dyear = old%100//10
if year in [2,3,4] and dyear != 1:
return "года"
elif year == 1 and dyear !=1:
return "год"
else:
return "лет"
def human(name, sex):
def how_old():... |
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print list(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print max(l) # 9
print min(l) # 0
# index(l) # NameError: name 'index' is not defined
# count(l) # NameError: name 'count' is not defined
print len(l) # 10
print sorted(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove(l) # NameError: ... |
#https://leetcode.com/problems/find-numbers-with-even-number-of-digits/
class Solution(object):
def findNumbers(self, nums):
even = 0
for i, num in enumerate(nums):
if len(str(nums[i]))%2 == 0:
even += 1
else:
even += 0
return even |
'efficiently compute median of a set of numbers given one by one'
from __future__ import division
from heapq import heappush, heappop
import unittest
class RunningMedian:
def __init__(self):
self.left_max_heap = []
self.right_min_heap = []
def insert(self, item):
left_len = len(self.l... |
'write a program to print pre-order binary tree traversal non-recursively'
from binary_tree import BinaryTree, get_toy_binary_tree2
import unittest
def pre_order_non_recur(n):
if n == None:
return []
result = []
util_stack = [n]
while len(util_stack) != 0:
top = util_stack.pop()
... |
'compute the k closest stars to earth. Assume earth is a (0, 0, 0)'
import unittest
from heapq import heappush, heappushpop, heappop
def get_k_closest(lst, k = 3):
h = []
for p in lst:
dist = p[0] ** 2 + p[1] ** 2 + p[2] ** 2
if len(h) < k:
heappush(h, (-dist, p))
else:
... |
'''Write a program which takes as input an integer and a binary tree with
integer weights, and checks if there exists a leaf whose path weight
equals the given integer.
path-weight: pw of a node is the sum of the integers on the unique path from the
root to that node
'''
|
"find the i'th order statistic in an array A"
from random import randint
def randomized_partition(A, start_ind, end_ind):
'partition array A randomly by choosing a random pivot'
piv_ind = randint(start_ind, end_ind)
A[start_ind], A[piv_ind] = A[piv_ind], A[start_ind]
i = start_ind + 1
pivot = A[st... |
'''We are given items 1, 2, 3, 4, 5...
with integral weights w1, w2, w3, w4, w5...
and values of items v1, v2, v3, v4, v5...
W -> maximum weight the knapsack can carry
We would like to find what is the maximum value and what items to pack if
Case 1) There is only 1 count of each item (art gallery)
Case 2) Th... |
#!/usr/bin/env python3
'tests for binary_tree.py'
from binary_tree import BinaryTree, BinarySearchTree,\
get_toy_binary_tree, get_empty_tree, get_toy_binary_search_tree, \
BinaryTreeWithPrarent
import unittest
class TestBinaryTree(unittest.TestCase):
def setUp(self):
self.tr = get_toy_b... |
'tests for quicksort implementation'
from quicksort_impl import quicksort, partition
from random import randint
import unittest
class Test_Quicksort_impl(unittest.TestCase):
def test_partition(self):
lst1 = [2, 5, 4, 7, 3, 1, 6]
self.assertEqual(5, partition(lst1, 0, len(lst1) - 1))
expec... |
'search a sorted array for the first occurence of k'
import unittest
def get_first_occur(lst, k):
l = 0
u = len(lst) - 1
while l <= u:
m = l + (u - l) // 2
if lst[m] == k:
if m == 0:
return 0
if lst[m - 1] == k:
u = m - 1
... |
n = int(input())
for i in range(n):
A, B = map(int, input().split())
if B == 0:
print("divisao impossivel")
else:
print("{:.1f}".format(A/B))
|
entradas = input()
A, B, C = entradas.split(" ")
A = float(A)
B = float(B)
C = float(C)
print("TRIANGULO: {:.3f}".format((A*C)/2))
print("CIRCULO: {:.3f}".format(3.14159*C**2))
print("TRAPEZIO: {:.3f}".format((A+B)*(C/2)))
print("QUADRADO: {:.3f}".format(B*B))
print("RETANGULO: {:.3f}".format(A*B))
|
n = int(input())
for num in range(1, n + 1):
print(num, num ** 2, num ** 3)
print(num, num ** 2 + 1, num ** 3 + 1) |
import random
number=random.randint(1,100)
guess=0
count=0
while guess!=number and guess!="exit":
guess=int(input("whts your guess man?\n"))
if guess=="exit":
break
guess=int(guess)
count+=1
if guess<number:
print("too low!")
elif guess>number:
print("too high!")
... |
# The in and not in operators
a = "Welcome"
if 'come' in a:
print('Inside')
if 'busy' not in a:
print('not in') |
class Rectangle:
def __init__(self, height = 1, width = 2):
self.height = height
self.width = width
def getArea(self):
return self.height* self.width
def getPerimeter(self):
return self.height * self.width*2
a = Rectangle(int(input('enter the height here: ')), int(input('enter the width here: ')))... |
#Creating a prime number
my_list= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for num in (my_list):
if num>1:
for i in range (2, num):
if num%i== 0:
print(num, ' not a prime')
break
else:
print(num, 'is a prime number') |
'''
This script allows you to INPUT countries of interest, data of interest, starting date and
an integer smoothing parameter in order to plot the time series for the given type of data
and country set using matplotlib module and parsing the information provided in the dataset
collected by "Our World in Data" organizat... |
# Ask the user to enter their name
x = raw_input("What's your name? \n")
# Print hello + their name
print("Hello, " + x)
|
# Uses python3
# Given two integers a and b, find their greatest common divisor.
# Input.The two integers a,b are given in the same line separated by space.
# Constraints. 1 ≤ a,b ≤ 2·109.
# Output Format. Output GCD(a,b).
import sys
def gcd(a, b):
if a % b == 0:
return b
else:
return gcd(b,... |
#comment one
def do_nothing(c):
if c > 0:
do_nothing(c - 1)
def main():
# comment two
frmt = """#comment one
def do_nothing(c):
if c > 0:
do_nothing(c - 1)
def main():
# comment two
frmt = %c%c%c%s%c%c%c
print frmt %% (34,34,34,frmt,34,34,34,34,34)
if __name__ == %c__main_... |
file = open('text.txt', 'r')
read = file.read()
# – прочитать входной файл, считать все символы;
print('все символы: ' + read)
list1 = list()
for i in read:
if i.isdigit():
list1 += i
print('цифры в файле, с сохранением порядка: ' + str(list1)) # – вывести те символы из файла, которые обозначают цифры от ... |
"""
Do not change the input and output format.
If our script cannot run your code or the format is improper, your code will not be graded.
The only functions you need to implement in this template is linear_regression_noreg, linear_regression_invertible,regularized_linear_regression,
tune_lambda, test_error and mappin... |
# -*- coding=utf-8 -*-
import urlparse
def reverseUrl(url):
"""
examples:
http://bar.foo.com:8983/to/index.html?a=b
com.foo.bar:http:8983/to/index.html?a=b
https://www.google.com.hk:8080/home/search;12432?newwi.1.9.serpuc#1234
hk.com.google.www:https:8080/home/search;12432?newwi.1.9.se... |
"""
- 9/28/2016
"""
from random import randrange
from typing import List
def bsort(array: List[int]):
modified = False
size = len(array) - 1
for i in range(size):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
modified = True
i += 1
i... |
"""
Mike McMahon
"""
from typing import List
class LinkedList(object):
class Node(object):
def __init__(self, data: any = None, next_node=None):
self._data = data
self._next = next_node
def get_next(self):
return self._next
def set_next(self, next_no... |
#!/usr/bin/env python
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# Calculate the length of the line
vlen = len(line)
# TODO: Students to output <lineLength, 1>
print('%s\t%s' %... |
# import os, csv, datetime and openpyxl libraries
import os
import csv
from datetime import datetime
from openpyxl import Workbook
folder = './data'
# function to scan folder for xlsx and csv files
def scan_folder(folder):
print(os.getcwd())
files = os.listdir(folder)
xlsx_files = []
csv_files = []
... |
''' Ask the user what their Favorite ganmeis and
say that you also like to play that game'''
game = input('what is your Favourite game?\n')
print("i like to paly",game,"too") |
class Parser:
def __init__(self, grammar, word):
self.grammar = grammar
self.alpha = word + '$'
self.pif = self.readPIF("PIF.txt")
self.st = self.readFile("ST.txt")
self.codificationTable = self.readCodificationTable()
def parseSequence(self):
beta = self.grammar... |
#Description: Build a movie recommendation engine (more specifically a content based recommendation engine)
#Import Libraries
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
#Load the data
from google.colab impor... |
#Created by: Justin Bronson
#Created on: Sept, 2017.
#Created for: ICS3U
#This program calculates the height of an
# object in mid air using the gravity formula
import ui
def calculate_button_touch_up_inside(sender):
#calculate circumference
#constant
GRAVITY = 9.8
#input
seconds = int(v... |
#!/usr/bin/env python3
import os, glob
def main():
rootDir = input('Enter parent directory to run script: ') + '/'
keywords = input('Enter words in filename to be replaced (multiple words separated by space): ').split(" ")
replaceInFileName = input('Enter string to take its place (Enter to remove keywo... |
from tkinter import *
from functools import partial
from NewWordPage import NewWordPage
class Startpage:
#-------------------------------#
#----------CONSTRUCTOR----------#
#-------------------------------#
def __init__(self, window):
Button(window, text="Add a new word",
command=lambda: self.s... |
# We maintain a stack of active rectangles.
# One could store them as pairs (start, height)
# Here an optimization is to store rightmost locations of bottleneck heights.
# Then both start and height are encoded in same queue:
# the height is just heights[bottleneck location],
# and the start of the rectangle is just af... |
# Reading an excel file using Python
import xlrd
import pandas as pd
import sys
class ExcelFileParser:
def parseFile(self, inputFilePath, outPutFilePath):
csv = pd.read_csv(inputFilePath, error_bad_lines=False)
csv = csv.rename(columns={'Team 1': 'home_team'})
csv = csv.rename(columns={'Te... |
entrada = input ("Entre com um valor: ")
print "Voce entrou com o valor: " + str (entrada)
|
def prime(n):
prime = True
for el in range(2, n//2):
if n % el == 0:
prime = False
break
return prime
number = int(input())
for i in range(2, number//2+1):
if prime(i) and prime(number - i):
print(i, number-i)
break
|
from typing import Sequence
import warnings
import matplotlib.pyplot as plt
import numpy as np
__all__ = [
'calculate_enrichment_factor',
'convert_label_to_zero_or_one',
'plot_predictiveness_curve',
]
def _normalize(arr):
return (arr - arr.min()) / (arr.max() - arr.min())
def _set_axes(ax, lim, fo... |
# remove() method - If the item to remove does not exist, it will throw an error
set1 = {"apple", "banana", "cherry"}
set1.remove("banana")
print(set1)
# discard() method - If the item to remove does not exist, it will not throw an error
set2 = {"apple", "banana", "cherry"}
set2.discard("banana")
print(set2)
# pop() ... |
# Note: Both union() and update() will exclude any duplicate items.
# union() method - used to join items from two sets and returns a new set
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
# update() method - inserts all the items from one set into another
setA = {"a", "b" , "c"}
setB = {... |
# if - else
a = 90
if (a < 10):
print ("a is less than 10")
else:
print ("a is greater than 10")
# if - elif - else
a = 50
if (a == 10):
print(a)
elif ( a == 50):
print(a)
else:
print ("a is undefined")
# Nested if
a = 35
if (a != 0):
if(a < 40):
print("a is less than 40")
else:
... |
# For loop
tuple4 = ("summer", "winter", "spring")
for x in tuple4:
print (x)
# Loop Through the Index Numbers - loop through the tuple items by referring to their index number.
# Use the range() and len() functions to create a suitable iterable.
tuple4 = ("summer", "winter", "spring")
for x in range(len(tuple4)... |
choice = raw_input('rock(r), paper(p),scissors(s), lizard(l), or spock(sp)? ')
from random import randint
com_choice = randint(1,5)
if com_choice == 1:
computer = 'r'
elif com_choice == 2:
computer = 'p'
elif com_choice == 3:
computer = 's'
elif com_choice == 4:
computer = 'l'
elif com_choice == 5:
c... |
#prueba para método resta
def resta(num1, num2):
return num1 - num2
resultado_1 = resta(num1 = 60, num2 = 30)
resultado_2 = resta(num1 = 0, num2 = 0)
resultado_3 = resta(num1 = 1000, num2 = 4000)
print(f'El resultado de la resta 1 es: {resultado_1}')
print(f'El resultado de la resta 2 es: {resultado_2}')
print... |
print('0~100までの得点(整数値)を2つ入力して下さい')
n1=int(input('1つ目の得点:'))
n2=int(input('2つ目の得点:'))
if n1>=80 and n2>=80:
print('合格です')
elif n1>=80 or n2>=80:
print('補欠合格です')
else:
print('不合格です') |
n=int(input('0~100までの得点(整数値)を入力して下さい'))
if n>=80:
print('合格です')
n=int(input('0~100までの得点(整数値)を入力して下さい'))
if n>=60:
print('合格です')
else:
print('不合格です') |
x=int(input('0~100までの国語の得点(整数値)を入力して下さい'))
if x>80:
y=int(input('0~100までの英語の得点(整数値)を入力して下さい'))
if y>=80:
print('合格です')
else :
print('不合格です')
else:
z=int(input('0~100までの数学の得点(整数値)を入力して下さい'))
if z>=80:
print('合格です')
else:
print('不合格です') |
n=int(input('0~100までの得点(整数値)を入力して下さい'))
if n<0 or n>100 :
print('入力値が不正です')
else :
print('正しい入力値です') |
a=0
b=100
while a<b:
a+=1
if a%3==0:
continue
print(a)
|
def write(dic):
for i,c in dic.items():
print(i,":",c)
dic={"赤":"red",
"白":"white",
"黒":"black",
"青":"blue",
"緑":"green"}
write(dic) |
# -------------------
# Background Information
#
# In this problem, you will build a planner that helps a robot
# find the shortest way in a warehouse filled with boxes
# that he has to pick up and deliver to a drop zone.
#For example:
#
#warehouse = [[ 1, 2, 3],
# [ 0, 0, 0],
# [ 0, 0... |
def words(param):
result = {}
# Deal with multiple spaces
proper_sentence = ' '.join(param.split())
# Create a list containing word items
proper_words = proper_sentence.split(" ")
for my_word in proper_words:
if my_word in result:
continue
try:
result[in... |
import Board
import AIplayer
class TicTacToe():
def __init__(self, initial_turn=True):
self.board = Board.Board()
self.board.reset
self.initial_turn = initial_turn
self.player_mark, self.ai_mark = None, None
self.ai = None
def setAI(self, mode, my_mark, opponent_mark):
... |
while True:
print(" ************MENU************ ")
print("1.Pixel 1")
print("2.Pixel 2")
print("3.Pixel 3")
print("4.Salir")
op=int((input("INGRESE LA OPCION QUE DESEA EJECUTAR:")))
if op==1:
print("1.Completa")
print("2.En partes")
op1 = input... |
"""
Interpreting Chi^2
Author: Sheila Kannappan
excerpted/adapted from CAP REU tutorial September 2016
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import numpy.random as npr
# experiment to illustrate Monte Carlo creation of chi^2
# distributions for two values of... |
import pygame
import math
amigo = []
# menuLetras
q = 0
q == int(1)
# cores
rosa = (255, 228, 196)
azul = (0, 0, 255)
verde = (34, 139, 34)
preto = (0, 0, 0)
branco = (255, 255, 255)
vermelho = (255, 0, 0)
ouro = (218, 165, 32)
magenta = (255, 0, 255)
PI = math.pi
pygame.init()
largura = 640
altura = 480
pos_x = in... |
import pandas as pd
def calcfreq(mylist):
freq={}
for i,items in enumerate(mylist):
freq[(i,items)]=mylist.count(items)
for key,value in freq.items():
print(key,":",value)
return freq
doc1="Cosine similarity is a metric, helpful in determining, how similar the data objects are irres... |
"""
容器序列:list、tuple、collections.deque
扁平序列:str、bytes、bytearray、memoryview、array.array
容器序列和扁平序列的区别?
容器序列可以存放不同类型的数据。即可以存放任意类型对象的引用。
扁平序列只能容纳一种类型。也就是说其存放的是值而不是引用。换句话说扁平序列其实是一段连续的内存空间,由此可见扁平序列其实更加紧凑。但是它里面只能存放诸如字符、字节和数值这种基础类型。
可变序列:列表,字典
不可变序列:元组,字符串
"""
def my_map(func,iterables):
if hasattr(iterables,'__iter_... |
# => SELECTION SORT ALGORITHM FILE
def selection_sort(elements, change):
for i in range(len(elements)):
min_index = i
for j in range(i + 1, len(elements)):
if elements[min_index].size_Y > elements[j].size_Y: min_index = j
elements[i], elements[min_index] = element... |
class CoffeeMachine:
def __init__(self, water_: int, milk_: int, coffee_beans_: int, disposable_cups_: int, money_: int, exit_: bool):
self.water = water_
self.milk = milk_
self.coffee_beans = coffee_beans_
self.disposable_cups = disposable_cups_
self.money = money_
... |
age = int(input('What is your age?\n'))
if age < 18:
print('You are still a child!')
else:
print('You are an adult now!')
|
print('Let\'s play a game! Try to guess my number...')
try:
guess = int(input('Enter a number between 0 and 100: '))
except NumberFormatException:
print('Uh oh, that\'s not a number.')
if not (guess <= 100 and guess >= 0):
print('Hey! You\'re cheating! The number must be between 0 and 100.')
elif guess < 7... |
for i in range(34):
if i % 2 = 0:
print(i)
else if i % 3 = 3:
print(i % 3)
else
print(3)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.