text stringlengths 37 1.41M |
|---|
dic = {}
n = int(input())
for i in range(n):
palavra, adjetivo = input().split()
dic[palavra] = adjetivo
frase = input().split()
for palavra in frase:
if palavra in dic:
print(dic[palavra])
#https://pt.stackoverflow.com/q/346650/101
|
def funcao():
return int(input('insira um número:'))
tupla = (funcao(), funcao(), funcao(), funcao())
print(tupla.count(9))
print(tupla)
#https://pt.stackoverflow.com/q/339514/101
|
frase = input("Escreva uma frase: ")
frase = frase.upper().replace(' ','')
print("\n", frase)
#https://pt.stackoverflow.com/q/340130/101
|
entrada = input("A B C").split()
A, B, C = int(entrada[0]), int(entrada[1]), int(entrada[2])
if A >= 1 and A <= 300 and B >= 1 and B <= 300 and C >= 1 and C <= 300:
pass
else:
raise ValueError("Deu Erro")
entrada = input("Qual a altura e largura").split()
H, L = int(entrada[0]), int(entrada[1])
if H >= 1 and H ... |
import collections
numeros = [5, 3, 1, 2, 3, 4, 5, 5, 5]
repetidos = collections.Counter(numeros)
print(repetidos[5])
#https://pt.stackoverflow.com/q/176255/101
|
i = 1 #inicializador
while i < 10: #verifica a condição
print(i) #o corpo, a ação
i += 2 #o passo de "incremento"
i = 10 #inicializador
while i > 0: #verifica a condição
print(i) #o corpo, a ação
i -= 1 #o passo de "incremento"
for i in range(1, 10, 2):
print(i)
for i in range(10, 1, -1):
pri... |
for x in range(11): if x % 2 == 0: print(x)
[print(x) for x in range(11) if x % 2 == 0]
#https://pt.stackoverflow.com/q/463390/101
|
from random import choice
minusculas = "abcdefgh"
maiusculas = "ABCDEFGH"
senha = []
pos = 0
while pos < 8:
senha.append(choice(maiusculas))
senha.append(choice(minusculas))
pos += 1
print(''.join(senha))
#https://pt.stackoverflow.com/q/461052/101
|
#secret number game where user guesses between 1 and 10
import random #imports random module for random number generation
secret_num = random.randint(1,10) #generates random in in range 1-10
guess = input("I'm thinking of a number between 1 and 10. Guess!!! " ) #asks user for input
guess_num = 5 #This is the number o... |
# Write a function f(x) that returns the sin of x. Hint: there is a sin function in the math module. Plot it from -5 to 5 in increments of 1
from matplotlib import pyplot
import math
def f(x):
return math.sin(x)
def run():
xs = list(range(-5, 6))
ys = []
for x in xs:
ys.append(f(x))
pypl... |
#Various exercies with Python loops
# print numbers between 1 and 10
for number in range (1, 10):
print(number)
#same as above with prompt of start and end
startfrom = input('Start from: ')
endon = input('End on: ')
x = int(startfrom)
y = int(endon)
for number in range (x,y):
print(number)
#print each odd nu... |
#promt user for file name, read file and print to screen
file_read = open(input('name of file?'), 'r')
contents = file_read.read()
file_read.close()
print(contents)
|
#Nested dictionary exercices
ramit = {
'name': 'Ramit',
'email': 'ramit@gmail.com',
'interests': ['movies', 'tennis'],
'friends': [
{
'name': 'Jasmine',
'email': 'jasmine@yahoo.com',
'interests': ['photography', 'tennis']
},
{
'name': 'Jan',
'email': 'jan@hotmail.com',... |
# import the pygame module, and the
# sys module for exiting the window we create
import pygame, sys
# import some useful constants
from pygame.locals import *
DIRT = 0
GRASS = 1
WATER = 2
COAL = 3
# color
BLACK = (0, 0, 0)
BROWN = (153, 76, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# useful game dimentions
TILE_SI... |
number = 0
while number < 5:
print(number)
number = number + 1
print('Ended!')
|
my_list = [1, 2, 3, 11, 14, 18, 23, 28, 29]
number_less_than_0 = my_list[0:3]
number_less_than_20 = my_list[3: 6]
number_less_than_30 = my_list[6:]
print(number_less_than_0)
print(number_less_than_20)
print(number_less_than_30)
|
name = 'Luiz Otavio'
age = 32
height = 1.80
is_greater_than_18 = age > 18
weight = 80
bmi = weight / height ** 2
print(name, 'is', age, 'years old and his BMI is', bmi, sep=' ')
print(f'{name} is {age} years old and his BMI is {bmi:.2f}')
print('{} is {} years old and his BMI is {:.2f}'.format(name, age, bmi))
print('... |
from functools import reduce
from data import products, people, numbers
sum_of_numbers = reduce(lambda accumulator, item: accumulator + item, numbers, 0)
print(sum_of_numbers)
average_of_numbers = reduce(lambda accumulator, item: accumulator + item, numbers, 0) / len(numbers)
print(average_of_numbers)
sum_of_prices ... |
my_dictionary = dict(
first_key='First value',
second_key='Second value'
)
my_dictionary['third_key'] = 'Third value'
print(my_dictionary)
print(my_dictionary['first_key'])
print(my_dictionary['second_key'])
print(my_dictionary['third_key'])
|
from data import people
names = map(lambda person: person['name'], people)
print(list(names))
ages = map(lambda person: person['age'], people)
print(list(ages))
|
first_set = {1, 2, 3, 4, 8}
second_set = {3, 4, 5, 6, 7}
third_set = first_set - second_set
print(third_set)
third_set = first_set.difference(second_set)
print(third_set)
|
from abc import ABC, abstractmethod
class Account(ABC):
def __init__(self, agency, account_number, balance):
self._agency = agency
self._account_number = account_number
self._balance = balance
@property
def agency(self):
return self._agency
@property
def account_number(self):
return s... |
class Bank:
def __init__(self):
self.agencies = [1111, 2222, 3333]
self.customers = []
self.accounts = []
def insert_customer(self, customer):
self.customers.append(customer)
def insert_account(self, account):
self.accounts.append(account)
def authenticate(self, customer):
if custom... |
questions = {
'First Question': {
'question': 'How much is 2 + 2?',
'answers': { 'a': '1', 'b': '4', 'c': '5' },
'correct_answer': 'b'
},
'Second question': {
'question': 'How much is 3 * 2?',
'answers': { 'a': '4', 'b': '10', 'c': '6' },
'correct_answer': 'c'
}
}
correct_answers = 0
f... |
text = 'Python'
for index, letter in enumerate(text):
print(f'{index} = {letter}')
|
from data import products
def increase_price(product):
product['price'] = round(product['price'] * 1.05, 2)
return product
new_products = map(increase_price, products)
for product in new_products:
print(product)
|
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
try:
file = open(filename, mode)
print('Opening file')
yield file
finally:
print('Closing file')
file.close()
with open_file('object-oriented-programming/context-manager/my_file.txt', 'w') as file:
file.writ... |
import pygame
import random
# Set up how the enemy thinks
class Enemy():
# Enemy constructor function
def __init__(self, x , y, speed, size):
#Make the Enemy's variables
self.x = x
self.y = y
self.pic = pygame.image.load("../assets/mos.png")
self.speed = speed... |
from sklearn import datasets,svm,metrics
import matplotlib.pyplot as plt
digits = datasets.load_digits()
#Task - a 认识数据集
images_and_labels = list(zip(digits.images, digits.target))
# for every element in the list
for index, (image, label) in enumerate(images_and_labels[:8]):
# initialize a subplot of 2X4 ... |
"""
Author: Jake Wachs
User object
12/7/2019
"""
import json
class User:
def __init__(self):
"""
Instantiate User object, default constructor
"""
print('Instantiating new user object')
def setUsername(self, n):
"""
Setter for name
"""
self.user... |
#creating a dictionary for keys and integers and there squares as values.
numbers = {
"1": 1**2,
"2": 2**2,
"3": 3**2,
"4": 4**2,
"5": 5**2,
"6": 6**2,
"7": 7**2,
"8": 8**2,
"9": 9**2,
"10": 10**2,
"11": 11**2,
"12": 12**2,
"13": 13**2,
"14": 14**2,
"15": 15**... |
class Game:
def __init__(self, home, away):
self.home = home
self.away = away
from sportsreference.nfl.boxscore import Boxscores
games_today = Boxscores(9, 2019)
# Prints a dictionary of all matchups for week 1 of 2017
print(games_today.games)
#games_today.game
stef = games_today._boxscores
week = ... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:
Description :
Author : ianchen
date:
-------------------------------------------------
Change Activity:
2017/11/22:
-------------------------------------------------
"""
impor... |
import math
def parseFile(file):
numbers = []
with open(file) as f:
for line in f:
numbers.append(int(line))
return numbers
def findNumbersWithSum(numbers, target_sum, total_numbers, chosen=None):
if chosen is None:
chosen = []
sum_so_far = sum(chosen)
if len(chosen) + 1 == total_numbers:... |
age = int(input("What is your age?: "))
if age <= 1:
print("You are an infant.")
elif 2 < age < 13:
print("You are a child.")
elif 13 <= age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
|
class ListIterator():
def __init__(self, collection = []):
self.collection = collection
self.cursor = 0
def current(self):
if self.cursor < len(self.collection):
return self.collection[self.cursor]
def next(self):
if len(self.collection) >= self.cursor + 1:
... |
# Aufgabe 1
# Vervollständige die Funktion shortest_word(): Ihr sollen mehrere Strings übergeben
# werden (KEINE Liste von Strings!), von denen sie den String mit den wenigsten Zeichen zurückliefert.
def shortest_word(*nameslist):
short_name = nameslist[0]
for name in nameslist:
if len(name) < len(sho... |
"""
Once the data is imported use Pandas to do the following:
- Clean and Scrub the data as required
- Identify the Top 5 customers based on $ spent
- Identify the Top 3 products being sold
- Daily trend of sales per products (data and graph)
- Daily trend of sales per customer (data and graph... |
i=0
while i<7:
print("*"*i)
i=i+1
j=5
while j>0:
print("*"*j)
j=j-1
print() |
#coding=utf-8
#读文件
file=open('D:\\1.txt','r')
#print(file)
for i in file:
print(i)
file.close()
#写文件
str1='一切都是最好的安排'
file=open('D:\\2.txt','w')
file.write(str1)
file.close()
print('执行完毕')
#追加文件
file=open('D:\\2.txt','a')
file.write('\n come on baby!!!')
file.close()
print('追加完毕')
|
#coding=utf-8
#直接访问
li=['heygor','ladeng','o8ma']
print(li)
#遍历访问
for i in li:
print(i)
#成员访问
print('heygor' in li)
print('*****************8888')
li=[1,2,3]
print(li[0])
print(li[-2])
#print(li[5])
print(li[:-1])
print(li[1:])
print(li[1:2])
print('*****************8888')
li=[1,2,3]
li2=[4,5,6]
print(li+li2)
... |
#coding=utf-8
def sum(a,b):
jisuan=a+b
return jisuan
s=sum(20,30)
print(s)
print('----------------------')
def re(a,b):
a*=10
b*=10
return a,b
num=re(3,5)
print(num)
print(type(num))
print('----------------------')
r1,r2=re(3,4)
print(r1,r2)
print(type(r1))
print(type(r2))
|
#coding=utf-8
def test():
n=1
print('first')
yield n
n+=1
print('second')
yield n
n+=1
print('third')
yield n
a=test()
print('next one')
print(next(a))
print('next one')
print(next(a))
print('next one')
print(next(a))
print('next one')
print(next(a))
|
n=int(input("Enter the number"))
sum=0
while(n>0):
reminder=n%10
sum=sum+reminder
n=n//10
print("the sum of digits",sum)
|
n=int(input("Enter a number1:")
m=int(input("Enter a number2:")
c=n-m
if(c%2==0):
print("the difference is even")
else:
print("the difference is odd")
|
numb1=int(input("Enter a number1"))
numb2=int(input("Enter a number2"))
numb3=int(input("Enter a number3"))
if(numb1>numb2)&(numb1>numb3):
print("the number 1 is greatest")
elif(numb2>numb3)&(numb2>numb1):
print("the number 2 is greatest")
else:
print("the number 3 is greatest")
|
str1=input()
if (len(str1%3==0):
m=len(str1)//3
print(str1[:m-1]+'*'+'*'+str1[m+1:])
else:
m=len(str1)//3
print(str1[:m]+'*'+str1[m+1:])
|
import cv2
import numpy as np
'''In order to add
the color functionality'''
Custom_Image_1=np.zeros((500,500,3),np.uint8)
'''
Function for drawing the line
1st=The file which is Custom_Image_1 for our case
2nd= Starting Point
3rd= Ending Point
4th=Color(red for our case)
5th= Thickness
'''
cv2.line(Custom_Image_1,(... |
from GameState import *
from random import randint
from OpponentAI import MinimaxAI
next = False
while not next:
userInput = input("Want to go first? (y/n)\n")
if userInput == "y":
next = True
first = True
if userInput == "n":
next = True
first = False
game_state = State("O... |
def main():
#write your code below this line
longest_name = ''
longest_name_len = 0
sum_of_years = 0
year_count = 0
while True:
line = input()
if line == '':
break
data = line.split(",")
name = data[0]
name_len = len(name)
year = int... |
import read
from dateutil import parser
df = read.load_data()
def hour_parser(date):
parsed_date = parser.parse(date)
return parsed_date.hour
hour_count = df["submission_time"].apply(hour_parser).value_counts()
print(hour_count)
for hour, count in hour_count.items():
print("{0}: {1}".format(hour, count... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 13:57:29 2020
@author: primi
"""
import pandas as pd
import time
df = pd.read_csv('glassdoor_data.csv')
# remove missing values in salary section
df.dropna(subset=['Salary Estimate'], inplace=True) # remove missing values in salary section
# dist... |
#! usr/bin/env python3
input_list = [2, 5, 1, 153, 15, 20, 13, 200, 10]
def div_by_five(num):
if num % 5 == 0:
return True
else:
return False
# Create a generator
div_5_gen = (li for li in input_list if div_by_five(li))
# normal
for li in div_5_gen:
print(li)
# one liner
[print(li) ... |
#! usr/bin/env python3
names = ["John", "Toby", "Rachel", "Sam"]
for name in names:
# Fancy
print(" ".join(["Hey,", name]))
print(", ".join(names))
|
import random
import sys
# This Roll class is subclassing the int class, that way it can be treated like
# an int in almost all cases, but we retain what the roll is so we can print it
# properly
class Roll(int):
def __new__(cls, *args):
values = list(args)
value = reduce(lambda x, y: x + y, values... |
# American Flag
# Aiden Dow
# 9/27/2019 - Revised 12/21/2020
import datetime
import graphics as g
def main():
# Initialize window
win = g.GraphWin("America the Beautiful", 760, 400)
win.setCoords(0, 0, 1.9, 1)
# Draw stripes
stripeWidth = 0.0769
stripeColor = "red"
nextY = 0
for strip... |
# Changing bases
# This program converts a base 10 number into another base specified by the user using a recursive function
# Aiden Dow
# 12/13/2019 - Revised 12/21/2020
import datetime
def baseConvert(num, base):
"""Convert a number into a different base"""
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
... |
# Car vs. Goats
# A guess-the-door game demonstrating the Monty Hall problem
# Aiden Dow
# 11/20/2019 - Revised 12/16/2020
import datetime
from random import randrange
from graphics import GraphWin, Button, Point, Text
from time import sleep
def getDoorPick(win, buttons):
"""Waits for a click in b1, b2, or b3 and ... |
# Write a program, which find all the numbers between 100 and 500
# such that each digit of the number is odd and then print the numbers.
# For example, 111 is the first number between 100 and 500 which all the digits are odd.
# you may want to use for loop, and list to program this task)
num1 = 100
num_list = [... |
from timeit import default_timer as timer
def exec_time(func):
def wrapper(*args):
start = timer()
func(*args)
end = timer()
result = end = start
return result
return wrapper
# да се качи без долното в джъдж
@exec_time
def loop(start, end):
tot... |
""" Mesh module.
"""
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import array
from itertools import islice
import mimpy.mesh.mesh_cython as mesh_cython
import mimpy as mimpy
from six.moves import map
from six.moves import range
from six.moves import zip
def tb(s):
... |
def look_up_word_value(words):
"""
---------------------------------------------------------------------
DESCRIPTION
Translates the word (string) array into a floating-point value array.
---------------------------------------------------------------------
PARAMETERS
words (string array): Th... |
print("--- 아르바이트 급여 계산 프로그램 ---")
print("--- 2021년 최저시급은 8720원입니다 ---")
print("")
mywage = 0
totalwage = 0
basic = int(input("시급을 입력하세요: "))
print("")
print("[시급]")
print("*** 주간근무 :", basic, "원 ***")
print("*** 야간근무 : 주간 시급 * 1.5 ***")
print("")
while True:
select = input("주간근무 or 야간근무를 입력하세요 ... |
#fibonacci numbers
def fibonacci(N):
count = 1
i = 0
j = 1
if N == 0:
return 0
else:
while count != N:
temp = i + j
i = j
j = temp
count += 1
return j
num = 30
print(fibonacci(num)) |
import random
num_rand = random.randint(0,100) # a number between 0 and 99
cont = 6 # chances
adm = True # for while exit
while adm :
resp_user = int(input("Guess a number between 0 to 100 > "))
cont -= 1
if resp_user > num_rand :
print("Your number is higher, Try again :(")
print("You have {} attempts".form... |
from bs4 import BeautifulSoup as bs
import re
html_doc="""
<html>
<head>
<title>
The Dormouse's story
</title>
</head>
<body>
<p class="title">
<b>
The Dormouse's story
</b>
</p>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a class=... |
import random
a = random.randint(1,9)
guess = int(input("请输入一个数值,与改随机数比较:"))
while guess != a:
if guess > a:
print("大了")
elif guess < a:
print("小了")
guess = int(input("猜错了,再给你一次机会:"))
if guess == a:
print("你真厉害,猜对了")
else:
if guess > a:
print("你猜大了")
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
*******
Bad CSV
*******
Convert bad a badly formatted CSV to a good one.
This is using the function of the table file to
convert the CSV in a correct manner.
"""
import six
from csv_tools import table
__author__ = "Daniel Melichar"
__copyright__ = "Copyright 2015"... |
"""
Author: David Thong Nguyen
Date Created: Nov 15th, 2013
Date Modified: Nov 17th, 2013
- tested random damage multiplier [8,9]
- decided multiplier's optimal range: [8,10]
--> Damage is quite balanced
NEXT OBJECTIVES:
+ add evasion system/check accuracy
"""
import random
import math
def ... |
"""Busca binária"""
def binary_search(array, item, begin=0, end=None):
"""
Utiliza do algoritmo de busca binária para encontrar um ítem em uma lista. Partindo do pressuposto que o array esteja ordenado.
:param array: lista em que será feita a busca.
:param item: o ítem que está sendo pesquisado.
:... |
class Solution:
# 迭代
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
cur = root
res = []
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)... |
import informedSearch
import random
import time
# Module Classes
class sixteenPuzzleState:
def __init__(self, numbers):
"""
Constructs a new 16 puzzle from an ordering of numbers.
numbers: a list of integers from 0 to 15 representing an
instance of the eight puzzle. 0 represe... |
"""
⒈ 从第一个元素开始,该元素可以认为已经被排序
⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描
⒊ 如果该元素(已排序)大于新元素,将该元素移到下一位置
⒋ 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
⒌ 将新元素插入到下一位置中
⒍ 重复步骤2~5
"""
# debug rang(i, 0, -1) 改成 range(i, -1, -1)
# 不然只有第一遍历会让第一个和第二值比较
import random
list1 = [1, 3, 5, 6, 2, 4]
Range = 100
Length = 6
list = random.sample(range(Range),Length)
d... |
#!/usr/bin/env python
PEOPLE_COLUMNS = (
("Name", str), ("Age", int), ("Gender", str), ("Height", int))
PEOPLE = (
("John", 52, "male", 175),
("Alice", 34, "female", 184),
("Bob", 31, "male", 156),
("Jane", 38, "female", 164)
)
def compute():
for row in PEOPLE:
yield row
# dataset des... |
'''
As long as you have a URL, the webbrowser module lets users cut out the step of
opening the browser and directing themselves to a website. Other programs could
use this functionality to do the following:
AIM: Open the browser to the URL for your local weather.
'''
####### LIBRARIES WE'RE GOING TO NEED #######
# W... |
from abc import ABCMeta
from abc import abstractmethod
# simple Abastract Base Class demo (Not exactly what I wnat....
# anyway......
class Foo(object):
def oop_trash(self):
return "agreement from Foo"
class LayerMeta(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
... |
def recurrent(*args, **kwargs):
"""Wraps an apply method to allow its iterative application.
This decorator allows you to implement only one step of a recurrent
network and enjoy applying it to sequences for free. The idea behind is
that its most general form information flow of an RNN can be descri... |
memo = {}
def divide(total_len, block_size) :
if total_len < 0 :
yield 0
elif total_len == 0 :
yield 1
else :
if total_len in memo :
yield memo[total_len]
else :
for block in block_size :
if block <= total_len :
#print (total_len, block)
newsize = total_len - block
if block != 1 and ... |
from math import sqrt
from copy import deepcopy
import sys
def getPrimeList(n):
primeList = range(2,n)
if n < 11:
return [2,3,5,7]
k = int(sqrt(n))
sqrtPrimeList = getPrimeList(k)
length = len(primeList)
primeAssist = [True]*length
for i in sqrtPrimeList:
indexList = 2*i-2
while indexList <length:
prime... |
def binarySearch(a, v) :
lo, hi = 0, len(a)-1
if v > a[-1] : return len(a)
elif v < a[0] : return -1
while lo <= hi :
mid = lo + ((hi - lo) >> 1)
if a[mid] > v : hi = mid - 1
elif a[mid] < v : lo = mid + 1
else: return mid
return hi +1
if __name__ == "__main__" :
import string
def testBinarySearch(a, v... |
import psyco
psyco.full()
def reverseString(s) :
return "".join(s[-i-1] for i in range(len(s)))
def isPalindrome(s) :
return all(s[i] == s[len(s) - i - 1] for i in range(len(s) >> 1))
def palindromicNumber(n) :
if n & 1 :
x = (n - 1) >> 1
lower = int(10 ** (x-1))
upper = int(10 ** x)
for j in range(lower,... |
def palindrome_helper(s, n) :
if n == 0 :
yield s
else :
lower = (0 if n > 2 else 1)
for i in range(lower, 10) :
seed = str(i) + s + str(i)
for x in palindrome_helper(seed, n - 2) :
yield x
return
def palindrome_10(n) :
if n & 1 :
lower = (0 if n > 1 else 1)
for i in range(lower,10) :
for x... |
user_input = input()
ma = -1
for ch in user_input:
if(user_input.count(ch) > ma):
ma = user_input.count(ch)
char = ch
print(char)
|
#P4T1 Turtle Lab
#P4Lab1: Shapes
#CTI 110
#Jessica Washington
#create turtles
import turtle
wn = turtle.Screen()
jess = turtle.Turtle()
wn.title("Square and Triangle")
jess.shape("turtle")
jess.color("hotpink")
jess.pensize(5)
ed = turtle.Turtle()
ed.color("blue")
ed.pensize(5)
#create square
fo... |
#P4T2
#CTI 110
#Jessica Washington
#July 2nd, 2018
#Initialize the accumulator.
runningTotal = 0
#Collect info from user.
while runningTotal >= 0:
print('Enter a number?')
#Input numbers.
n = int(input())
#Add numbers together.
runningTotal = runningTotal + n
#Cre... |
#!/usr/bin/env python
# -*- coding:utf-8-*-
#リスト作り方①
a_list = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#リスト作り方②
b_list = []
c_list = []
for i in range(3):
b_list.append(0)
for j in range(3):
c_list.append(b_list)
#リスト作り方③
d_list = [[0]*3]*3
a_list[1][1] = 1
c_list[1][1] = 1
d_list[1][1] = 1
print(a_list)
print(c_... |
import numpy as np
from sklearn.datasets import load_boston
boston = load_boston()
from matplotlib import pyplot as plt
plt.scatter(boston.data[:,5], boston.target, color='r')
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
x = boston.data[:,5]
y = boston.target
x = np.transpose(np.atleast_... |
#PF-Exer-26
def factorial(number):
fact=1
for i in range(1,number+1):
fact*=i
return fact
def find_strong_numbers(num_list):
strong_num_list=[]
for i in num_list:
temp=i
sum=0
if(temp==0):
continue
else:
while i!=0:
num... |
#Write your function here
def reversed_list(lst1, lst2):
count = 0
for i in range(0, len(lst1)):
if lst1[i] == lst2[-i - 1]:
count += 1
if count == len(lst1):
return True
return False
#Uncomment the lines below when your function is done
#print(reversed_list([1, 2, 3], [3, 2, 1]))
#print(reversed... |
#!/usr/bin/env python
"""nims.py
A simple competitive game where players take stones from stone piles.
"""
total = int(40)
player = False
while total > 0:
while not player:
print total,"stones left.",
p1 = int(raw_input("Player 1 [1-5]: "))
if p1 > 5 or p1 < 1:
print "Invalid number of stones."
elif p1 > ... |
#!/usr/bin/env python
import math
try:
import unittest2 as unittest
except:
import unittest
import shapes
from shapes import *
@unittest.skipIf(not hasattr(shapes, "Shape"), "No Shape class defined")
class ShapeTest(unittest.TestCase):
def test_shape_does_nothing(self):
shape = Shape()
... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
#MUST BE FIRST LINE OF CODE
from tkinter import *
# create a new tk object named "root"
root = Tk()
# set up the window
## geometry is width x height in pixels of the total amount of space the total amount of created tk vars can take up
root.geometry("350x250")
## cr... |
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if len(input_list) == 0:
return []
if len(input_list) == 1:
... |
"""
ProcessInput.py
Description
-----------
This file reads an input file containing words and their associated vectors. The input format is 'Word [Vector]'. The words
and their vectors are stored in an empty dictionary with words being keys and vectors value.
"""
import re
import numpy as np
def ProcessInput(filen... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 10:59:58 2020
@author: alexa
"""
import itertools
import time
rows = "123456789"
cols = "ABCDEFGHI"
def AC3(csp, queue=None):
if queue is None:
queue = list(csp.binary_constraints)
while queue:
(xi, xj) = queue.pop(0)
... |
def merge_sorted_lists(li1,li2):
ans = []
len1 = len(li1)
len2 = len(li2)
i = j = 0
while i<len1 or j<len2:
if i<len1 and j<len2:
if(li1[i]<=li2[j]):
ans.append(li1[i])
i += 1
else:
ans.append(li2[j])
j += 1
elif i<len1:
ans.append(li1[i])
i += 1
elif j<len2:
ans.append(li2... |
'''
Write a function which will take a list of integers as input and returns the max integer from that list
as the output
'''
def max_integer(li):
final = li[0]
for num in li[1:]:
if num > final:
final = num
return final
print(max_integer([22,11,3,45,6,17])) |
class ProgramRunner:
def run_program(self, prog, steps, problem_input):
""" Runs the given program on an input for a given number of steps and returns the output.
Args:
prog (boolean array): binary encoding of the program.
steps (int): Upper bound on the number of instru... |
import sys
class Reader:
def __init__(self,path):
self.data = []
self.path = path
def read(self):
with open(self.path, 'rb') as txtfile:
for line in txtfile:
newline = line.rstrip().split(' ')
self.data.append(newline)
return self.data
class Writer:
def __init__(self, path... |
import datetime
# Any time 5 PM or later is interpreted as today. Any time "earlier" than 5 PM is interpreted as tomorrow.
class BabysitterTime:
earliest_start_allowed = 17
latest_end_allowed = 4
today = datetime.date(1970, 1, 1)
tomorrow = today + datetime.timedelta(days=1)
def __init__(self, h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.