text stringlengths 37 1.41M |
|---|
from operator import sub, add, mul
operators = {
"-": sub,
"+": add,
"*": mul
}
class DynamicList:
DEFAULT_INITIAL_CAPACITY = 10
MINIMAL_CAPACITY = 10
GROW_COEEFICIENT = 2
def __init__(self, initialCapacity = DEFAULT_INITIAL_CAPACITY):
self.capacity = max(initialCapacity, self.MI... |
def find_max_substring_occurrence(input_string):
if len(input_string) == 0:
return 0
else:
repeatLengthCandidate = 1
while repeatLengthCandidate < len(input_string):
if len(input_string) % repeatLengthCandidate == 0:
k = len(input_string) // repeatLengthCandid... |
import re
def sanitise_string(string: str) -> str:
return re.sub(r"\_|[^\w']+", ',', string.lower()).strip(',')
def sanitise_words(words: list) -> list:
results = []
for w in words:
word = re.sub(r"^['\']|['\']$", "", w)
results.append(word)
return results
def count_words(sentenc... |
def hello_again(**kwargs):
return "I am {}, and am I'm {}".format(kwargs['name'], kwargs ['age'])
print hello_again(name='Joe', age=20)
print hello_again(age=20, name='Jane')
other_people = [
{'name': 'Joe', 'age':98},
{'name': 'Jane', 'age':60},
{'name': 'Pauline', 'age':26}
]
Pauline = {'name': 'Joe', ... |
def funky(a, b):
if isinstance(a, (int,list,float)) and isinstance (b, (int,list,float)):
return a + b
elif isinstance(a, dict) and isinstance (b, dict):
z = dict(a.items() + b.items())
return z
elif type(a) ==str or type(b) ==str:
return str(a) + str(b)
else:
return "NO CAN DO"
print('h',7)
print funk... |
def data_type(item):
if type(item) == str:
return(len(item))
elif type(item) == bool:
return item
elif type(item)== int:
if item < 100:
return "less than 100"
elif item > 100:
return "more than 100"
else:
return "equal to 100"
elif type(item) == list:
if len(item) < 3:... |
"""
neural nets will be masd up of layers.
Each layer needs to pass its input forward
and propagate gradients backward.
for example, a neural net might look like:
inputs -> Linear -> Tanh -> Linear -> output
"""
import os, sys
from mynet import tensor
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))... |
import time
def sumOfN(n):
startTime = time.time()
theSum = 0
for i in range(1, n+1 ):
theSum = theSum + i
endTime = time.time()
return theSum, endTime - startTime
print(time.time())
print(sumOfN(10))
for i in range(5):
print("sum is %d required %10.5f seconds" % sumOfN(10000))
for i... |
import time
def sumOfN3(n):
startTime = time.time()
theSum = n * (n+1) / 2
endTime = time.time()
return theSum, endTime - startTime
print("the sum is %d reuqired %10.10f seconds" % sumOfN3(10000))
print("the sum is %d reuqired %10.10f seconds" % sumOfN3(1000000))
print("the sum is %d reuqired %10.10... |
def print_max(x, y):
""" Print the maximum of two numbers. 打印两个数值中的最大数
the two values must be integer. 这两个数都应该是整数 """
# 如果可能,将其转换至整数类型
x = int(x)
y = int(y)
if x > y:
print(x, ' is the maximum')
elif x < y:
print(y, ' is the maximum')
else:
print('The two number... |
import random
import time
a = ["stone", "paper", "scissor"]
print("lets start the game \nThere will be 3 rounds \n")
time.sleep(1)
print("\t 3")
time.sleep(1)
print("\t 2")
time.sleep(1)
print("\t 1")
time.sleep(0.5)
print("\n\tlets go !!!!\n")
# print(random.choice(a))
PlayerPoints = 0
CompPoints = 0
i = 1
while... |
#!/usr/bin/env python3
'''
booksdatasource.py
Jeff Ondich, 18 September 2018
For use in some assignments at the beginning of Carleton's
CS 257 Software Design class, Fall 2018.
'''
import sys, csv, operator
class BooksDataSource:
'''
A BooksDataSource object provides access to data about books ... |
'''
var1 =0 #equality & inequality operators
print(var1 != 0)
var1 =1
print(var1 != 0)
x = int(input("Enter the number you want to enter : "))
print(x<=100)
# read two numbers IF ELSE STATEMENT ..............
number1 = int(input("Enter the first number: "))
numbe... |
def strangeListFunction(n):
strangeList = []
for i in range(0, n):
strangeList.insert(0, i)
return strangeList
print(strangeListFunction(5))
# O/p: [4, 3, 2, 1, 0]
|
nombre_archivo = raw_input("nombre del archivo? ")
if nombre_archivo != "":
archivo = open (nombre_archivo, "r")
else:
exit ()
total_linea = 0
total_char = 0
for linea in archivo:
total_linea +=1
for caracter in linea:
total_char += 1
print "total lineas", total_linea
print "total caracteres", total_char |
# -*- coding: utf-8 -*-
"""
Programming template for CS-E5740 Complex Networks problem 3.3 (PageRank)
Written by Onerva Korhonen
Created on Tue Sep 8 10:25:49 2015
@author: aokorhon
"""
from random import random
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import timeit
def page_rank(n... |
#!/usr/bin/env python
import psycopg2
def connect():
"""Connect to the PostgreSQL database.
Returns a database connection."""
try:
return psycopg2.connect("dbname=news")
except:
print("Cannot conncet to DATABASE")
def popart():
db = connect()
cu = db.cursor()
# Part 1
q... |
import random
when = ['10 years ago' , 'Last week' , 'Yesterday' , 'Two weeks a go']
who = ['a man' , 'a dog' , 'a girl', 'a raccoon' , 'a panda' ]
name = ['Stevie', 'Rafa' , 'Jane', 'Abdul', 'Raj', 'Jane','Rhonda']
residence = ['Portland' , 'Toronto' , 'NYC' , 'Berlin']
went = ['Paris' , 'Delhi' , 'Sydney', 'Louisian... |
import random
roll_dice = input("Do you want to roll the dice? ")
while roll_dice.lower() == 'yes' or roll_dice.lower() == 'y':
n1 = random.randint(1,6)
n2 = random.randint(1,6)
print(f"Your numbers are {n1} & {n2}")
roll_dice = input("Do you want to roll again? ")
|
class ATM(object):
def __init__(self, cardnum, pin, bankname):
self.cardnum=cardnum
self.pin=pin
self.banname=bankname
self.amount=50000
def checkbalance(self):
print("Your balance is", self.amount)
def withdraw(self, amount):
bal=self.amount-am... |
from person import *
class PersonManager(object):
"""人员管理类"""
def __init__(self):
# 存储数据所用的列表
self.person_list = []
# 程序入口函数
def run(self):
# 加载文件里面的人员数据
self.load_person()
while True:
# 显示功能菜单
self.show_menu()
# 用户输入目标功能序号... |
#three2min.py
a=eval(input("第1个整数:"))
b=eval(input("第2个整数:"))
c=eval(input("第3个整数:"))
temp=0 #用于存放三个数的最小值
if (a>b):
temp=b
else:
temp=a
if(temp<c):
print("最小数为:%d" %temp)
else:
print("最小数为:%d" %c)
|
# -*- coding: UTF-8 -*-
# @Project -> File: python_training -> order_search
# @Time: 2021/8/1 15:47
# @Author: Yu Yongsheng
# @Description:
# 顺序查找
def orderSearch(num_list, x):
for i in range(len(num_list)):
if num_list[i] == x:
return i
return -1
if __name__ == '__main__':
num_list =... |
pizza = {
"ctust":"thick",
"toppings":["mushroom","extra cheese"]
}
print("You ordered a "+pizza["ctust"]+"- crust pizza" +"with the flowing toppings:")
for topping in pizza["toppings"]: print("\t"+topping) |
message1 = input("Tell me something,and I will repeat it back to you:")
print(message1)
promot = "\n Tell me something, and I will repeat it back to you:"
promot = "\n Enter 'quit' to end the program."
message = ""
while message != "quit":
message = input(promot)
if message != "quit":
print(message) |
age = 88
if 2<age<=4:
print("他正蹒跚学步")
elif 4<age<=13:
print("他是儿童")
elif 13<age<=20:
print("他是青少年")
elif 20<age<=65:
print("成年人")
elif 65<age:
print("老年人")
fruits = ["strawberry","grapefruit","bananas"]
if "strawberry" in fruits:
print("You really like strawberry!")
if "grapefruit" in fruits:
... |
squares =[]
for value in range(1,11):
square = value ** 2
squares.append(square)
print(squares)
# 另一种写法
for value in range(1,11):
squares.append(value**2)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares)) |
# """
# if <Condition>:
# statement
#
# """
# number_01 =1
# number_02 =2
# number_03 =4
#
# # if number_01 < number_02:
# # print('Number 02 is greater than Number01.')
# #
# # #if else
# #
# # if number_01 > number_02:
# # print("Number 01 is greater than Number02.")
# # else:
# # print('Number 02 is ... |
class Fifteen:
def __init__(self, verbose=0):
self.count = 0
def lab(self,xlength,ylength):
if xlength > 0 and ylength >0:
self.lab (xlength - 1, ylength)
self.lab (xlength, ylength -1)
if xlength==0 or ylength==0:
self.count = self.count + 1;
print str(xlength) + ' ' + str(ylength) + ' ' + s... |
def read_triangles_from_file ():
triangles = []
with open('triangles.txt', 'r') as f:
for line in f:
triangle = line.rstrip('\n')
triangles.append(triangle)
return triangles
def get_A(line):
values = line.split(',')
values = map(float, values)
A = []
A.append([values[0], values[2], values[4]])
A.append... |
faculty=1
for i in range(100,1,-1):
faculty= faculty * i;
print faculty
facultyStr=str(faculty)
summe=0
for i in range (0,len(facultyStr)):
summe = summe + int(facultyStr[i])
print summe
|
from argparse import ArgumentParser
from subprocess import call as _call
parser = ArgumentParser(description="Development scripts for OpenSlides")
subparsers = parser.add_subparsers()
def command(*args, **kwargs):
"""
Decorator to create a argparse command.
The arguments to this decorator are used as ar... |
"""
Inverse Burrows-Wheeler Transform Problem: Reconstruct a string from its Burrows-Wheeler transform.
Input: A string Transform (with a single "$" symbol).
Output: The string Text such that BWT(Text) = Transform.
CODE CHALLENGE: Solve the Inverse Burrows-Wheeler Transform Problem.
Sample Input:
TTCCTAACG... |
def layered_multiples(arr):
print arr
new_array = []
for x in arr:
val_arr = []
for i in range(0,x):
val_arr.append(1)
new_array.append(val_arr)
return new_array
x = layered_multiples(multiply([2,4,5],3))
print x |
#inventory using functions
def order():
print("Each box price is Rs.3000/-")
enter = int(input("Enter how many boxes you want to order: "))
return enter
def bill(box):
unit_cost = 3000
price = box * unit_cost
return price
def discount(offer):
if offer >= 50000:
user_discou... |
'''A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.'''
#lambda arguments : expression
x = lambda a: a*10
print(x(3))
y = lambda a,b : a * b
print(y(3,4))
#The power of lambda is better shown when you use them as an ano... |
###PROGRAM TO SEARCH IN A LIST###
tem = input("Enter the item you want to find? ")
mylist = [input() for num in range(5)]
flag = False
for x in range(len(mylist)):
if mylist[x] == item:
print("Item is found " + item + " at location: " + str(x+1))
flag = True
break
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 04 18:49:27 2016
@author: Geetha Yedida
"""
import turtle
def draw_sphere():
sphere = turtle.Turtle()
window = turtle.Screen()
for i in range(36):
sphere.circle(100)
sphere.right(10)
window.exitonclick()
draw_sphere() |
# if 문을 사용한다.
money =1
if money :
print("taxi")
else :
print("walk")
a =10
if a :
print("true")
print("what we can do")
print("yes we can")
else :
print("false")
money = 2000
if(money > 3000) or a :
print("money is much than 2000")
else:
print("money is less than 2000")
if 1 in [1,2,3] :
print("1 is i... |
'''
🍏219. Contains Duplicate II
Easy https://leetcode.com/problems/contains-duplicate-ii/description/
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: t... |
'''
🍏145. Binary Tree Postorder Traversal
Easy https://leetcode.com/problems/binary-tree-postorder-traversal/
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = ... |
'''
🍊🔐1569. 社交网络
中等 https://www.lintcode.com/problem/1569/
每个人都有自己的网上好友。现在有n个人,给出m对好友关系,寻问任意一个人是否能直接或者间接的联系到所有网上的人。若能,返回yes,若不能,返回no。好友关系用a数组和b数组表示,代表a[i]和b[i]是一对好友。
样例1 样例2
输入: n=4, a=[1,1,1], b=[2,3,4] 输入: n=5, a=[1,2,4], b=[2,3,5]
输出: "yes" 输出: "no"
说明: Explanation:
1和2,3,4能直接联系 1,... |
'''
22. Generate Parentheses
Medium https://leetcode.com/problems/generate-parentheses/
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Cons... |
'''
🍊153. Find Minimum in Rotated Sorted Array
Medium https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
• [4,5,6,7,0,1,2] if it was rotated 4 times.
... |
import numpy as np
WHITE = -1
BLACK = +1
EMPTY = 0
PASS_MOVE = None
class GameState(object):
"""State of a game of Go and some basic functions to interact with it
"""
def __init__(self, size=19):
self.board = np.zeros((size, size))
self.board.fill(EMPTY)
self.size = size
self.turns_played = 0
self.curre... |
import json
#Класс хранит состояние игры в города, есть методы для того чтобы делать ходы
class Game:
def __init__(self):
with open('cities.json', 'r', encoding='utf-8') as fin:
self.cities = json.load(fin)
self.used_cities = []
self.prev_city = 'Москва'
self.player_turn ... |
def student_name(*names):
for name in names:
print(name)
student_name("jayshri","vaishali","puja","saru")
# def student_name(*names):
# print(names)
# student_name("jayshriuyi","baishu","hgijk","gyguij")
|
""" Recurrent Neural Network.
A Recurrent Neural Network (LSTM) implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Links:
[Long Short Term Memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf)
[MNIST Da... |
from numpy import mean, std
operaciones_lista=[-9,-45,0,7,45,-100,89] #Se crea la lista
suma_numeros_positivos=0
suma_numero_negativos=0
for i in range(len(operaciones_lista)): #For que vaya desde i=0 hasta la cantidad de numero en la lista
if operaciones_lista[i]>=0: #Solo si son mayor a 0
suma_... |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
# convert decimal to binary using bin()
# use [2:] to remove the ob from start of output
bin_output = bin(n)[2:]
#print(bin_output)
count = 0
total_count... |
8.5심사
so = {'go':90,'en':81,'ma':86,'si':80}
9.3 심사
so['en'] > 80 or so['ma'] > 85 or so['si'] >= 80 or so['go'] >= 90
10.5심사
su = int(input())
print(list(range(-10,11,su)))
11. 심사
ans1 = str(input())
ans2 = str(input())
for i in ans1:
a = ans1.index(i)
12.심사
key = ['health', 'health_regen', 'mana' ,'mana_re... |
from collections import defaultdict
def group_anagrams(strings):
anagrams = defaultdict(list)
for string in strings:
s_anagram = "".join(sorted(string)).replace(" ", "")
anagrams[s_anagram].append(string)
all_anagrams = []
for anagram_strings in anagrams.values():
all_anagrams... |
def rotated_search(array, needle):
if not array:
return None
mid = int(len(array) / 2)
mid_val = array[mid]
if mid_val == needle:
return mid
right_val = array[-1]
if (needle > mid_val and not needle > right_val) or (needle < mid_val and needle < array[0]):
return rotat... |
num = int(input())
count = 0
for i in range(2,num):
if num % i == 0:
count = count + 1
if(count >= 1):
print("no")
else:
print("yes")
|
ps=input()
ps=ps.replace(" ","")
ps=ps.lower()
if(len(set(ps)))==26:
print("yes")
else:
print("no")
|
a1=int(input())
if a1>1:
for i in range(2,a1//2):
if(a1%i)==0:
print("yes")
break
else:
print("no")
else:
print("yes")
|
nber1=str(input())
for i in range(0,len(nber1)):
if nber1[i]!='0' and nber1[i]!='1':
print("no")
else:
print("yes")
|
number=int(input())
l={1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",9:"Nine",10:"Ten"}
print(l[number])
|
number=input()
e=input().split(" ")
f=len(e)
for i in range(f):
print(e[i],end=" ")
print(i)
|
shi,sea=map(str,input().split())
if(len(shi) != len(sea)):
print('no')
xs=[shi.count(char1) for char1 in shi]
ys=[sea.count(char1) for char1 in sea]
if(xs==ys):
print('yes')
else:
print('no')
|
num=input()
count=0
for i in num:
if (i.isnumeric())== True:
count=count+1
print(count)
|
num=int(input())
a=input().split(' ')
b= [int(j) for j in a]
b.sort()
for j in range (num):
print(b[j],end=" ")
|
print([x*x for x in range(4)])
print([x*x*x for x in range(4) if x*x % 3 == 0])
print([x.lower() for x in "LOREM IPSUM DOLOR".split()])
print(sum([x*x*3 for x in range(4) if x*x % 3 == 0]))
|
import os
import os.path
def przegladanie(root, file_dictionary):
file_list = os.listdir(root)
dir_list = []
for item in file_list:
if os.path.isfile(os.path.join(root, item)):
full_name = os.path.join(root, item)
file_size = os.path.getsize(full_name)
if file_s... |
class NotStringError(Exception):
pass
class NotIntError(Exception):
pass
class Wyrazenie:
pass
class Zmienna(Wyrazenie):
def __init__(self, nazwa):
if not isinstance(nazwa, str):
raise NotStringError
self.nazwa = nazwa
def __str__(self):
return self.nazwa
... |
class CustomException(Exception):
def __init__(self, msg):
self.msg = msg
class TryAddExistTriangleException(CustomException):
pass
class NotValidinstanceOfTriangleException(CustomException):
pass
class ValidationException(CustomException):
pass
class ListOfTriangles(list):
"""
Creates... |
import sys
# ----------------------------------------------
# Cartesian coordinate point
# ----------------------------------------------
class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
def printIt(self):
sys.stdout.write("(" + str(self.x) + ", " +... |
def main():
print(is_even([5, 6, 7, 8]))
def is_even(arr):
return sum(arr) % 2 == 0
if __name__ == '__main__':
main() |
import pandas as pd
import numpy as np
# Adpated from https://machinelearningmastery.com/convert-time-series-supervised-learning-problem-python/
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
var_n= data.columns.tolist()
... |
#/usr/bin/python
import sys
def main(argv):
strand = str(argv[0])
aCount = 0
cCount = 0
gCount = 0
tCount = 0
#Parsing DNA strand
for molecule in strand:
if molecule == "A":
aCount += 1
elif molecule == "C":
cCount += 1
elif molecule == "G":
gCount += 1
elif molecule == "T":
tCount += 1
... |
# python3 /users/haoransong/Desktop/python/5qi.py
import random
def play_wuziqi():
first = 1 #1:player first 2:computer first
board = make_board()
x = []
for i in range(13):
x.append([])
for i1 in range(13):
x[-1].append(0)
y = []
for i in range(13):
y.append([])
for i1 in range(13):
y[-1].append(... |
score = input("Enter Score: ")
try :
x=float(score)
except:
print ("Error,pleas enter a numeric input between 0.0 and 1.0")
quit()
if x < 0.6 :
print ("F")
elif x > 1 :
print ("Error,pleas enter a numeric input between 0.0 and 1.0")
elif x >= 0.6 :
print ("D")
elif x >=0.7 :
print ("C")
elif... |
class Solution(object):
def lexicalOrder(self, n):
res = []
def print_numbers(k, n):
for i in range (0, 10):
if (k+i)<= n:
res.append(k+i)
print_numbers((k+i)*10, n)
for k in range (1, 10):
if k <= n:
... |
class Solution:
def spiralOrder(self, matrix):
def spiral(d,i,j):
result.append(matrix[i][j])
temp[i][j] = matrix[i][j]
if d == 'right':
if j == n-1 or temp[i][j+1] != '.':
d = 'down'
i += 1
else: j +... |
class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
else:
tank = 0
i = 0
result = 0
while True:
tank += gas[i]-cost[i]
if i == len(gas)-1:
return re... |
class Solution:
def mySqrt(self, x):
low = 0
high = x
if x < 2:
return x
while low < high-1:
mid = (low+high)//2
if mid**2 == x:
return mid
elif mid**2 > x:
high = mid
else:
lo... |
class Solution:
def findMin(self, nums):
low = 0
high = len(nums)-1
if nums[0] < nums[-1]:
return nums[0]
while low < high-1:
mid = (low+high)//2
if nums[mid] < nums[-1] or nums[mid] < nums[0]:
high = mid
elif nums[mid] ... |
class Bike:
list_of_bikes = []
rate = 0
bill = 0
def __init__(self,stock,bikes_requested):
self.stock = stock
self.bikes_requested = bikes_requested
def price_of_bikes(self,type_of_rate):
if type_of_rate == "hourly":
Bike.rate = 5
elif type_o... |
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
def create_data():
df = pd.read_excel("../dataset/GDP_original.xlsx")
df = df.fillna(value=0)
year_GDP = {"Year" : "million_dollars"}
for row in range(2, 2+9):
year_GD... |
import random
def create_matrix(columns:int, rows: int):
"""
Testea la funcion que crea una matriz:
- Creando una matriz randomizada (utilizando seed)
>>> random.seed(5)
>>> columns = 5
>>> rows = 5
>>> create_matrix(columns, rows)
[[5, 3, 3, 5, 1], [4, 2, 1, 2, 1], [3, 4, 2, 4, 5], [1... |
# coding=utf-8
from collections import defaultdict
import random
from environment import *
import matplotlib.pyplot as plt
Q_PERIOD = 3
class Q_Agent():
def __init__(self, actions, epsilon=0, discount=1, alpha=0.8):
self.actions = actions
self.game = Game()
self.Q = defaultdict(float)
... |
#creando la lista vacia
listaRegistro = []
clientes = 0
clientela = int(input("Clientes a ingresar: "))
costoTotal=0
while clientes < clientela:
cliente = input("nombre del cliente: ")
producto = input("nombre del producto: ")
costo = float(input("costo($0.00): "))
#registro: {"cliente"... |
########### This program to indicate whether a point is within a city's borders on a 2-dimensional grid (X and Y axes) or not ##############
import csv
from collections import defaultdict
import numpy as np
import os.path
def ReadaingCitiesCoordinatesFromCSV():
columns = defaultdict(list)
# ge... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the candies function below.
def candies(n, arr):
for e in range(len(arr)):
if e==0:
ans=1
peek=1
last=1
acc=0
else:
if(arr[e]>arr[e-1]):
... |
def identificarcarta(x):
if x=="T" or x=="J" or x=="Q" or x=="K" or x=="A":
return 10
else:
return int(x)
t=1
casos=int(input())
while t<=casos:
Y=0
buscador=26
x=input()
x=x.split()
card=identificarcarta(x[buscador][0])
Y+=card
buscador-=10-card+1
... |
import random
chance = 1
max_chance = 10
rand_value = random.randint(1, 1000)
while chance <= max_chance:
try:
print('Chance :', chance)
user_value = int(input('enter the value :'))
except ValueError as err:
print('invalid input, retrying......\n')
continue
if user_value =... |
"""http request with proxies"""
import requests
def get_proxies():
proxies = dict(
http='http://user:passwd@isas.danskenet.net:80',
https='http://user:passwd@isas.danskenet.net:80',
)
return proxies
if __name__ == '__main__':
url = 'http://google.com'
response = requests.get(url)... |
"""sort or reverse"""
temp = [3.3, 2.2, 0.98, 0.12, 3.3, 2.2, 0.98, 0.12, 3.3, 2.2, 0.98, 'peter']
temp.reverse() # inplace edit
print(temp) |
import os
import re
def count_word():
"""
统计总字数
:return:
"""
dirname = '章节'
filenames = os.listdir('章节')
count = 0
for name in filenames[:]:
with open(os.path.join(dirname, name), 'r', encoding='utf8') as f:
words = re.findall('[\u4e00-\u9fa5]', f.read())
... |
# 반례를 생각하지 못했다 - 합친 카드 팩과 다른 것을 비교할때 다른 두개가 더 작을경우
# 그 두개 먼저 비교해야하는데 그 경우를 생각하지 못했다.
# 시간복잡도가 너무 크게나와 우선순위 큐를 힙으로 구현하여 사용하기로 했다.
import sys
import heapq
N = int(input())
data = []
for i in range(N):
heapq.heappush(data, int(sys.stdin.readline()))
result = 0
if len(data) == 1: # data 가 1개일 경우 비교할 필요 없음
print(0... |
def person_print(name, last_name, *others, age):
formatted_data = 'Imię: {}, nazwisko: {}, wiek: {}'.format(name, last_name, age)
others_str = ' '
for arg in others:
others_str += arg + ' '
print(formatted_data + others_str)
person_print('Jan', 'Kowal', 'pesel: 90122413426', age=33)
... |
# Input function lets you input a string into the variable
string = input("Please enter a string: ")
i = 0
stringrev = ""
#print prints to the console
print(string)
stringlen = len(string)
j = stringlen
print(stringlen)
#reverses the string into the stringrev
for i in range(0, stringlen):
stringrev += string[j... |
# print("你好,世界!")
# day01 复习
# Python 简介
# python执行方式
# 交互式:在终端中输入指令,回车即可得到结果
# 文件式:将指令存放在.py的文件中,可以重复执行
# Python执行过程
# 编译:运行前,将源代码转换为机器码,例如:C语言
# 优势:运行速度快
# 劣势:开发效率低
# 解释:运行时,逐行翻译执行,例如JavaScript
# 劣势:运行速度慢
# 优势:开发效率高
# 运行时
# 源代码 -“编译”- 字节码 -解释-》 机器码
# 第一次
class A:
... |
import math
def findMaximum(arr, mid):
# Caso chegue em um ponto no qual arr[mid] é maior que ambos os elementos adjacente
if arr[mid] > arr[mid + 1] and arr[mid] > arr[mid - 1]:
return arr[mid]
# Se o arr[mid] é maior que o próximo elemento e menor que o elemento anterior
if arr[mid] ... |
def trifeca(word):
"""
Checks whether word contains three consecutive double-letter pairs.
word: string
returns: bool
"""
double = 0
ind = 0
while ind < (len(word)-1):
if word[ind] == word[ind+1]:
double = double+1
ind = ind+2
else:
ind... |
phone=input("请输入手机号")
list=[151,186,153,139,156,187]
try:
int(phone)
if(len(phone)==11):
head=phone[:3]
bool=False
for i in list:
if(int(head)==(i)):
bool=True
break
if(bool):
print("合格")
else:
print("不合格... |
# my_list = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
# # my_list="hello"
# print(len(my_list))
# print(my_list[0:-1])
# a = [1, 2, 3]
# b = (5, 6, 7)
# u, s, t = b
# x, y, z = a
# print(x)
# print(y)
# print(z)
# print(u)
# print(s)
# print(t)
#
# a = [1,2,3]
# del a[0]
# print(a)... |
# 5.9 (Palindrome Tester) A string that’s spelled identically backward and forward, like
# 'radar', is a palindrome. Write a function is_palindrome that takes a string and returns
# True if it’s a palindrome and False otherwise. Use a stack (simulated with a list as we did
# in Section 5.11) to help determine whether a... |
import os
def main( argv ):
"""Main entry point for processing the file."""
if ( len(argv) > 1 ):
text_filename = argv[1]
if ( os.path.exists(text_filename) and os.path.isfile(text_filename) ):
print("Opening file...")
file_object = open(text_filename, 'r')
lines = file_object.readl... |
'''
used to pass a keyworded, variable-length argument list
A keyword argument is where you provide a name to the variable as you pass it into the function.
One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it.
**kwargs differs from *args in that you will need ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.