text stringlengths 5 121k |
|---|
import random
import math
def fillList(count) :
list = []
for i in range(0, count) :
list.append(random.randint(0,10))
return list
def printList(lst) :
for val in lst:
print(val)
def sumList(lst) :
sum = 0
for val in lst:
sum += val
return sum
myList = fillList(25... |
import math
print('This calculator requires you to enter a function and a number')
print('The functions are as follows:')
print('S - sine')
print('C - cosine')
print('T - tangent')
print('R - square root')
print('N - natural log')
print('X 0- eXit the program')
f, v = input("Please enter a function and a value ").spl... |
import random
def createList(count) :
list = []
for i in range(0, count) :
list.append(random.randint(1,100))
return list
def printList(lst) :
for val in lst:
print(val)
def smallLarge(lst) :
smallest = lst[0]
largest = lst[0]
for val in lst:
if smallest > val :
... |
import math
print("This program calculates the area of any circle")
r=input("Please enter a radius in cm: ")
n=int(r)
r=(n**2)*math.pi
print(str(r)+" cm^2")
print("x")
|
import random
def fun():
total = 0
for i in range(0, 11):
i = random.randint(0, 1000)
total += i
print("The total sum of the 10 numbers is: ", total)
fun()
|
def fun2(number, odd=True):
if number % 2 == 0:
odd = False
print(number, "is an even number!")
else:
print(number, "is an odd number")
i = input("Please enter a number: ")
n = int(i)
fun2(n) |
class Shingle():
def wordshingling(self, word):
shingle = []
for i in range(0, len(word) - 2):
shingle.append(word[i] + " " + word[i + 1] + " " + word[i + 2])
return shingle |
import numpy as np
import matplotlib.pyplot as plt
def lorenz(x, y, z, s=10, r=28, b=2.667):
"""
Given:
x, y, z: a point of interest in three dimensional space
s, r, b: parameters defining the lorenz attractor
Returns:
x_dot, y_dot, z_dot: values of the lorenz attractor's partial
... |
nama = (input('Harap masukan nama anda: '))
jenis = (input('Harap masukan jenis kelamin anda P/L: '))
if jenis =="P":
print('Selamat datang, Bunda', nama )
else:
print('Selamat datang, Papah', nama )
print() |
x='3 + y*5'
print(x)
y=0
x = int(x)
print (x)
|
import argparse
import os
import subprocess
import sys
def create_parser():
parser = argparse.ArgumentParser(
description="Simple tool to find and delete hidden OS files like thumbs.db or ds_store.")
parser.add_argument("--d", dest="directory", default=os.getcwd(), type=str,
... |
import streamlit as st
@st.cache()
def calculate_emi(p,n,r):
n = n*12
r = r/12
emi = p*(r/100)*((1+(r/100))**n)/(((1+(r/100))**n)-1)
return round(emi,3)
def calculate_outstanding_balance(p,n,r,m):
n = n*12
r = r/12
R = (1+(r/100))
balance = (p*(R**n - R**m))/((R**n) - 1)
return round(b... |
class SearchSpacePrimitive(object):
pass
class IntSpace(SearchSpacePrimitive):
def __init__(self, from_int, to_int, default=None):
self.from_int = from_int
self.to_int = to_int
self.default = default
def __str__(self):
return "IntSpace(from_int={}, to_int={})".format(self.... |
565645
"""
Created on Sat Sep 10 18:17:16 2016
@author: frederico
"""
x = int(input('Enter an integer:'))
if x%2 == 0:
print('Even number.')
else:
print('Odd number.')
print('Finished execution.') |
"""
Created on Sat Sep 10 19:59:32 2016
@author: frederico
"""
str1 = 'hello'
str2 = ','
str3 = 'world'
print('str1: ' + str1)
print('str1[0]: ' + str1[0])
print('str1[1]: ' + str1[1])
print('str1[-1]: ' + str1[-1])
print('len(str1): ' + str(len(str1)))
|
"""
Created on Mon Sep 26 18:43:20 2016
@author: frederico.x.silva
"""
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
lower = ""
higher = ""
middle = ""
midPos = 0
if len(aStr... |
grid = [
['.', '.', '.', '.', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['0', '0', '0', '0', '.', '.'],
['0', '0', '0', '0', '0', '.'],
['.', '0', '0', '0', '0', '0'],
['0', '0', '0', '0', '0', '.'],
['0', '0', '0', '0', '.', '.'],
['.', '0', '0', '.', '.', '.'],
['.', ... |
import os
import sys
import PyPDF2
from PyPDF2.utils import PdfReadError
def encrypt(folder_path, password):
"""
Encrypts all pdf files in given directory with given password
:param folder_path: String
:param password: String
:return: None
"""
os.chdir(folder_path)
f... |
def collatz(num):
print(num)
while num != 1:
if int(num) % 2:
num = 3 * num + 1
else:
num = num // 2
print(num)
user_num = input('Enter a number ')
collatz(user_num)
|
def bfs(G):
n = len(G)
for i in range(n):
queue = [i]
distances = [-1] * n
distances[i] = 0
visited = [False] * n
parent = [None] * n
while queue:
v = queue.pop(0)
for j in range(n):
if G[v][j] == 1 and not visited[j]:
... |
from queue import PriorityQueue
def bfs(graph, s, t, parent) -> bool:
queue = PriorityQueue()
visited = [False for _ in range(len(graph))]
queue.put(s)
visited[s] = True
while not queue.empty():
u = queue.get()
for idx in range(len(graph[u])):
if visited[idx] is False ... |
def cycle_util(graph, v, visited, parent):
"""
Utility function for cycle.
:param graph: representation of a graph as adjacency list.
:param v: current vertex.
:param visited: list of visited vertexes.
:param parent: list of vertexes' parents.
:return: boolean value for cycle function.
"... |
a = 1
while a<=5:
if a==3:
break
print("a=", a)
a += 1
else:
print("반복문 정상탈출")
print("반복문 강제탈출 ")
n = 0
while n<5:
n += 1
if n == 3:
continue
print("n=", n)
|
import sqlite3
class DBTools:
def __init__(self, dbname, table_name):
self.dbname = dbname
self.tablename = table_name
def createTable(self):
try:
conn = sqlite3.connect(self.dbname)
sql = 'create table if not exists {}(name var(20), ' \
'... |
class Test:
def __init__(self):
print("init call")
self.a = 0
self.b = 0
self.myDic = {}
def setData(self,x,y):
self.a = x
self.b = y
def show(self):
print(self.a, self.b)
def __repr__(self):
return f'a={self.a} b={self.b}'
d... |
a = 5
rst = 100 if a>0 else 200
print(rst)
rst = [200, 100][False]
print(rst)
rst = {True:100, False:200}[a>0]
print(rst)
score = input("점수 입력:")
score = int(score)
result = "합격" if score >= 70 else "불합격"
result=["불합격", "합격"][score>=70]
print(result)
|
a=3
a**=2
print(a)
n = 1
n +=1
print(n)
|
import re
s1 = 'apple kiwi banana straw'
s2 = 'apple kiwi banana application'
try:
my = re.findall('ap[a-z]+', s2)
print(my)
except Exception as err:
print("Not Found")
|
lst1 = [1,2,3,4,5,6,2,1,5,6,7,8,4,12,11,10,5,5,5,1,1,2,8]
no_duplicates=[]
duplicate_items=[]
print ("Original list is : ",lst1)
lst1.sort()
print("After Sorting : ",lst1)
duplicate_count = []
dup_count =0
for i in range(len(lst1)):
if(i==0):
no_duplicates.append(lst1[i])
else:
if ... |
import random
def generatekey():
keystore = open("key.txt", 'w')
word = input("Enter encryption word:")
length = len(word)
multiplier = random.randint(1,length)
key = length * multiplier
keystore.write(str(key))
keystore.close()
return(key)
def retrievekey():
keystore = open("ke... |
import sqlite3
class PhonebookModel:
def __init__(self):
self.con = sqlite3.connect('files/test.db')
self.cur = self.con.cursor()
def createTable(self):
self.cur.execute('''CREATE TABLE person
(id_person INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT , address TEXT)... |
'''
Generating Unique Codes for students. These codes are used for authentication when collecting student preferences.
Codes are sent to students by email. Students are required to enter this unique code when submitting the form.
Each unique code contains 8 characters, alphanumeric. 'Case Sensitive'.
'''
from random i... |
"""Tool to clean wordcounts files by removing the count."""
import argparse
def clean_word_counts(args):
"""Remove count from wordcounts file."""
with open(args.valid_words) as f:
valid_words = set(word.strip() for word in f)
with open(args.word_counts) as i, open(args.output, "w") as o:
... |
import math
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if(int(test)<0):
print("This program is for humans")
elif(int(test)<3 and int(test)>-1):
print("Still in Mama's arms")
elif(int(test)<5 and int(test)>2):
print("Preschool Maniac")
elif(int(test)<1... |
import math
def isPrim(zahl):
for i in range(3,(int)(zahl/2),2):
if(zahl%i==0):
return 0
return 1
primAnz=1
primSum=2
zahl=3
while primAnz<1000:
if(isPrim(zahl)==1):
primAnz+=1
primSum+=zahl
zahl+=2
print(primSum)
|
T = int(input())
if T < 1 and T > 10:
exit()
else:
for i in range(T):
S = input()
odd = ''
even = ''
for j in range(len(S)):
if j % 2 == 0:
odd = odd + S[j]
else:
even = even + S[j]
print(odd,even)
|
from mnist import MNIST
mndata = MNIST('.')
images, label = mndata.load_training()
print("Read all Images")
def makeBarcodes(images,label):
import matlab.engine
eng = matlab.engine.start_matlab()
import numpy as np
nrows = 28
ncols = nrows
numRays = 8
showRBC = 0
for index i... |
"""
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
"""
x = 10
y = 4
print(x & y)
print(x | y)
print(-x)
|
"""
Write a Python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
"""
def pattern_star_right_arrow_method1(n):
print('pattern_star_right_arrow_method1')
for i in range(n + 1):
print("* " * i)
for j in ran... |
d = {'A': 1, 'B' : 2}
print(d)
print(d.items())
print(d.keys())
print(d.values())
print(d.get('A'))
print(d['A'])
my_dict = {}
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
my_dict = dict({1:'apple', 2:'ball'})
print(my_dict)
my_dict = dict([(1,'appl... |
"""
Strings are immutable.
Forzensets are immutable version of the set
This means that elements of a string cannot be changed once they have been assigned.
We can simply reassign different strings to the same name.
"""
my_string = 'programiz'
"""
enumerate
The enumerate() function returns an enumerate object.
... |
singleLine = "Single line string"
multiLine = """ Multi line
string"""
print(singleLine)
print(multiLine)
print(float(5))
print(int(5.0))
print(float(0))
print(int(0.0))
print(float(-5))
print(int(-5.0))
print("#"*50)
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='\n')
pr... |
"""
Adding float in python PROBLEM
It turns out that the decimal fraction 0.1 will result in long binary fraction 0.1000000000000000055511151231257827021181583404541015625
and our computer only stores a finite number of it.
******* When to use Decimal instead of float? *******
# When we are making financial applicat... |
import os
import time
from selenium import webdriver
class FindElementBy:
def testFindElement(self):
driverLocation_windows = "C:\\Users\\aparida\\OneDrive\\Code\\Selenium\\chromedriver.exe"
driverLocation_mac = "anmolparida\OneDrive\Code\Selenium_Python\chromedriver... |
n1=input();
n2=input();
n3=input();
Largest = n1
if Largest < n2:
if n2 > n3:
print(n2,"is Largest")
else:
print(n3,"is Largest")
elif Largest < n3:
if n3 > n2:
print(n3,"is Largest")
else:
print(n2,"is Largest")
else:
print(n1,"is ... |
g_list = ["bread", "cheese", "milk", "juice"]
for g_list in range(3):
print(g_list)
|
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
salesDist = pd.read_csv('./stores-dist.csv')
salesDist = salesDist.rename(columns={'annual net sales':'sales','number of stores in district':'stores'})
sales = salesDist.drop(columns={'district... |
from cs50 import get_int
def get_height(min=1, max=8):
"""Prompt user for height value."""
while True:
height = get_int("Height: ")
if height >= min and height <= max:
return height
def print_pyramid(n):
"""Print n height of half-pyramid to console."""
for i in range(1, n... |
def is_palindrome(string:str)->bool:
"""Returns if the string is palindrome (True or False)"""
string= string.replace(" ","").lower()
return string == string[::-1]
def suma(a:int,b:int)->int:
return a+b
def main():
print(suma('2','3'))
print(is_palindrome(1000))
if __name__ == '__main__':
main() |
def climbingStairs(n):
a = [0, 1, 2]
for i in range(3,n+1):
a.append(a[i - 1] + a[i - 2])
return a[n]
|
inversion_count = 0
def inversion_counter_conquer(first, second):
"""[This function counts #inversions while merging two lists/arrays ]
Args:
first ([list]): [left unsorted half]
second ([list]): [right unsorted half]
Returns:
[tuple]: [(first: merged list of left and right halves... |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
email_data = dict()
for readfile in handle:
if not readfile.startswith ("From "):
continue
email_list = readfile.split()
email_only = email_list[1]
email_data[email_only]=email_data.get(email_only,... |
'''Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages.
You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Once... |
def starFormation1(n):
Kolom=0
Baris=n
i=0
while(i<=n):
j=0
while(j<Kolom):
print('*',end='')
j+=1
print('')
i+=1
Kolom+=1
starFormation1(4)
print()
def starFormation2(n):
Kolom=n
Baris=n
i=0
while... |
"""This is a simple port scanner built using the concept of sockets in python"""
import socket
import sys
import argparse
import pyfiglet
import os
"""This function is used to scan a given ip for a given open port"""
def portScanSingle(port,ip):
s=socket.socket()
try:
print ("[+] 4tt3mpting t0 c0nn3ct ... |
pat = raw_input()
n = int(raw_input())
for _ in range(n):
s = raw_input()
if '*' in pat:
a, b = pat.split('*')
ok = len(a+b) <= len(s) and s.startswith(a) and s.endswith(b)
else:
ok = s == pat
if ok:
print('Passar')
else:
print('Passar ekki')
|
import urllib3
from bs4 import BeautifulSoup
http = urllib3.PoolManager()
request_data = http.request('GET', 'https://in.hotels.com/search.do?resolved-location=CITY%3A1506246%3AUNKNOWN%3AUNKNOWN&destination-id=1506246&q-destination=New%20York,%20New%20York,%20United%20States%20Of%20America&q-rooms=1&q-room-0-adults... |
for i in range(1,11):
print("Tabla del " + str(i) + ":")
print("---------------------------")
for j in range(1,11):
print(i,"por",j,"es",i*j)
print("\n")
|
import itertools
from math import gcd
from input_reader import read_moons
class Moon1D:
def __init__(self, x, v=0):
self.x = x
self.v = v
def __repr__(self):
return f'<Moon1D {self.x} -> {self.v}>'
def __eq__(self, other):
return (self.x == other.x and self.v == other.v)... |
lst = []
n = int(input("Enter the number of inputs: "))
for i in range(0, n):
ele = input()
lst.append(ele)
lst.sort(reverse = True)
print(lst)
|
import docx
from docx.shared import Pt
class Template:
def __init__(self, user, file_name):
self.user = user
self.file_name = file_name
self.document = docx.Document('../files/template.docx')
def create_template(self):
doc = self.document
... |
def uniq_add(my_list=[]):
sum_unique = my_list[0]
n = 0
for i in range(1, len(my_list)):
for j in range(i):
if my_list[i] == my_list[j]:
n = 0
break
else:
n = my_list[i]
sum_unique += n
return (sum_unique)
|
from string import Template
nome, idade = "Ana", 30
print("Nome: %s Idade: %d %r %r" % (nome, idade, True, False))
print("Nome: {} Idade: {}".format(nome, idade))
print(f'Nome: {nome} Idade: {idade}')
s = Template('Nome: $nome Idade: $idade')
print(s.substitute(nome =nome, idade = idade)) |
for i in range(1, 11):
if i == 6:
break
print(i)
else:
print("Fim") |
def getDiaSemana(dia):
dias = {
1: "Domingo",
2: "Segunda",
3: "Terca",
4: "Quarta",
5: "Quinta",
6: "Sexta",
7: "Sabado"
}
return dias.get(dia, "Dia Invalido")
def getTipoDia(dia):
if dia == 1 or dia == 7:
return "Fim de se... |
class Data:
def __init__(self, dia = 1, mes = 1, ano = 1970):
self.dia = dia
self.mes = mes
self.ano = ano
def __str__(self):
return f"{self.dia}/{self.mes}/{self.ano}"
if __name__ == "__main__":
d1 = Data(ano = 2020)
print(d1) |
def prime(x):
m = x // 2
for i in range(2, m + 1):
if x % i == 0:
return False
return True
def compo(x):
lst = []
keep = x
start = 2
while x != 1:
if x % start != 0:
start += 1
if start % 2 == 0 and start != 2:
start += 1
... |
from house import House
from battery import Battery
class Cable(object):
def __init__(self, house, battery):
self.house = house
self.battery = battery
self.route = route
def distance(self):
"""
Calculates a route between battery and house
according to the manha... |
class Battery(object):
def __init__(self, id, x_pos, y_pos, capacity):
"""
Initializes an Item
"""
self.id = id
self.x_battery = int(x_pos)
self.y_battery = int(y_pos)
self.capacity = float(capacity)
self.capacity_available = 0
def __str__(self):... |
def change_possibilities(amount, denominations):
"""
Computes the number of ways to make amount of money with coins of the available denominations.
Dynamic space efficient programming solution
"""
if (len(denominations) == 0) or (amount < 0):
return 0
results = [0 for x in ra... |
fake = False
empty = None
stmt = 0
f = 69
k = 420
hz = [60, 75, 90, 120, 144, 240, 360]
if k > f:
print(f"no parentheses if condition: {k} > {f}")
if (k > f):
print(f"with parentheses if condition: {k} > {f}")
if not k==hz[5]:
print(f"variable {k=}, not {hz[5]}")
if fake ==... |
def isPalindrome(string, i=0):
j = len(string) - 1 - i
return True if i >= j else string[i] == string[j] and isPalindrome(string, i + 1) |
def d(a):
divisor_sum = 0
for i in range(1, a):
if a%i == 0:
divisor_sum += i
return divisor_sum
total_sum = 0
for a in range(1, 10001):
b = d(a)
if d(b) == a and a!=b:
total_sum = total_sum + a
print (total_sum)
|
import keyboard
while True:
print("_____________________________Tamrin #3 _________________________________\n\n")
MySentence = input("Please enter a long sentence : ")
MySentence_Splited = MySentence.split(" ")
print("\nBe soorat List kalamate jomle vared shode : ",MySentence_Splited)
pr... |
def binary_search(list, item):
"""
二分查找法
Args:
list: 需要查找的列表
item:需要查找的元素
Returns:
mid:元素索引
None:查找不到返回空
"""
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
... |
raio = float(input('Entre com o valor do raio para obter a circunferencia do circulo: '))
circunferencia = 2 * 3.14 * raio
print("A circunferencia do circulo: {:.2f}".format(circunferencia)) |
string1 = "he is "
string2 = "probably "
string3 = "pining "
string4 = "for the "
string5 = "fjords"
print(string1 + string2 + string3 + string4 + string5)
print("he is " "probably " "pining " "for the " "fjords")
print("Hello \n"*(2*2))
today = "monday"
print("day" in today)
print("Tue" in today) |
import random
num = random.randint(1,9)
count = 0
while True:
guess = input("What is your guess? (0-9): ")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess > num:
print("it is too high!")
elif guess < num:
print("it is too low!")
else:
... |
import matplotlib.pyplot as plt
import numpy as np
divisions = ["Python","PHP","CSS","JAVA","C++"]
divisions_average_marks = [92,76,9,67,51]
plt.bar(divisions, divisions_average_marks,color='pink')
plt.title("Bar Graph")
plt.xlabel("ngôn ngữ lập trình")
plt.ylabel("tỷ lệ")
plt.show() |
"""
This module holds the abstract class for player data model
All players will inhered from this class
"""
class Player:
def __init__(self, first_name, last_name, height_cm, weight_kg):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight... |
import os
import sys
def rename():
path=input("请输入路径:")
name=input("请输入开头名:")
startNumber='1'
fileType='.jpg'
print("正在生成以"+name+startNumber+fileType+"迭代的文件名")
count=0
filelist=os.listdir(path)
for files in filelist:
Olddir=os.path.join(path,files)
if os.path.isdir(Olddi... |
direction = input ("choose operation mult add sub div:")
if direction == "add":
ans = input ("Number One:")
rad = input ("Number Two:")
result = int(ans) + int(rad)
print (result)
if direction == "mult":
an = input ("Number One:")
ra = input ("Number Two:")
ww = int(an) * int(ra)
print (... |
x = 20
y = 10
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
|
import unittest
from simple_queue import Queue
class QueueTest(unittest.TestCase):
def test_operations(self):
q = Queue()
self.assertTrue(q.is_empty())
self.assertEqual(q.front(), None)
self.assertEqual(q.pop(), None)
q.push(1)
self.assertFalse(q.is_empty())
... |
import numpy as np
def exchangeability_test(x, y, size):
"""
Calculate the variance test.
This test tests the null hypothesis that two distributions on X and Y have
same variance. This time, the assumptions on medians are relaxed, but it
requires the existence of the 4th moment.
Parameters
... |
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
from typing import List
class Solution:
def... |
import streamlit as st
from neo4j import GraphDatabase
from py2neo import graph
uri = "bolt://localhost:7687"
user = "neo4j"
password = "password"
driver = GraphDatabase.driver(uri, auth=(user, password))
def create_node(tx, label, properties):
query = f"MERGE (n:{label} {properties})"
tx.run(... |
from PIL import Image
def median( inputList ):
a = 0
while a < 8:
if (inputList[a] > inputList[a + 1]):
b = inputList[a]
inputList[a] = inputList[a + 1]
inputList[a + 1] = b
if (a > 1):
a -= 2
a += 1
return (inputList[4])
imag... |
def cons(a, b):
def pair(f):
return f(a, b)
return pair
class Problem5(object):
def __init__(self,
name):
self.name = name
def solver_car(self, f):
def first(x, y):
return x
return f(first)
def... |
class Problem12(object):
def __init__(self,
name):
self.name = name
def solver_dp(self, N, steps=[1,2]):
dp = [0] * (N + 1)
dp[0] = 1
for i in range(1, N+1):
val = 0
for j in steps:
if (i - j) >= 0:
v... |
def is_odd_string(word):
"""Is the sum of the character-positions odd?
Word is a simple word of uppercase/lowercase letters without punctuation.
For each character, find it's "character position" ("a"=1, "b"=2, etc).
Return True/False, depending on whether sum of those numbers is odd.
For example... |
l = int(raw_input())
p = int(raw_input())
q = int(raw_input())
print(p * l / float(p + q))
|
res = ''
for i in xrange(8):
res += raw_input()
white_sum = res.count('Q') * 9 + res.count('R') * 5 + res.count('B') * 3 + res.count('N') * 3 + res.count('P')
black_sum = res.count('q') * 9 + res.count('r') * 5 + res.count('b') * 3 + res.count('n') * 3 + res.count('p')
if white_sum > black_sum:
print('White'... |
s, n = map(int, raw_input().split())
dragons_and_points = []
for i in xrange(n):
dragons_and_points.append(tuple(map(int, raw_input().split())))
dragons_and_points.sort()
for power, treasure in dragons_and_points:
if s > power:
s += treasure
else:
print('NO')
break
else:
pri... |
n = int(raw_input())
number = raw_input()
diff = 0
one = True
for i in xrange(n):
if number[i] == '1' and one:
diff += 1
one = True
if number[i] == '0' and one:
diff += 1
one = False
print(diff)
|
from string import maketrans
r_transtab = maketrans(
'qwertyuiop'
'asdfghjkl;'
'zxcvbnm,./',
'wertyuiopp'
'sdfghjkl;;'
'xcvbnm,.//'
)
l_transtab = maketrans(
'qwertyuiop'
'asdfghjkl;'
'zxcvbnm,./',
'qqwertyuio'
'aasdfghjkl'
'zzxcvbnm,.'
)
direction = raw_input()
word ... |
n = int(raw_input())
numbers = map(int, raw_input().split())
numbers.sort(reverse=True)
result = 0
odd = 0
for i in numbers:
if i % 2 == 0:
result += i
else:
if odd:
result += odd
result += i
odd = 0
else:
odd = i
print(result)
|
def ipadd(string):
list1 = list(string.split("."))
decimal = 0
i = 3
for num in list1:
decimal += (int(num)*pow(256, i))
i -= 1
return decimal
def isogram(string):
set1 = set(string)
list1 = list(string)
return "It is an isogram" if len(set1) == len(list1) else "It is n... |
"""
Main function (Login and Signup
"""
from authenticate import SignUp, LogIn
import menu
def main():
"""
Main method contains login and signup features
:return:
"""
print("\n-----Welcome to MSS----- \n 1. Login \n 2. Signup")
tryexit = 1
choice = None
while tryexit:
try:
... |
import unittest
import FibSequence
class TestFibSequence(unittest.TestCase):
def test_get_fib_sequence_valid_value(self):
expected = "2, 3, 5, 8, 13, 21, 34, 55, 89"
result = FibSequence.get_fib_sequence(1, 100)
self.assertEqual(result, expected)
def test_validate_args_negative_value(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.