text stringlengths 37 1.41M |
|---|
def leftRotate(arr, n, k):
# To get the starting point of rotated array
mod = k % n
s = ""
# Prints the rotated array from start position
for i in range(n):
print(str(arr[(mod + i) % n]),end=" ");
return
# Driver program
a, k = input().split()
arr = list(map(int, input().rstrip().spl... |
"""
Robb Doering
robbwdoering@gmail.com
This program fetches the records of individual congress members that are currently
in office. It can be asked about who a certain member is, how their voting history compares
to those of any individual colleague, or their committee memberships.
For publishing on the Amazon Alexa... |
'''
Generate edges on a graph using preferential
attachment. The first node is selected randomly and
the second is selected using preferential attachment.
'''
import networkx as nx
import random as rand
import sys
import matplotlib.pyplot as plt
NODES = 100
STEP = 5
list_to_randomize = []
def add_preferential_edge(n... |
import multiprocessing
import time
def worker(d, key, value):
d[key] = value
def reader(d):
while True:
for k ,v in dict(d).items():
print(k)
time.sleep(1)
if __name__ == '__main__':
mgr = multiprocessing.Manager()
d = mgr.dict()
jobs = [ multiprocessing.Process(target=... |
import math
def sieveOfErat(n):
import math
primes = [True] * (n+1)
primes[0] = False
primes[1] = False
for i in range(2, int(math.sqrt(len(primes)))):
if primes[i]:
for j in range(i*i, len(primes), i):
primes[j] = False
return [i for i in range(len(primes)) if primes[i]]
def DimensionDistance(a, b,... |
def substring(A, B):
A = str(A)
B = str(B)
for b in B.split():
if not b in A.split():
return 0
return 1
elements of computing
|
__author__ = 'sunary'
class SortedWords():
def __init__(self):
self.words = []
def set(self, sorted_list):
self.words = sorted_list
def add(self, word=None, list_word=None):
'''
add word or list of words to sorted list
Args:
word: the word need to ad... |
"""
The Western Suburbs Croquet Club has two categories of membership, Senior and Open.
They would like your help with an application form that will tell prospective members which category they will be placed.
To be a senior, a member must be at least 55 years old and have a handicap greater than 7.
In this croquet clu... |
def counVowels(str):
vowels = 0
for i in str.lower():
if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
vowels = vowels + 1
print("The Vowels in the String <",str,"> are : ",vowels)
str = input("Enter an String : ")
counVowels(str) |
from copy import deepcopy
from os import system
from queue import Queue
from random import randint, seed
MAX_COL = 4
MAX_ROW = 4
SHUFFLE_MAGNITUDE = 20
class board:
""" game board """
def __init__(self):
""" construct a board """
self.goal = [[" 1", " 2", " 3", " 4"],
[... |
# dict 활용
# dict 과 map, zip을 이용해봅시당
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
#
#
# input
# 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 221 222 223 224 225 226
# XYZ
# output
# 456
# 일의 자리수만 뽑아서 매칭
my_dict = dict()
before = [chr(ord('A')+i) for i in range(26)]
# A B C D E F G H I J K L M ... |
#!usr/bin/python
#This is an attempt at making a shut the box game!
import sys
import pygame
import random
pygame.init()
size = width, height = 1200, 800
black = (0,0,0)
white = (255,255,255)
red = (255, 0, 0)
green = (0,255,0)
blue = (0, 0, 255)
turquoise = (0, 100, 155)
screen = pygame.display.set_mode(size)
py... |
import numpy as np
a = np.arange(10)**2
print(a)
#perkalian matrix
a = np.array (([1,2],
[3,4]))
b = np.ones([2,2])
print ("matrix a:")
print (a)
print(b)
c1 = np.dot(a,b)
c2 = a.dot (b)
print("matrix c:")
print(c1)
print("matrix c2:")
print(c2)
a1 = np.array(([1,2,3],
[4,... |
import numpy as np
a = np.arange(10)**2
print(a)
#slicing
print ('elemen dari 1-6 adalah',a[0:6])
print ('elemen dari 4 sampai akhir', a[3:1])
print ('elemen dari awal sampai 5', a[:5]) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Time complexity: Sum all integers of an interval [a,b]."""
import time
def iterative_sum(num_list):
"""Calculate the sum using a for loop and acumulator variable."""
start_time = time.time()
total = 0
for num in num_list:
total += num
lapse... |
#注册
from User import User
from UserList import UserList
class ShoopingSystem:
@staticmethod
def register():
userName = input("请输入用户名:")
password = input("请输入密码:")
C_password = input("请在此输入密码:")
userList = UserList()
if len(userName) == 0 or len(password) == 0 or password... |
#!/usr/bin/env python3
# nrooks.py : Solve the N-Rooks, N-Queens and N-Knights problem!
# Based on the Prof. David Crandall's starter code
# Created by Varun Miranda, 2018
# a0.py : Solve the N-Rooks, N-Queens and N-Knights problem!
#Citations :
#https://docs.python.org/3/library/functions.html - implementing the zi... |
#!/usr/bin/python
# Quick Sort class that allows for O(lg 2 n) to O(n^2) sorting of items,
# depending on where pivot picked happens to be within context of all sorted items
# Low memory overhead as it simply swaps items during comparisons
class QuickSort:
def __init__(self, items):
self.items = items
def ... |
# A library containing methods to generate random names.
from random import choice
def _to_list(filename):
names = []
with open(filename, 'r') as f:
for line in f:
names.append(line.rstrip())
return names
male_names = _to_list('malenames')
female_names = _to_list('femalenames')
su... |
##Leira Salene 1785752
import math
paintColor = {
'red' : 35,
'blue' : 25,
'green' : 23
}
height = float(input('Enter wall height (feet):\n'))
width = float(input('Enter wall width (feet):\n'))
wallArea = height * width
print ('Wall area: {:.0f} square feet'.format(wallArea))
paint = wall... |
#6
r=int(input('Enter radius:'))
pi=3.14
a=pi*r*r
print('The area of circle:',a)
|
num = 10
stars = 0
blanks = 10
while num >= 0:
print(" "*blanks+"*"*stars)
blanks -= 1
stars += 1
num -= 1
print("You're welcome!")
|
class Product:
def __init__(self, nm, nb):
self.name = nm # unikalna
self.number = nb # ile mamy na stanie
def __str__(self):
return f'{self.name}: {self.number}'
class Warehouse:
def __init__(self, local_account):
self.products = {} # warehouse status - key - name, val... |
age = 18
if age >= 18:
print("You can vote")
print("Mature")
elif age < 18:
print("Not mature")
else:
print("Ok bye")
print("Ok i am done")
|
# Author : Nihar Kanungo
import math
'''
A regular strictly convex polygon is a polygon that has the following characteristics:
all interior angles are less than 180
all sides have equal length
This class facilitates creation of objects which can get the properties
edges
vertices
... |
# General Functions for String Operations.
# Liu Dezi
from astropy.io import fits
import os, sys
def read_param(filename):
"""
Read a parameter configuration file, and save the parameters into
a python directory structure.
Parameter:
filename: the input configuration file name.
NOTE: The for... |
#!/bin/bash/python
def listOfEvenNums():
l1 = [i for i in range(100,2000,2)]
print l1
def mergeTwoLists():
l1 = [i for i in range(1,10)]
l2 = [i for i in range(1,20,2)]
l3 = l1 + l2
l4 = list(set(l1 + l2)) #removing of duplicate elements
print l3
def multiplyLists():
l1 = []
l2 = [[1]*3] #here the elements... |
""" A program that stores and updates a counter using a Python pickle file
@author: Colvin Chapman
"""
from os.path import exists
import sys
import pickle
def update_counter(file_name, reset=False):
""" Updates a counter stored in the file 'file_name'
A new counter will be created and initialized to 1 i... |
# 工厂方法 模式,比 简单工厂 模式 更符合“开-闭”原则。
#1. 抽象工厂类
class Factory(object):
def getProduct(self): #必须要有某个方法
return Product()
#2. 抽象产品类
class Product(object):
pass
#3. 具体产品
class ProductA(Product):
def say(self):
print("Product A")
class ProductB(Product):
def say(self):
print("Product B... |
#一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
#一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
def f(i):
return i*i;
def f2(i):
return i/2;
a1=add(1,4,f)
a2=add(1,4,f2)
print(a1);
print(a2); |
# 返回函数,可以实现预定义
def getSpliter(pattern):
#内函数能对外函数(不是在全局作用域)的变量进行引用,内部函数就被认为是闭包
def split_str(str):
import re;
return re.split(pattern,str);
return split_str;#返回的是内函数
# 定制化spliter
spliter_tab=getSpliter(r'\t')
spliter_e=getSpliter(r'e')
# 使用spliter
print(spliter_tab)
s2="name\tage\tgrade\t... |
#一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
#一个最简单的高阶函数:
def add(x, y, f):
return f(x) + f(y)
def f(i):
return i*i;
print( add(1,4,f) )
#http://research.google.com/scholar/mapreduce-osdi04.pdf |
# 广度优先算法:
# 维护一个队列,先加入一度节点;
# 遍历,如果找到了就停止;没找到,就弹出,并把其好友添加到队列末尾。
# 直到返回,或者找不到。
#
# 这个粗糙的实现有个问题,就是有人(peggy) 被查询了2次。
# 首先同一个元素检查2次是在浪费时间,其次这有可能陷入死循环,如果两个人互为好友。
# 应该使用一个表格,记录检查过的元素。
# 创建图
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["t... |
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 100000: # 退出循环的条件
raise StopIteration();
retu... |
# 分而治之: 数组求和,递归法;
def sumArr(arr):
sum=0;
for i in arr:
sum+=i
return sum
print(sumArr([2,4,6]))
# 方法二,使用递归,数组长度为1或0时返回,否则拿出一个值加上其余 求和数组
def sumArr2(arr):
if len(arr)==0:
return 0
else:
return arr[0] + sumArr2(arr[1:])
print(sumArr2([2,4,6]))
|
import re
# 用正则表达式切分字符串比用固定的字符更灵活
r='a b c'.split(' ')
print('1: ',r)
#['a', 'b', '', '', 'c']
#无法识别连续的空格,用正则表达式试试:
r=re.split(r'\s+', 'a b c')
print('2: ',r)
# ['a', 'b', 'c']
#无论多少个空格都可以正常分割。
#加入,试试:
r=re.split(r'[\s\,]+', 'a,b, c d ,e fg')
print('3: ',r)
#再加入;试试:
r=re.split(r'[\s\,\;]+', 'a,b;; c d')
p... |
# 选择排序
arr=[20,1,6,100,5]
# 返回最小元素的下标
def findSmallest(arr):
small=arr[0]
index=0
for i in range( len(arr)):
if small> arr[i]:
small=arr[i]
index=i;
return index
# use this function in sorting
def searchSort(arr):
arr2=[]
for i in range( len(arr) ):
pri... |
#支持函数嵌套
def add3(a,b,c):
#内部函数
def add2(x,y):
return x+y
return add2(add2(a,b),c)
print(add3(1,2,3))
|
# 广度优先算法:
# 维护一个队列,先加入一度节点;
# 遍历,如果找到了就停止;没找到,就弹出,并把其好友添加到队列末尾。
# 直到返回,或者找不到。
from re import search
#
# v2: 为了避免死循环,要记录搜寻过的元素,并跳过它。
# 另一个更新,是把函数封装的更好:传入图和要查找的起始点。
# 创建图
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
... |
#if语句
a=110;
if a>0:
if a>100:
print(">100")
elif a>10:
print('>10')
else:
print('>1')
elif a<0:
print('<0')
else:
print('=0')
# 数据类型
mytype=type("this is a book")
mytype2=type(50.3)
print(mytype,' ',mytype2)
#使用if判断数据类型
if type("string") is str:
print("Yes,a string")
else:
print("No, not a string"... |
# 汉诺塔思想笔记
# 认识汉诺塔的目标:把A柱子上的N个盘子移动到C柱子,可以使用中间柱子B,小盘必须在大盘上面。
# 递归的思想就是把这个目标分解成三个子目标
# 子目标1:将前n-1个盘子从a移动到b上
# 子目标2:将最底下的最后一个盘子从a移动到c上
# 子目标3:将b上的n-1个盘子移动到c上
# 然后每个子目标又是一次独立的汉诺塔游戏,也就可以继续分解目标直到N为1
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b)# 子目标1
move(1, a, b... |
def addEnd(L=None):
if L is None:
L=[]
L.append('END')
return L
a1=addEnd([1,2,3])
print(a1);
b1=addEnd();
b2=addEnd();
b3=addEnd();
print(b1);
print(b2);
print(b3);
print(a1); |
def now():
print('2015-3-25')
f = now
f()
print('now: ', now )
print('now.__name__: ', now.__name__ )
print('f: ', f )
print('f.__name__: ', f.__name__ )
#现在,假设我们要增强now()函数的功能,
#比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,
#这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
# OOP的装饰模式需要通过继承和组合来实现,而Python除了能支持OOP的decorator外,直接从语法层次... |
def fact(x):
if x<=1:
return 1;
else:
if debug:
print(x)
return x*fact(x-1)
debug=True
x=fact(5)
print(x)
|
#嵌套来模仿二维数组
L=[
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
]
#调用元素
print(L[0][1]); #Google
#元素长度
print('Before append:', len(L));
#在末尾添加元素
L.append(['Adam', 'Bart', 'Lisa'])
print('After append:', len(L));
#删除元素
print(L)
del L[2][-1] #删除序号是2的list中的最后一个元素
print(L)
print("abou... |
# Queue和Pipe只是实现了数据交互,并没实现数据共享。
# 即一个进程去更改另一个进程的数据。那么就要用到Managers
from multiprocessing import Process, Manager
def fun1(dic, lis, index):
dic[index] = 'a'+str(index)
dic['2'] = dic.get("2","")+ '_'+str(index)
lis.append(index) #[0,1,2,3,4,0,1,2,3,4,5,6,7,8,9]
print(index)
if __name__ == '__mai... |
u"""
Write a program that outputs the file_names of duplicate files.
"""
__author__ = "Diana Rusu"
__email__ = "diana.russu.87@gmail.com"
import os
import sys
from collections import defaultdict
import hashlib
def find_files_with_same_size(folder_to_check):
"""Find files that have the same size."""
file_size... |
def isPalindrome(s, ignorecase=False):
"""
>>> type(isPalindrome("bob"))
<type 'bool'>
>>> isPalindrome("abc")
False
>>> isPalindrome("bob")
True
>>> isPalindrome("a man a plan a canal, panama")
True
>>> isPalindrome("A man a plan a canal, Panama")
False
>>> isPalindrome... |
def find_it(seq):
numbers = {}
scanNumbers = (x for x in seq)
for x in scanNumbers:
if x in numbers:
numbers[x] = numbers[x] + 1
else:
numbers[x] = 1
it = next((k, v) for k, v in numbers.items() if v & 1)
return it[0]
print(find_it([20,1,1])) |
def comp_v1(array1, array2):
if (array1 is None and array2 is not None) or (array1 is not None and array2 is None):
return False
if len(array1) != len(array2):
return False
for num in array1:
try:
array2.remove(num**2)
except:
return False
return T... |
from linked_list import LinkedList
"""
Given a linked list which might contain a loop, implement an
algorithm that returns the node at the begining of the loop (if exists)
"""
# time complexity: O(n), space complexity: O(1)
def get_loop_head(list):
if list.head == None:
return None
fast_node = list.h... |
#Given a string, write a function to check if it is a permutation of a palindrome.
def get_char_to_count_map(str):
charToCount = {}
for char in str:
if char == ' ':
continue
elif char in charToCount:
charToCount[char] = charToCount[char] + 1
else:
char... |
# This program converts integers and fractions into binary numbers.
x = float(input("Think of a number for binary conversion : "))
numint = int(str(x).split(".")[0])
numffloat = float("."+str(x).split(".")[1])
p = 0
while (numffloat*(2**p))%1 != 0:
#print("remainder : " + str(numf*(2**p)- int(numf*(2**p))))
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
def plot_data(x, y):
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.plot(x, y, 'rx', markersize=6)
plt.show()
|
from itertools import cycle
from random import choice
from tic_tac_toe import tic_tac_toe_winner
board = " " * 9
symbol = cycle("XO")
while " " in board:
field = choice([n for n, s in enumerate(board) if s == " "])
board = board[:field] + next(symbol) + board[field + 1 :]
print(board)
winner = tic_ta... |
# -*- coding: utf-8 -*-
from sys import argv
from time import time
"""variation of dijkstras shortest path algorithm that searches route between cities that caries heaviest loads
comments in finnish for the finnish teacher"""
# lukee kartta tiedoston
def read_roads(name):
# phase määrää lukeeko ohjelma ensinmäisä ... |
print(float(4.6))
print(int(4.6))
print(int(3.7))
print(int(4.5))
print(int(4))
print(int(5))
print(float("three"))
#a.float(4.6) comes out as 4.6 but int(4.6) comes out as 4
#b.int(3.7) turns into 3
#c.int(4.5) turns into 4 so no, but int(4 and 5) works
#d.it dosen't work because three point six is a str() |
prime = [1]
GivenNumber = 600851475143
IterNumber = GivenNumber
idx = 2
while idx <= IterNumber:
if IterNumber % idx == 0:
IterNumber = IterNumber / idx
prime.append(idx)
#print(prime)
#print("New prime is: " + str(idx))
idx = idx + 1
Prime_Max = 1
for idx in prime:
... |
store = ["Name", "color", "x"]
y = input("What's your name? ")
store[0] = y
z = input("What is your favorite color? ")
store[1] = z
a = input("How many pets do you have? ")
store[2] = a
print(store[0] + "'s favorite color is " + store[1] + ". They have " + store[2] + " pets. ") |
# HOMEWORK: LESSON 1 : PRINTING AND SIMPLE ARITHMETIC
#
print("What is your name?")
print("My name is Li Zhang")
s = input("What is your age?")
print("I am " + s + " years old")
print("Or say I am " + str(int(s) * 12) + " months old")
|
age = int(input("What is your age? "))
age = age + 1
print("You will be " + str(age) + " next year") |
def dividing_func(x , y):
return x % y
x = int(input("Please input a dividend (number): "))
y = int(input("Please input a divisor (number): "))
if dividing_func(x , y) == 0:
print("The number " + str(x) + " is divisible by " + str(y) + ".")
else:
print("The number " + str(x) + " is not divisible by " +... |
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0
W = capacity
# write your code here
# print(capacity, weights, values)
while W > 0:
max_value = -1
index = len(weights)
for i in range(0, len(weights)):
if weights[i] != 0 and ... |
# Uses python3
import sys
import random
import math
def binary_search(a, x):
left, right = 0, len(a)-1
# if right == 0:
# return -1
# # write your code here
# mid = (right + left) // 2
# if a[mid] == x:
# return mid
# elif a[mid] > x:
# return mid - binary_search(a[left... |
# Write a program to create a table of word frequencies by genre, like the one given in Section 2.1 for modals. Choose your own words and try to find words whose presence (or absence) is typical of a genre. Discuss your findings
import nltk
from nltk.corpus import brown
cfd = nltk.ConditionalFreqDist(
(genre,word.lo... |
class Grade:
def __init__(self, kor, math, eng):
self.kor = kor
self.math = math
self.eng = eng
def sum(self):
return self.kor + self.math + self.eng
def avg(self):
return self.sum()/3
def get_grade(self):
score = int(self.avg())
# grade = ''
... |
class CalculatorConstructor:
# 생성자
def __init__(self, first, second): # init 메소드라 불린다.
self.first = first
self.second = second
def add(self):
return c.first + c.second
def sub(self):
return c.first - c.second
def mul(self):
return c.first * c.second
d... |
inp = input('Enter file name to open: ')
mylist = list()
try:
fh = open(inp)
except:
print('Sorry! Can\'t open file ')
quit()
for line in fh:
words=line.split()
for word in words:
if word not in mylist:
mylist.append(word)
else:
continue
mylist=sorted(mylist) ... |
hours = input('Enter Hours:')
rate = input('Enter Rate:')
fhours=float(hours)
frate=float(rate)
if fhours>40:
pay = fhours*frate
epay = (fhours-40)*0.5*frate
tpay = pay+epay
else:
tpay=fhours*frate
print('Pay:',tpay)
|
time = float(input("Input time in minutes: "))
if (time<60):
hour=0
minutes=time
else:
hour=time/60
minutes=time%60
print("h:m-> %d %d" % (hour, minutes))
|
x = raw_input('Enter the string: ')
y = int(input('no of times: '))
def mul(a,b):
z = a*b
print z
mul(x,y)
|
a=int(input("Enter a 5 digit number"))
s=0
while(a!=0):
r=a%10
s=s*10+r
a//=10
print(s)
|
def countPairs(N1,N2,s):
c=0
for i in N1:
if s-i in N2:
c+=N2.count(s-i)
return c
N1=list(map(int,input("Enter elements of list1").split()))
N2=list(map(int,input("Enter elements of list2").split()))
s=int(input("Enter sum"))
print(countPairs(N1,N2,s))
|
n=int(input("Enter the no of batsmen"))
batsmen={}
print()
for i in range(1,n+1):
print("Enter the details of player:"+str(i))
batsmen[i]={'type':input("type"),'name':input("name"),'matches':input("no.of matches played"),'runs':input("runs scored"),'average':input("average score"),'highest score':input('hi... |
matrix=[[j for j in range(5)]for i in range(5)]
print(matrix)
flatten_matrix=[val for sublist in matrix for val in sublist]
print(flatten_matrix)
print()
matrix=[[j for j in range(10)]for i in range(5)]
print(matrix)
print()
flatten_even=[val for sublist in matrix for val in sublist if val%2==0]
print(flatte... |
from abc import ABC, abstractmethod
# class Animal(ABC):
# def correr(self):
# print('Correr')
#
# @abstractmethod
# def respirar(self):
# pass
#
#
# class Cao(Animal):
# def respirar(self):
# print('Respirar como um cão')
#
#
# class Passaro(Animal):
# def respirar(self):
... |
"""
Original Sourcecode pulled from:
https://thadeusb.com/weblog/2010/10/10/python_scale_hex_color/
"""
def clamp(val, minimum=0, maximum=255):
if val < minimum:
return minimum
if val > maximum:
return maximum
return val
def color_scale(hex_str, scale_factor):
"""
Scales a hex s... |
import turtle
import math
import time
import random
import ball
from ball import Ball
turtle.bgcolor("black")
turtle.tracer(00)
turtle.hideturtle()
RUNNING = True
SLEEP = 0.0077
SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2
#determines balls defenitions
NUMBER... |
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
#please remove above 3 lines if you are using teminal for input and output
def merge(li1,li2):
total = len(li1) + len(li2)
n = len(li1)
m = len(li2)
outLi = [0]*total
i = 0
j = 0
k = 0
while i < total :
if(k == m or (j < n and... |
n = input().split(" ")
len = len(n)
lis = []
ans = 0
i = 0
while i < len :
ele = int(n[i])
ans = ans ^ ele
i = i + 1
lis.append(ele)
print("In the list ", lis, "unique element is", ans)
## LOGIC :
''' If you remember if you XOR any element with itself
answer will be zero
and if you will XOR a... |
## given a sorted list and an integer x
## find the first value in the list which is grater or equal to x
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
def findElement(li, tar):
n = len(li)
start = 0
end = n-1
while(start <= end):
mid = start + (end-start)//2
if ta... |
numbers=int(input())
for i in range(numbers):
for k in range(i,-1, -1):
print('Осталось секунд:', k)
print('Пуск', i+1) |
nums = input().split()
from_to = input().split()
squares_of_nums = [int(i)**2 for i in nums]
from_to = [int(i) for i in from_to]
print(sum(squares_of_nums[from_to[0]:from_to[1]+1]))
|
from yandex_testing_lesson import is_correct_mobile_phone_number_ru
ans = ''
numbers = ['+7(900)1234567', '8(900)1234567', '+7 999 123-45-67',
'+7-999-123-45-67', '8 (900) 123 45 67']
for i in numbers:
if is_correct_mobile_phone_number_ru(i):
ans = 'YES'
else:
ans = 'NO'
... |
word= input()
while True:
if word[0] == 'А' or word[0] == 'а':
print('ДА')
break
if word[0] != 'А' or word[0] != 'а':
print('НЕТ')
break
|
from yandex_testing_lesson import is_prime
ans = ''
prime_nums = ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31',
'83', '89', '97', '101', '103', '107', '109']
for i in prime_nums:
if is_prime(i) in prime_nums:
ans = 'YES'
else:
ans = 'NO'
complicated... |
city=input()
city1=input()
while True:
if city[-1] == 'ь':
city=city[:-1]
if city[-1] == city1[0]:
print('ВЕРНО')
break
else:
print('НЕВЕРНО')
break |
num=int(input())
search=[]
for i in range(num):
search.append(input())
n=int(input())
search_words=[]
final=[]
for i in range(n):
search_words.append(input())
for i in range(len(search)):
there_is_search_word=True
for j in range(len(search_words)):
if search_words[j] not in search[i]... |
import string
skip_window=2
f=open('./aesop10.txt','r')
l=list(f)
original_text=[]
for x in l:
original_text=original_text+x.split(' ')
n_wordLine=len(original_text)
new_text=[]
# print original_text
pos=string.punctuation.find('.') # position of the period
punc_Period=string.punctuation[0:pos]+string.punctuation... |
# https://www.lintcode.com/problem/edit-distance/description
# 区间型DP要从最大状态开始想,类似分治。从小到大的DP用循环,从大到小的DP用记忆化搜索
class Solution:
"""
@param word1: A string
@param word2: A string
@return: The minimum number of steps.
"""
def minDistance(self, word1, word2):
# write your code here
... |
# 총점, 평균, 학점
name='name'
kor=90
mat=70
eng=90
def getTotal():
#pass - 함수 작성전 쓰는 더미코드!
total = kor+mat+eng
return total
def getAverge():
total=getTotal()
average=total/3
return average
def getGrade():
average=getAverge()
grd='가'
if average > 100 or average >= 90:
grd='수'
... |
class Card():
"""
Base card class
"""
type: str
value: int
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
display = f"{self.type}\t\t"
if 1 <= self.value <= 10:
display += str(self.value)
elif sel... |
from Oving8.ship import Ship
class Position:
shot: bool
__ship: Ship
def __init__(self, x_position, y_position):
self.x_position = x_position
self.y_position = y_position
self.shot = False
self.__ship = None
@property
def is_taken(self):
return self.__ship... |
from circle import Circle
if(__name__ == "__main__"):
first_circle = Circle(4, 4, 5)
second_circle = Circle(14, 5, 5.1)
third_circle = Circle(7, 15, 6)
fourth_circle = Circle(9.35, -0.58, 2.04)
print(first_circle)
print(second_circle)
print(third_circle)
print(fourth_circle)
print... |
# -*- coding:utf8 -*-
import os
def rename(dirpath):
path = dirpath
filelist = os.listdir(path) # 该文件夹下所有的文件(包括文件夹)
try: # (第二次改名的话,一定要排序,因为os.listdir生成的元素是随机的,第二次改名(os.rename函数)会将第一生成的同名文件覆盖,导致总文件数目变少)
filelist.sort(key=lambda x: int(x[:-4]))
print "文件有序"
retu... |
import sys # print("Debug messages...", file=sys.stderr)
import math
root = {}
count = 0
n = int(input())
for _ in range(n):
print("root", root, file=sys.stderr)
current = root
phone_number = input()
for number in phone_number:
if number not in current:
current[number] = {}
... |
from typing import List
# Name: Split Array Largest Sum
# Link: https://leetcode.com/problems/split-array-largest-sum
# Method: Dynamic programming, keep track of dp[partitions][to index] (alternatively, greedy binary search)
# Time: O(n^2 \* m)
# Space: O(n \* m)
# Difficulty: Hard
class Solution:
def splitArra... |
from typing import List
class Solution:
def maxLength(self, arr: List[str]) -> int:
combo_list = [set()]
for x in arr:
if len(set(x)) != len(x):
continue # duplicates smh
x_l = set(x)
for combo in combo_list:
# If no... |
from typing import List
import unittest
from collections import defaultdict
# Name: Subarray Sum Equals K
# Link: https://leetcode.com/problems/subarray-sum-equals-k/
# Method: Prefix sum, store number of ways to get to a sum, check against target
# Time: O(n)
# Space: O(n)
# Difficulty: Medium
class Solution:
d... |
#!/bin/python3
import sys
n = int(input().strip())
height = [int(height_temp) for height_temp in input().strip().split(' ')]
height.sort()
height.reverse()
maxCand =1
while(True):
if(maxCand >= len(height) or height[maxCand-1]!=height[maxCand]):
break
maxCand+=1
print(maxC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.