text stringlengths 37 1.41M |
|---|
"""
Design a class called Sentence that has a constructor that takes a string
representing the sentence as input. The class should have the following methods:
get_first_word(): returns the first word as a string
get_all_words(): returns all words in a list.
replace(index, new_word): Changes a word at a particular ind... |
def size(i: int):
value = []
for x in range(i):
value.append(input("Enter some value: "))
return value
def check_target(value):
v = []
for z in value:
if z not in v:
v.append(z)
return v
s = size(int(input("Enter size of list: ")))
print(check_target(s))
|
def size(i: int):
value = []
for x in range(i):
value.append(input("Enter some value: "))
return value
def check_target(x, value):
if x in value:
v = x + " is in the list"
else:
v = x + " is not in the list"
return v
s = size(int(input("Enter size of list: ")))
print(... |
# ch03
# The Boston Housing Price dataset (p.92)
from keras.datasets import boston_housing
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
# Preprocessing
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
test_data -= mean
test_data /... |
#! usr/bin/env python
# -*- coding: utf-8 -*-
from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt
'''
r:读
rb: 读二进制文件
'''
def file2matrix(fileName):
fr = open(fileName)
arrayOLines = fr.readlines() #用 readlines() 一次读取所有内容并按行返回 list
numerOfLines = len(arrayOLines) #行数
returnMat = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#函数中的可变参数
#定义可变参数,在参数前面加一个* ,此时可以传入list 或者tupe
def cale (*number):
sum = 0
for n in number:
sum += n*n
return sum
print cale(1,2) #传入的是一个元祖,省略了()
# 2. 如果已经有一个list 或者tupe 需要作为参数传进去,则按照如下调用,且是非常常见 ,当然也可以还原为tupe形式
list1 = [1,2,3]
print cale(*list1)
# 3. 关键字参数: 自动组装0个或任意... |
def questao1():
return 5**2,9*5,15/12,12/15,15//12,12//15,5%2,9%5,15%12,12%15,6%6,0%7
def questao2():
return '5 da tarde'
def questao3():
a=int(input('Digite a hora atual: '))
b=int(input('Digite daqui a quantas horas o alarme deverá tocar: '))
desp=(a+b)%24
if desp>24:
desp... |
# ----------
# Given a car in grid with initial state init.
# Compute the car's optimal path to the position to the goal.
# The costs are given for each motion.
#
# There are four motion directions: up, left, down, and right.
# Increasing the index in this array corresponds to making a
# a left turn, and decreasing the... |
"""hackathon communitea functions"""
from typing import List, Tuple, Dict, TextIO
popup_msg = 'Incorrect username or password. Please try again, or sign up.'
user_list = {}
cups_of_types = {}
English_breakfast = {}
# def sign_up
def welcome_page(username: str, password: str) -> None:
""" Admit users with existi... |
#!/usr/bin/python3
Binary_Node = __import__("binary_tree_node").Binary_Node
class Binary_Tree_Travel:
"""create a nice looking printing when travelling"""
def __init__(self):
self.root = None
def inorder_array(self, node, lis=[]):
if node.left_node is not None:
self.inorder_arr... |
#!/usr/bin/python3
def complex_delete(a_dictionary, value):
del_key = []
for k, v in a_dictionary.items():
if v == value:
del_key += [k]
for k in del_key:
a_dictionary.pop(k)
return a_dictionary
|
class Status:
def __init__(self, size, stat_arr=[], stat_comb = []):
self.stat_arr = stat_arr
self.stat_comb = stat_comb
self.size = size
def return_comb(self):
"""create a combination of Queen location"""
comb = []
for y in range(self.size):
for x in... |
sample_dict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
keys_to_remove = ["name", "salary"]
for key in keys_to_remove:
if key in sample_dict:
del sample_dict[key]
print(sample_dict) |
# username = input("Enter your username: ")
# password = input("Enter your password: ")
# plength= len(password)
# password_block= plength*'*'
# print(f'{username}, your password {password_block}, is {plength} charecters long')
# school = {'Bobby','Tammy','Jammy','Sally','Danny'}
# attendance_list = ['Jammy', 'Bobby... |
# Ex 1
# li1 = [1,2,3,4,5]
# li2 = [6,7,8,9]
# for i in li2:
# li1.append(i)
# print(li1)
# joint_ist = [*li1,*li2]
# print (joint_ist)
# Ex 2
# number = []
# number.append(input("Input the 1st number: "))
# number.append(input("Input the 2nd number: "))
# number.append(input("Input the 3rd number: "))
# p... |
sen = input("Enter a sentance: ")
letter = input("Enter a Letter: ")
print(f'{letter} apperares {sen.count(letter)} times') |
TICKET_PRICE = 10
SERVICE_CHARGE = 2
ticket_remaining = 100
def calc_price(numer_of_tickets):
return (TICKET_PRICE * numer_of_tickets)+SERVICE_CHARGE
while ticket_remaining >= 1:
print ("There are {} tickets remaing".format(ticket_remaining))
name = input("What is your name?: ")
ticket_amount = inp... |
class Node:
def __init__(self):
self.id = ""
self.connected = []
self.x = 0
self.y = 0
self.coordinates = [self.x,self.y]
class Edge:
def __init__(self):
self.connects = []
self.w = 0
self.direction = []
self.x = 0
self.y = 0
self.coordinates = [self.x,self.y]
"""
Make a game of the Dijkstra... |
import random
choice = ["Rock","Paper","Scissors"]
def computer_choice():
return random.choice(choice)
def player_pick():
i=input()
if int(i) < 4 and int(i) > 0:
return choice[i-1]
def main():
print(computer_choice())
if __name__ == '__main__':
main() |
camel_word = input()
snake_word = ""
for char in camel_word:
if char.islower():
snake_word += char
elif char.isupper():
snake_word += "_" + char.lower()
print(snake_word)
|
x = float(input())
y = float(input())
if (x > 0) and (y > 0):
print("I")
elif (x < 0) and (y > 0):
print("II")
elif (x < 0) and (y < 0):
print("III")
else:
print("IV") |
cafe = []
cats = []
while True:
user_input = input()
if user_input == 'MEOW':
break
else:
cat_cafe = user_input.split()
cafe.append(cat_cafe[0])
cats.append(int(cat_cafe[1]))
max_nb_of_cats = (cats.index(max(cats)))
print(cafe[max_nb_of_cats])
|
def factorial(number):
return number * factorial(number - 1) if number > 1 else 1
def fibo(posinfibo):
if posinfibo > 2:
return fibo(posinfibo - 1) + fibo(posinfibo - 2)
else:
return 1
|
import turtle
window = turtle.Screen()
window.setup(width=800, height=600)
window.bgcolor('black')
window.tracer(0)
#Our Game Objects
#Balls
balls = int(input('Set difficulty:'))
for i in range(0, balls):
ball[] = turtle.Turtle()
ball.color('green')
ball.shape('circle')
ball.penup()
ball.speed(0)... |
import numpy as np
def mult_matrix(m1, m2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes invalid ... |
'''
@author:navin106
# Exercise: Assignment-2
# Write a Python function, sumofdigits, that takes in one number \
and returns the sum of digits of given number.
# This function takes in one number and returns one number.
'''
def sumofdigits(int_num):
'''
n is positive Integer
returns: a positive in... |
#Newton Divided difference Formula: Python Coding from below
diff1,diff2,diff3,diff4,diff5,x,y = [ ] , [ ] , [ ] , [ ] , [ ] , [ ] , [ ]
v,w,k=0,0,0
result=0
n=int (input("How many pairs of x and y:\t"))
print ("Enter the value of x:\n")
for i in range(0,n):
a=float(input())
x.append(a)
print ("Enter the value... |
from math import exp,cos,sin,tan,log
import parser
print("Equation format will be x**a+b*x+9 where a is the power of x")
print("b is the constant like 1,2...9 etc\n")
print("When need to input exp or cos or sin use exp() or sin()")
formula=str(input("Enter your whole equation:\n"))
code = parser.expr(formula).compile()... |
# 面向对象编程
# 属性:名字/身高/年龄。。
# 功能/动作:吃喝拉撒
# class Person():
# # 属性:成员变量
# name = "萧瑟"
# high = 180
# # 功能:成员方法,self固定就行
# def chi(self):
# print("吃大餐")
# # 实例化类:p类的对象/把柄
# p = Person()
# print(p.name)
# print(p.high)
# p.chi()
class Cat():
name = "阿珍"
high = "80"
def run(self... |
# 导入 selenium
from selenium import webdriver
import time
# 打开谷歌浏览器: Chrome 的C大写的!! 浏览器的把柄
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.maximize_window()
# 打开网址
driver.get("http://ljtest.net:9090/shopxo/")
# 搜索
driver.find_element_by_id("search-input").send_keys("裙子")
driver.find_element_by_id(... |
import sys
import math
# https://www.codingame.com/ide/puzzle/dwarfs-standing-on-the-shoulders-of-giants
influences = {}
n = int(input()) # the number of relationships of influence
for i in range(n):
# x: a relationship of influence between two people (x influences y)
x, y = [int(j) for j in input().split()]... |
from home_work.classes.Figure import Figure
import math
class Triangle(Figure):
name = 'Треугольник'
angles = 3
def __init__(self, size_a, size_b, angle_a):
# Figure.__init__(self)
if size_a > 0 and size_b > 0 and (angle_a > 0 and angle_a < 180):
self.size_a = size_a
... |
from random import randint
from IPython.display import clear_output
# create the blackjack class, which will hold all game methods and attributes
class Blackjack():
def __init__(self):
self.deck = []
self.suits = ("Spades", "Hearts", "Diamonds", "Clubs")
self.values = (2, 3, 4, 5, 6, 7, 8,... |
from matplotlib import pyplot as plt
from IPython.display import clear_output
ratings, num_ratings = [1, 2, 3, 4, 5], [0, 0, 0, 0, 0]
n = True
while n:
x = True
while x:
rating = input("What would you rate this movie (1-5)? ")
if rating == '1':
num_ratings[0] += ... |
from flask import Flask
import json
import random
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
class Questions():
"""
"""
def __init__(self):
self.questions = None
def get_questions(self, filename='questions.json'):
qs = json.load(open(filename, 'r')... |
def get_odd_factorials(func):
def wrapper(*args,**kwargs):
if args[0]%2==0:
print("We give only odd-positive factorials")
else:
func(*args,**kwargs)
return func(*args,**kwargs)
return wrapper
@get_odd_factorials
def display(num):
f=1
for x in range(1,... |
"""
Write a function that takes directory path, a file extension and an optional tokenizer.
It will count lines in all files with that extension if there are no tokenizer.
If a the tokenizer is not none, it will count tokens.
For dir with two files from hw1.py:
>>> universal_file_counter(test_dir, "txt")
6
>>> univers... |
"""
Given a Tic-Tac-Toe 3x3 board (can be unfinished).
Write a function that checks if the are some winners.
If there is "x" winner, function should return "x wins!"
If there is "o" winner, function should return "o wins!"
If there is a draw, function should return "draw!"
If board is unfinished, function should return... |
"""
Homework 1:
============
We have a file that works as key-value storage, each like is represented as key and value separated by = symbol, example:
name=kek
last_name=top
song=shadilay
power=9001
Values can be strings or integer numbers. If a value can be treated both as a number and a string, it is treated as n... |
"""
Write a function that takes a number N as an input and returns N FizzBuzz numbers*
Write a doctest for that function.
Write a detailed instruction how to run doctests**.
That how first steps for the instruction may look like:
- Install Python 3.8 (https://www.python.org/downloads/)
- Install pytest `pip install ... |
import pandas as pd
import numpy as np
import nltk
import re
from spacy.lang.fr.stop_words import STOP_WORDS as fr_stop
from nltk.stem.snowball import FrenchStemmer
# using stemming of words
stemmer = FrenchStemmer()
# spliting a string using a regular expression
tokenizer = nltk.RegexpTokenizer(r'\w+')
# lists of... |
class SavingsAccount:
def __init__(self, annual_inter_rate, saving_balance):
self.annual_inter_rate=annual_inter_rate
self.saving_balance=saving_balance
def MonthlyInterest(self):
self.monthly_interest=(self.annual_inter_rate*self.saving_balance*0.01)/(12)
self.sa... |
#Automating the analysis of a paragraph.
#Import a text file filled with a paragraph of your choosing.
#Assess the passage for each of the following:
#Approximate word count
#Approximate sentence count
#Approximate letter count (per word)
#Average sentence length (in words)
import re
import os
numlines = 0
numwords = ... |
n=int(input("Enter any number :"));
cube=0;
temp=n;
while(n>0):
no=n%10
cube=cube+(no**3)
n=n//10
if(temp==cube):
print("No is armstrong")
else:
print("No is not armstrong")
|
x=int(input("Enter the number of element of list: "))
l1=[]
def input_fun():
for i in range(0,x):
if(i==0):
num=int(input('Enter 1st element: '))
l1.append(num)
elif(i==1):
num=int(input('Enter 2nd element: '))
l1.append(num)
elif(i==... |
"""
NEED:
Input parsing (command and identifier)
Map support
World floors/sectors
Basic NPC conversations
WANT:
Map random generation
"""
from random import randint
def start():
print('Insert exposition here.')
while True:
name = input('\nWhat is your name: ')
if input('Your name is '+name+' ... |
"""
Linked list
questions (pdf page 106-107, book page 94-95)
solutions (pdf page 220, book page 208)
"""
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def print_list(head):
node = head
while node is not None:
print(node.da... |
from scipy import optimize
# linspace의 데이터 추출 시각화
import matplotlib.pyplot as plt
import math
import numpy as np
def border() :
print()
print("=================================================")
print()
def sigma(K, N, value):
return sum(value[n] for n in range(K, N))
def positive_number(x) :
ret... |
import re
def find_max_ap(students_line):
pattern = r'AP{1,}'
return re.findall(pattern, students_line)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
students_line = input()
res = find_max_ap(students_line)
if len(res) != 0:
... |
def calc(array):
ref = set(array)
for i in range(len(array)):
for j in range(i + 1, len(array)):
if abs(array[i] - array[j]) not in ref:
ref.add(abs(array[i] - array[j]))
return list(ref)
def is_nice(array):
while len(array) <= 300:
x = calc(array)
... |
import re
if __name__ == '__main__':
n = int(input())
arr = []
count = 0
targ = False
for _ in range(n):
x = input()
if count == 0:
pattern = r'OO'
res = re.search(pattern, x)
if res:
x = x.replace('OO', '++', 1)
co... |
def check_three_strings(x, y, z):
for i in range(len(x)):
if x[i] == y[i]:
if x[i] != z[i]:
return 'NO'
elif x[i] == z[i] or y[i] == z[i]:
continue
else:
return 'NO'
return 'YES'
if __name__ == '__main__':
t = int(input())
fo... |
def solve(tab, hand):
for i in hand:
if i[0] == tab[0] or i[1] == tab[1]:
return 'YES'
return 'NO'
if __name__ == '__main__':
card_on_table = input()
card_on_hand = input().split()
ans = solve(card_on_table, card_on_hand)
print(ans) |
import math
def isvalid(s):
# Solution of Quadratic Equation
k = (-1 + math.sqrt(1 + 8 * s)) / 2
# Condition to check if the
# solution is a integer
if math.ceil(k) == math.floor(k):
return int(k)
else:
return -1
if __name__ == '__main__':
n = int(input())
t = input()... |
def binary_search_insertion(item, arr):
# handling border cases
print(f'key: {item}, arr: {arr}')
if arr[0] > item:
new_arr = [item]
new_arr.extend(arr)
return new_arr
elif arr[-1] < item:
arr.append(item)
return arr
start = 0
end = len(arr) - 1
whi... |
if __name__ == '__main__':
# there are n candies and you must distribute them to two sisters alice and betty
# alice will get a (a > 0) and betty will get b (b > 0)
# a > b and a + b = n
t = int(input())
for _ in range(t):
n = int(input())
if n % 2 == 0:
print(n // 2 - ... |
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if set(a).intersection(set(b)):
print('YES')
print(1, list(set(a).intersection(set... |
def solve(array):
x = sorted(array)
max1 = x[-1]
max2 = x[-2]
finalist = [max(array[0], array[1]), max(array[2], array[3])]
if max1 in finalist and max2 in finalist:
print('YES')
else:
print('NO')
if __name__ == '__main__':
t = int(input())
for _ in range(t):
... |
import numpy as np
import matplotlib.pyplot as plt
def generateOrthognalArray (m , n):
arr = np.empty([m,n])
arr[:,0] = np.ones(m , np.int)
for i in range(0,m-1):
item = i * (1/(m - 1))
for j in range(1 , n):
arr[i , j] = pow(item , j-1)
return arr
arr1 = generateOrthogna... |
import random
from objects.game_objects import Card
from objects.player_objects import Player, Action, Hint
class Rando(Player):
def __init__(self, id):
super().__init__(id)
def _strategy(self, players, game):
"""This strategy selects an action and action description completely at random. I... |
# Import connection pool tools from psycopg2
from psycopg2 import pool
# Create a class to create a connection to the database
class Database:
# Create connection_pool property in class
__connection_pool = None
@staticmethod
# Initialize connection with keyword arguments passed in, set pool range bet... |
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import cgi
import sys
PORT = 8080
# Simple server to respond to both POST and GET requests. POST requests will
# just respond as normal GETs.
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
SimpleHTTPServe... |
"""This module contains common operation connected with datetime"""
from datetime import datetime
def datetime_from_string(date_string):
"""
Returns datetime from string formatted like: 2021-01-01
:param date_string: formatted string
:return: datetime corresponding to date_string
"""
return da... |
meal_cost = 12
tip_percent = 20
tax_percent = 8
tip=meal_cost*tip_percent/100
tax=meal_cost*tax_percent/100
x=meal_cost+tip+tax
y=5
print("The total meal cost is {a} {b} dollars.".format(a=round(x),b=(y))) |
import re
def checkFasta(fastas):
status = True
lenList = set()
for i in fastas:
lenList.add(len(i[1]))
if len(lenList) == 1:
return True
else:
return False
def minSequenceLength(fastas):
minLen = 10000
for i in fastas:
if minLen > len(i[1]):
minLen = len(i[1])
return minLen
def minSequenceLeng... |
from random import randint
#criando função para criar ficha:
def criarficha(nomedaficha):
ficha = open(f"{nomedaficha}.txt", "w+")
while True:
classe = input("qual a classe do seu personagem?(Guerreiro, assasino ou mago)").upper()
if classe != "MAGO" and classe != "GUERREIRO" and classe != "AS... |
# I need this playground area to replace a dictionary key value on a small
# scale
from collections import defaultdict
# ASSIGN A NEW VALUE TO AN EXISTING KEY TO CHANGE THE VALUE
# Use the format dict[key] = value to assign a new value to an existing key.
a_dictionary = {"a": 1, "b": 2}
a_dictionary["b"] = 3
# US... |
#!/usr/bin/env python3
import os
def str_list_to_int_list(input):
for i, value in enumerate(input, start=0):
input[i] = int(value)
return input
def get_content(path):
with open(path, 'r') as data:
return data.read()
def get_deserialized_content(path):
return get_content... |
asd = input("Enter your 12 bit EAN barcode number: ")
tin = [int(i) for i in asd]
odd = 0
even = 0
for k in range(1,12,2):
odd += tin[k]
for j in range(0,12,2):
even += tin[j]
checksum = odd*3 + even
checkdigit = checksum % 10
if checkdigit != 0:
checkdigit = 10 - checkdigit
print(asd+str(checkdigit))
|
# coding:utf-8
'''
【101】对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.lef... |
# coding:utf-8
'''
96. 不同的二叉搜索树
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
class Sol... |
# coding:utf-8
'''
【229. 求众数 II】
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。
示例 1:
输入: [3,2,3]
输出: [3]
示例 2:
输入: [1,1,1,3,3,2,2,2]
输出: [1,2]
'''
class Solution(object):
'''
摩尔投票法
组一个team 若投票到team中的一员 进行下一轮,否则同时抵消;最终team中为最大的几个人
'''
def majoritElement(self, nums):
... |
# coding:utf-8
class Solution(object):
def minArray(self, numbers):
low = 0
high = len(numbers) -1
while low < high:
mid = low + (high-low)/2
if numbers[mid] < numbers[high]:
high= mid
elif numbers[mid] >numbers[high]:
low ... |
# coding:utf-8
class Solution(object):
def searchInsert(self, nums, target):
if not nums:
return 0
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high-low)/2
if nums[mid] == target:
return mid
elif nums[mi... |
# coding:utf-8
'''
【53. 最大子序和】
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
'''
class Solution(object):
def maxSubArray(self, nums):
dp = list()
dp.append(nums[0])
maxSum... |
# coding:utf-8
class Solution(object):
def reverse(self, s):
s = s.strip()
s = list(s)
low = 0
high = len(s) -1
while low < high:
tmp = s[low]
s[low] = s[high]
s[high] = tmp
low += 1
high -= 1
return ''.join... |
# coding:utf-8
'''
【560. 和为K的子数组】
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
'''
class Solution(object):
''' 前缀和 '''
def subarraySum(self, nums, k):
cnt = 0
... |
# coding:utf-8
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxDepth(self, root):
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
... |
# coding:utf-8
'''
【1025. 除数博弈】
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
选出任一 x,满足 0 < x < N 且 N % x == 0 。
用 N - x 替换黑板上的数字 N 。
如果玩家无法执行这些操作,就会输掉游戏。
只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。
示例 1:
输入:2
输出:true
解释:爱丽丝选择 1,鲍勃无法进行操作。
示例 2:
输入:3
输出:false
解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行... |
# coding:utf-8
'''
【657. 机器人能否返回原点】
在二维平面上,有一个机器人从原点 (0, 0) 开始。给出它的移动顺序,判断这个机器人在完成移动后是否在 (0, 0) 处结束。
移动顺序由字符串表示。字符 move[i] 表示其第 i 次移动。机器人的有效动作有 R(右),L(左),U(上)和 D(下)。如果机器人在完成所有动作后返回原点,则返回 true。否则,返回 false。
注意:机器人“面朝”的方向无关紧要。 “R” 将始终使机器人向右移动一次,“L” 将始终向左移动等。此外,假设每次移动机器人的移动幅度相同。
示例 1:
输入: "UD"
输出: true
解释:机器人向上移动一次,然后向下移... |
# coding:utf-8
'''
【437. 路径总和 III】
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有... |
# -*- coding:utf-8 -*-
# author cherie
# jascal@163.com
# jascal.net
# Merge k Sorted Lists
class Solution:
def mergeKLists(self, lists):
if len(lists) == 0:
return None
if len(lists) == 1:
return lists[0]
mid = len(lists) // 2
l1 = self.mer... |
#coding:utf-8
import PIL.Image as Image
import os
import sys
def compressMutiImage(dirPath):
rename(dirPath)
fileList = os.listdir(dirPath)
for f in fileList:
if(".png" in f):
if os.path.isfile(f):
sImg=Image.open(f)
w,h=sImg.size
dImg=sImg.resize((w/2,h/2),Image.A... |
#This is primegame. this application gives the max difference between 2 primenumbers in a given range of numbers
def prime(n):
if n<=1:
return False
for i in range(2,n):
if n%i==0:
return False
return True
k=int(input("no.of iterations"))
while k>0:
l,m = [int(x) for x in input("enter ... |
def get_songs(data: dict) -> dict:
""" Returns a dictionary of song id: playbacks from data given."""
songs = dict()
for item in data["items"]:
name = item["track"]["id"]
if name in songs:
songs.update({name: songs[name]+1})
else:
songs[name] = 1
return songs... |
from starwars import list_of_swapi, detail_profile
if __name__ == '__main__':
choice = int(input("enter option"))
while choice != 6:
if choice == 1:
choice1 = int(input("enter choice\n1.Starwars people list\n2.Starwars planets list\n3.Starwars films list\n"
"4... |
#examAnewMark.py
import random
showAgain = True
while showAgain == True:
count = 0
totalSum =0
score = 0
for x in range(1,1001):
randomNumber= random.randint(1,9)
if randomNumber%2 == 0:
score = 100
else:
score = 60
totalSum += score
... |
def cipher():
#this encodes just one single letter
#store the alphabet as a string
alphabet ='abcdefghijklmnopqrstuvwxyz'
#get the letter from the user as a string
original = input("What is the letter in to encode: ")
#get the amount of shift from user as a number
shift = eval(input("... |
# CS110Exam_XXX_C_Block.py
# XXX, XXX (Jan, 2016)
'''
Pseudocode:
import the random momdule
game = True
setup game loop
while game = True
print welcome message
ask user to input name
set variables
compWins = 0
userWins = 0
loops for roll
while userWins does not equal 5 and whil... |
from random import randrange
def dieRoll(numDice):
x=[]
for i in range(numDice):
d=randrange(1,7)
x.append(d)
#print(x)
return x
def scoring(play,comp):
if play>comp:
print(namePlayer+' wins with '+str(playRoll),'George only rolled '+str(compRoll))
elif pla... |
# CS110Exam_Colwell_C_Block.py
# Colwell, Andrew (Jan, 2016)
'''
Pseudocode:
import Random
set initial variables
loop until game ends
get random number
loop until player stops
get user guess
add one to guess counter
compare with random number
== print number of ... |
#A5_3 Read three points from a text file
#Then draw the triangle with graphics.py
from graphics import *
from time import sleep
#file=open(r'A5_3.txt','r')
file=open(r'U:\trianglePoints.txt','r')
L1=[]
data=file.readline()
while data !='':
s=data.find('\n')
if s>=0: #If... |
#!/usr/bin/python3
# coding: utf-8
import sys
def tag_sort():
""" This mapper sort top 10 tags for each locality name in descending order
Input data format: place_url_1 \t {tag_n = count}
...
Output data format: place_url_1 \t {tag_top_1 = count} ... {tag_top_10 = count}
...
"""
top_10_tags =... |
# -*- coding: UTF-8 -*-
x = 33
y = 4
print(x % y)
print(x // y)
x = 2
y = 3
print(x ** y)
|
# POINTERS
PI = 3.14
print('pi', PI)
PI = 3
print('changed pi', PI)
first_number = 1
second_number = first_number + 1
print(first_number)
print(second_number)
first_letter = 'h'
second_letter = first_letter # 'h'
second_letter = 'hola'
print(first_letter)
print(second_letter)
numbers = [1, 2]
more_numbers = numbers... |
"""Demonstration of the Workflow Design Pattern.
As the name suggests, this pattern wants to represent workflows.
It is basically an extension of the 'Command Pattern' meant for more complex,
long-running commands consisting of multiple sub-commands. Workflows also
provide multiple ways of evaluation, usually local an... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 12:12:37 2018
@author: Admin
"""
import unittest
from calculator import Calculator
class CalculatorTest(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def testPrintDecimalNumbers(self):
self.calc.setInput(1)
... |
#! /usr/bin/python
row = "+-----"
def row1():
for i in range(4):
print(row,end="")
print("+")
def col1():
for i in range(4):
for i in range(4):
print("| ",end=" ")
print("|")
for i in range(4):
row1()
col1()
row1()
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self,x):
self.val = x
self.left = None
self.right = None
self.parent = None
"""
:type val: int
:type left: TreeNode or None
:typ... |
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1, 2, 2, 3, 4, 4, 3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
output: true
But the following [1, 2, 2, null, 3, null, 3] is not:
1
/ \
2 2
\ \
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.