text stringlengths 37 1.41M |
|---|
def largest(arr):
l = arr[0]
for i in arr:
if i > l:
l = i
return l
aList = [4, 6, 8, 24, 12, 2]
print(largest(aList)) |
def concat(a1, a2):
x = 0
result = []
while x < len(a1):
temp = a1[x] + a2[x]
result.append(temp)
x += 1
return result
list1 = ["M", "na", "i", "Ke"]
list2 = ["y", "me", "s", "lly"]
print(concat(list1, list2)) |
import math
def thirds(arr):
third = int(math.floor(len(arr) / 3))
x = 0
first = []
second = []
three = []
while x < 3:
if x == 0:
first = arr[:third]
first = first[::-1]
print(first)
elif x == 1:
second = arr[third: third * 2]
... |
def hyphen(s):
arr = s.split('-')
for x in arr:
print(x)
str1 = 'Emma-is-a-data-scientist'
hyphen(str1) |
#!/usr/bin/env python3
VALUES = {'black': 0, 'blue': 6, 'brown': 1, 'green': 5, 'red': 2}
MULT = {'black': 1, 'blue': 1000000, 'brown': 10, 'green': 100000, 'red': 100}
def compute_resistance(bands):
if bands is None: return None
band1, band2, mult = reversed(bands)
base = VALUES[band1] * 10 + VALUES[band2]
r... |
#Yevgeny Khessin
#A39652176
#HW1
#test1
import sieve
#run once to check if value produced is 3.
def test1():
s = sieve.sieve() #make a sieve object from file sieve
i = iter(s) #make iterator
val=i.next() #run iterator once, put value in val
assert val == 3 #check if value is 3. if not 3, fail.
pri... |
# A minion object is a card
from Card import Card
class Minion(Card):
def __init__(self,cost,name,ATK,HP):
Card.__init__(self,cost,name)
self.ATK = ATK
self.HP = HP
def printMinionInfo(self):
print("Name: " + str(self.name))
print("Cost: " + str(self.cost))
... |
################################################
#randomColor.py
#Generating the random RGB colors
#Version 1.0
###############################################
import random
'''Generating random colours'''
def colourGen(trans):
myColours = []
for i in range(0,trans):
r = lambda: random.randint(0,255)
... |
################################### RULE BASED CLASSIFICATION ########################################
# A game company wants to create level-based new customer definitions (personas) by using some
# features ( Country, Source, Age, Sex) of its customers, and to create segments according to these new customer
# defi... |
import plotly.express as plot
import numpy as np
np.random.seed(45)
# declaring size of the array
size = 100
x = np.random.randint(low=0, high=100, size=size)
y = np.random.randint(low=0, high=100, size=size)
fig = plot.scatter(x=x, y=y)
# Adjusting width and height of the image
fig.layout.template = 'plotly_dark'... |
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encrypt(msg, shift=13):
output = ""
for i in range(len(msg)):
c = msg[i]
j = alpha.find(c)
k = (j + shift)%len(alpha)
output += alpha[k]
return output
def decrypt(msg, shift=13):
output = ""
for i in range(len(msg)):
c = msg[i]
j = alpha.find(c)
k = (j - shif... |
import random
import string
import json
class VariousFunctions:
def random_string(self, string_size, chars=string.ascii_uppercase + string.digits):
self.string_size = string_size
final_string = ''.join(random.choice(chars) for i in range(string_size))
return final_string
def create_j... |
# Напишите программу, которая запрашивает у пользователя начальное количество денег и,
# пока оно меньше 10 000, запрашивает число, которое выпало на кубике (от 1 до 6).
# Если на кубике выпало 3, то выводится сообщение «Вы проиграли всё!», и деньги обнуляются.
# Если выпало другое число, к сумме прибавляется 500.
su... |
# В некоторых странах действует так называемая прогрессивная шкала налогообложения:
# чем больше ты зарабатываешь, тем больший налог платишь. Нужно написать программу,
# которая будет рассчитывать сумму налога исходя из прибыли. Если прибыль до 10 000
# — ставка налога равна 13%, начиная с 10 000 и до 50 000 — 20%. А н... |
# Планируется построить театр под открытым небом, но для начала нужно хотя бы примерно
# понять сколько должно быть рядов, сидений в них и какое лучше сделать расстояние между рядами.
# Напишите программу, которая получает на вход кол-во рядов, сидений и свободных метров между рядами,
# затем выводит примерный макет те... |
#! /usr/local/bin/python3
# Caitlin M
"""AoC Day 4: Giant Squid
Original problem at https://adventofcode.com/2021/day/4
"""
BINGO_SIZE = 5
def mark_bingo_boards(bingo_num):
"""Replace specified number with X in all boards"""
global bingoboards
for board in bingoboards:
for line in board:
... |
#! /usr/local/bin/python3
# Caitlin M
def load_input(input_name):
"""Load the input file (a line-seperated list of numbers)."""
with open(input_name) as input_file:
input_list = []
for line in input_file:
input_list.append(int(line.strip()))
return input_list
if __name__ == "__... |
#!/usr/bin/env python
"""Advent of Code 2017 Day 07 - Recursive Circus
http://adventofcode.com/2017/day/7
Find the root node name of a tree of "programs".
Given: list of nodes, weight and names of child nodes
in format "xxxx (ww) -> yyyy, zzzz"
"""
import re
INPUT_FILENAME = "d07-input.txt"
RE_NODE = r"^([a-z]+) ... |
#!/usr/bin/python
#conversion from float to int,string,long,hex,oct
x=445.125
print(int(x))
print(long(x))
print(str(x))
print(repr(x))
|
from collections import defaultdict
mass_content = dict()
#Creating monoisotopic mass dictionary
with open("data/monoisotopic_mass_table.txt") as monoisotopic_mass_dict:
'''
The monoisotopic mass table for amino acids is a
table listing the mass of each possible amino acid
residue, where the value o... |
#!/usr/bin/env python3
from algorithm import *
from ev3dev2.sensor import INPUT_4
from ev3dev2.sensor.lego import TouchSensor
def main():
begin, end, board = scan()
for row in board:
for col in row:
if col is None:
print(0, end="")
elif col is ... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
X = np.random.random(size=(20, 1))
y = 3*X.squeeze()+2+np.random.randn(20)
model = LinearRegression()
model.fit(X, y)
# Plot the data and the model prediction
X_fit = np.linspace(0, 1, 100)[:, np.newaxis]
y_fit = mod... |
numbers = input().split(", ")
numbers = [bin(round(float(item))).count("1") for item in numbers]
numbers.sort()
print(*numbers, sep=", ")
|
# Python example of command-line argument processing
import sys
num_args = len(sys.argv)
print ("{0} argument{1}" . format(num_args, "s" if (num_args != 1) else ""))
index = 0
for arg in sys.argv:
print ("sys.argv[{0}]: \"{1}\"" . format(index,arg))
index += 1
|
#!/usr/bin/python
from itertools import permutations
def checkValid(numlist):
"""check the validity of a number as described: """
if listToDigit(numlist[1:4])%2!=0: return False
if listToDigit(numlist[2:5])%3!=0: return False
if listToDigit(numlist[3:6])%5!=0: return False
if listToDigit(numlist[4... |
#!/usr/bin/python
import math
def factorize(num):
"""return the set of factors"""
s=set([])
ori=num
bound=int(math.sqrt(ori))+1
while ori!=bound:
change=False
for i in range(2, bound+1):
if ori%i == 0:
ori//=i
s.add(i)
bo... |
import numpy as np
grid = [[0,9,0,3,0,0,0,7,0],
[0,5,3,4,0,9,0,0,0],
[0,0,2,0,0,0,0,5,0],
[0,0,0,2,0,0,0,0,0],
[2,0,0,1,0,0,6,4,0],
[0,0,4,5,0,0,0,1,2],
[0,3,6,0,0,0,4,0,5],
[0,0,0,9,0,0,0,0,0],
[1,0,0,0,0,8,0,0,0]]
print("Entered Grid:")
print(np.matrix... |
#Exercise 1
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'octo', 'nov', 'dec']
for month in months:
if month[0] == 'j':
print(month)
#Exercise 2
integers = list(range(100))
for divisable in integers:
if divisable % 10 ==0:
print(divisable)
#Exercise ... |
class Worker:
def __init__(self, name, surname, worker_position, income):
self.name = name
self.surname = surname
self.position = worker_position
self._income = income
class Position(Worker):
def get_full_name(self):
return f"{self.name} {self.surname}"
def get_tot... |
n = input("Enter a number: ")
result = int(n) + int(n + n) + int(n + n + n)
print(f"{n} + {n}{n} + {n}{n}{n} = {result}")
|
a = float (input ())
litr = a * 3.78541181779
bar = a / 19.5
co2 = a * 20
ch = (a * 115000) / 75700
cost = a * 3.00
day = ((litr / 8,6) * 449800)
year = ()
print (litr,"литров", "\n", bar, "баррелей", "\n", co2, "фунтов углекислого газа", "\n", ch, "галлонов этанола", cost, "долларов США", day, "литров в Новосибисрке в... |
# open alice.txt, print lines that startwith
# 'Alice' and print out result with right-hand whitespace
# removed
with open('alice.txt') as file:
for line in file:
line = line.rstrip()
if line.startswith("Alice"):
print(line)
|
# open alice.txt, count the lines, and
# print out number of lines
with open('alice.txt') as file:
count = 0
for line in file:
count += 1
print('Line Count:', count)
|
"""An implementation of tabbed pages using only standard Tkinter.
Originally developed for use in IDLE. Based on tabpage.py.
Classes exported:
TabbedPageSet -- A Tkinter implementation of a tabbed-page widget.
TabSet -- A widget containing tabs (buttons) in one or more rows.
"""
from tkinter import *
class InvalidN... |
#!/usr/bin/python
# -*-coding: utf-8-*-
import re
import sys
def readFile(file_path):
file_object = open(file_path)
try:
return file_object.read( )
finally:
file_object.close( )
if __name__ == '__main__':
if len(sys.argv) == 1:
str='abcd(006531)(hello)'
arr = re.findal... |
#################
## Left Rotate ##
#################
def reverse(A,s,f):
while s < f:
A[s],A[f] = A[f],A[s]
f -= 1
s += 1
return A
# The following function shift all the elements of A by k positions on the left
# the first k elements are attached at the end of A
# This is done in plac... |
class disjointSets:
def __init__(self, n):
self.sets = [-1]*n
self.size = n
# returns true or false as to weather or not a union was preformed
def union(self, a, b): # union by size
rootA = self.find(a)
rootB = self.find(b)
if rootA == rootB:
return Fa... |
#coding:utf-8
class Animals():
def breathe(self):
print("breathing")
def move(self):
print("moving")
def eat(self):
print("eating food")
class Mammals(Animals):
def breastfeed(self):
print("feeding young")
class Cats(Mammals):
def _init_(self,spots):
self.spot... |
#!/usr/bin/python3
# sempre que vai buscar algo, é necessário buscar pela chave
# pessoa = {}
# pessoa = {'nome':'daniel','email':'daniel@daniel'}
# pessoa['nome']
# 'daniel'
# pprint é uma biblioteca para organizar o dicionario e exibir um abaixo do outro
# from pprint import pprint
# pessoas = [
# {'nome':'d... |
#!/usr/bin/python3
# escrever uma função se o número for par ou impar
import pdb
def par_impar(num):
if num %2 == 0:
return'Par'
else:
return'impar'
resultado = par_impar(10)
print(resultado)
|
print(' dict '.center(60, '*'))
student1 = {
'name': 'Python 3',
'age': 11,
'id': 11-21-21,
'phone': '+88016 7839743',
1 : 34
}
student1['add'] = 'Dhaka, Dangladesh'
student1['name'] = 'Python 2'
print(student1['name'])
print(student1.get('jfsl'))
print(student1.items())
print(student1.keys())
print... |
class Turtle:
#atri
color = 'green'
weight = 10
def eat(sel):
sel.color = 'red'
print('I am eating')
tt =Turtle()
print(tt.color)
tt.eat()
print(tt.color)
|
import sys
import copy
import time
#The input and the goal states are passed through an input file
with open('input.txt', 'r') as input_file:
data_item = [[int(num) for num in line.split()] for line in input_file if line.strip() != ""]
#Extracting the Input and Goal States from the input file.
start_sta... |
#dictionaries and generator expressions
prices = {'apple' : 0.40, 'banana' : 0.50}
my_purchase = {
'apple' : 1,
'banana' : 6 }
grocery_bill = sum(prices[fruit] * my_purchase[fruit]
for fruit in my_purchase)
print 'I owe the grocer $%.2f' % grocery_bill |
graph = {
'a': ['b'],
'b': ['c', 'f'],
'c': [],
'd': ['a', 'e'],
'e': ['f'],
'f': ['c']
}
def depth_first_search(graph):
visited = {}
for v in graph.keys():
visited[v] = False
for vertex in graph.keys():
dfs(vertex, graph, visited)
def dfs(vertex, graph, visited):
... |
def quick_sort(array, i, j):
if i >= j:
return []
pivot = find_pivot(array, i, j)
k = partition(array, i, j, pivot)
quick_sort(array, i, k-1)
quick_sort(array, k, j)
def find_pivot(array, i, j):
for k in range(i, j+1):
if array[i] != array[k]:
if array[i] > array[k]:... |
def bubble_sort(array):
for i in range(len(array)-2):
for j in reversed(range(i+1, len(array)-1)):
if array[j-1] > array[j]:
array[j-1], array[j] = array[j], array[j-1]
return array
print(bubble_sort([4, 6, 1, 3, 7]))
|
"""
Title: Library_Dhiraj
Authour: Dhiraj Meenavilli
Date: October 26 2018
"""
### --- Inputs --- ###
def operations():
customer = str(input("What is the customer's name?"))
print("")
return customer
def served():
try:
ask = int(input("Was the previous customer served justice ice tea? (1... |
import pandas as pd
# *********** LOAD DATA ***********
headers = ["age", "workclass", "fnlwgt", "education",
"education-num", "marital-status", "occupation",
"relationship", "race", "sex", "capital-gain",
"capital-loss", "hours-per-week", "native-country", "answer"]
df = pd.r... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Simple iterator that print all files.
Author: Ronen Ness.
Since: 2016.
"""
from .. import files_iterator
class PrintFiles(files_iterator.FilesIterator):
"""
Iterate over files and print their names.
"""
def process_file(self, path, dryrun):
"""
... |
import pickle
import os
class hello:
#实例初始化时调用方法
def __init__(self,name):
self.dd=name
self.sd=name+':'+name
print('1202初始化.....')
#无参数方法,Python类的方法的参数列表,必须至少有一个self 参数,调用时则可以不赋值,相当于JAVA中的this
def hhle(self):
print('Hi, this is my python class. my name is ',self.dd, '... |
'''
: string的实际使用技巧
:python cookbook3
: 2018-10-12
'''
import re
line='asdf fjdk; afed,fjek,asdf, foo'
#使用多个界定符分割字符串
my=re.split(r'[;,\s]\s*', line)
print(my)
m1=tuple(my) #list type convert into tuple type
print(m1)
m2=list(m1) #tuple type convert into list type
print(m2)
#文件名匹配检查,返回 True or False
from fnmatch im... |
#实现一个电话本,屏幕录入联系人信息,并写入文件,可查看、修改、删除操作。
import os
import time
import pickle
#文件名和存储路径
filename='电话本.txt'
filedir='d:\\PycharmProjects\\test'
filepath=filedir+os.sep+filename
print('电话本存储路径是:',filepath)
content={':':'-'}
class contactbook:
def __init__(self,name,sex,age,address,phone):
self.name=name
... |
from decimal import Decimal
from decimal import localcontext
n1=Decimal('1.245')
n2=Decimal('2.8992')
print(n1+n2)
# 通过上下文设置输出精度
with localcontext() as ctx:
ctx.prec=20 #设置运算结果的精度
print(n1/n2)
# 格式化输出
n3=10
print(format(n3,'b')) #将数字转化为二进制输出
print(format(n3,'o')) #将数字转化为八进制输出
print(format(n3,'x')) #将数字转... |
"""
This python file is shown how to use the Character function.
It includes all kinds of character usage.
It is from a web article.
Let's begin from March, 31st, 2022.
"""
'''
///第一部分:字符串切片操作///
'''
test = "python programming"
print("The string is: ", test)
for i in range(len(test)):
print(tes... |
# This is my first program in Python.
print("Hello,World!")
print("Hello,Thomas!")
print('{0} is my son, his age is {1}'.format('春晖',8))
print('{0:.6f}'.format(2/3))
print('this is first line,\nthis is second line.')
print("what's your name?") #字符串输出,用双引号
print('what\'s your name?') #字符串输出,用单引号+转义字符\
i=5
print(i)
i... |
import unittest
import cap
#you will inheret from unittest the class TestCase
class TestCap(unittest.TestCase):
# crate a function for each test
def test_one_word(self):
# going to test cap_text function you need to test with criteria (text = 'python')
# make sure you function performs as exp... |
# DocQuery-example.py
# Collin Lynch and Travis Martin
# 9/8/2021
# The DocQuery code is taked with taking a query and a set of
# saved documents and then returning the document that is closest
# to the query using either TF/IDF scoring or the sum vector.
# When called this code will load the docs into memory and deal... |
def sayHello(name):
return 'Hello, ' + name + '!'
name = input(
print(sayHello(name)) |
print("Hello World - Coding")
print(5) #숫자
print(100000)
print(5*3+(2-2)/4)
print("장하다.") #문자
print('잘하고있다')
print("넌 할수있다"*3)
# 한줄 주석사용하기
'''여러줄 주석처리하기
방법'''
# 들여쓰기
print('a"')
print('b')
print('c')
# 조건 참/거짓
print(5>10)
print(5<10)
print(True)
print(False)
# 줄바꿈 ( \n ) 같음 ( == )
# 변수, ... |
from playsound import playsound
import os
import random
def speak_number(number):
audio_path = "audio-numbers/" + str(number) + '.wav'
playsound(audio_path)
def play():
os.system('clear')
picked_numbers = []
numbers = [i for i in range(1, 91)]
random.shuffle(numbers)
while len(picked_... |
from Compiler.error_handler.runtime_error import RunTimeError
class Number:
def __init__(self, number_value):
self.number_value = number_value
self.set_position()
self.pos_start = None
self.pos_end = None
def set_position(self, pos_start=None, pos_end=None):
self.pos_s... |
from __future__ import annotations
from math import sqrt, sin, cos
class Vector:
"""A Python implementation of a vector class and some of its operations."""
values = None
def __init__(self, *args):
self.values = list(args)
def __str__(self):
"""String representation of a vector is i... |
# Gives Square root of first 10 Even Numbers
sq2 = [n**2 for n in range(10) if not (n %2)]
print("Square of first 10 Even numbers", sq2)
|
from stack import Stack
st2 = Stack()
def revstring(mystr):
liststr = []
# Bread the string into characters
# [liststr.append(mystr[i]) for i in range(0, len(mystr))]
[st2.push(i) for i in liststr]
# for ch in mystr:
# st2.push(ch)
return liststr
revstring("hello")
output = ''
while no... |
#This program computes the combination of a set of letters.
let = 'ABCD'
pairs = [(let[a], let[b]) for a in range(len(let))
for b in range(a, len(let))]
#Outputs the pairs
print(pairs)
|
import numpy as np
import matplotlib.pyplot as plt
pointsnum=300
learning_rate = 0.01
def labeling(array) :
for i in range(pointsnum) :
if array[i][0] + array[i][1] - 1 > 0 : # (x1 + x2 - 1 > 0)
array[i][2] = 1
else :
array[i][2] = -1
class perceptron :
de... |
# -*- coding: utf-8 -*-
print "你进去了一个漆黑的房间,里面有两扇门,你准备进入第一扇门还是第二扇门呢?"
door = raw_input("> ")
if door == "1":
print "房间里面有个老虎在吃肉,你准备采取以下哪种动作呢?"
print "1. 和它一起分享肉。"
print "2. 对老虎大叫。"
bear = raw_input("> ")
if bear == "1":
print "干的好,老虎把你一起吃了"
elif bear == "2":
pri... |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
order = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
def printAnimalAt(number):
print 'The animal at ' + str(number) + " is the " + str(number + 1) + "st animal and is a " + animals[number] + "."
def printTheAnimal(number):
print '... |
"""Generate Markov text from text files."""
from random import choice
# import sys
# input_path = sys.argv[1]
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
... |
dict1 = {
"april_batch":{
"student":{
"name":"Mike",
"marks":{
"python":80,
"maths":70
}
}
}
}
# Access "Mike"
print(dict1['april_batch']['student']['name'])
# Access 80
print(dict1['april_batch']['student']['marks']['python'])
# ch... |
Airthmatic operations using functions
num1=int(input("Enter first number: "))
num2=int(input("Enter Second number: "))
def add(num1,num2):
return num1+num2
def sub(num1,num2):
return num1-num2
def mul(num1,num2):
return num1*num2
def div(num1,num2):
return num1/num2
print(""" Enter your c... |
"""Пользователь вводит номер буквы в алфавите. Определить, какая это буква."""
letter = input('input eng letter: ').lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
if letter in alphabet:
position = alphabet.index(letter)+1
print(f'position of your letter "{letter}" is: {position}')
else:
print('try again, ... |
'''
Euler6.py - a program to solve euler problem 6 - sum of squares
Nate Weeks October 2018
'''
# squaresum = 0
# sum = 0
# for i in range(101):
# squaresum += i ** 2
# sum += i
#
# answer = (sum ** 2) - squaresum
# print(answer)
class Euler6(object):
''' object takes a max number - includes methods to fin... |
n=input("Enter a number")
for i in n:
if (int(i)%2)!=0:
print(i,"\t")
|
def prod(iterable):
result = 1
for n in iterable:
result *= n
return result
parser = argparse.ArgumentParser(description='Multiply some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='*',
help='an integer for the accumulator')
parser.add_argument('--p... |
# Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# use a with statement to open the text, and save it to a variable
with open('ciphertext.txt', 'r') as f:
words = f.read()
# bad characters do not need to get deciphered
bad_chars = ('\n',' ','!','"','(',')',',','.','1',':',';','?'... |
#!/usr/bin/env python
import argparse
import textwrap
def get_args():
'''This function parses and return arguments passed in'''
parser = argparse.ArgumentParser(
prog='filterFastaByName',
description='Filter fasta file by sequence name')
parser.add_argument('fasta', help="path to fasta in... |
import random
import string
class Application:
users = {}
def register(self, user):
"""
if user doesnot exist already, it creates a new use
:param user:
:return:
"""
if user.email not in self.users.keys():
self.users[user.email] = user
r... |
#!/usr/bin/python3
import pickle
import base64
CANVSIZE = 16
canvas = [[" " for i in range(CANVSIZE)] for j in range(CANVSIZE)]
def print_canvas(canvas):
print("#" * (CANVSIZE + 2))
for line in canvas:
print("#", end="")
for char in line:
print(char, end="")
... |
import random as rand
import abc
class LinkedList :
# Initializes an empty linked list.
def __init__(self):
self.list = [] # beginning of linked list
# Returns the number of items in this linked list.
def size(self):
return len(self.list)
# Returns true if this linked list is empty.
def isEmpty(self):
... |
class Ingredient(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def get_cost(self):
return self.cost
class Pizza(obj... |
import random
from random import randrange
print("Give me two numbers, a minimum and a maximum")
a = int(input("Select minimum. "))
b = int(input("Select maximum. "))
c = 0
while c < 10:
print(randrange(a, b))
c += 1 |
# problem 2. counting words
'''
Description
The method count() returns the number of occurrences of substring sub in
the range [start, end]. Optional arguments start and end are interpreted
as in slice notation.
Syntax
str.count(sub, start= 0,end=len(string))
Parameters
sub -- This is the substring to be searched.
st... |
# 단어 정렬
n = int(input())
# 1. 단어를 입력받음
words = []
for i in range(n):
words.append(input())
# 2. 중복되는 단어를 삭제
# 중복을 허용하지 않는 set
set_words = list(set(words))
# 3. 길이와 단어 쌍으로 묶어서 저장
sort_words = []
for i in set_words:
sort_words.append((len(i), i))
# 4. 단어 정렬
result = sorted(sort_words)
for len_word, word in ... |
def swap(input_list,a,b):
temp = input_list[a]
input_list[a] = input_list[b]
input_list[b] = temp
def permutation_looper(numpad_list,start,end):
if start == end:
permutation_output.append(numpad_list.copy())
else:
for i in range(start,len(numpad_list)):
swap(numpad_list... |
import random
def guessing_game():
count = 0
while True:
count += 1
if count > 5:
break
try:
n = int(input('Guess a number between 1 and 10: '))
r = random.randint(1, 10)
if n > 0 and n < 11:
if r == n:
... |
#Name: Shane Bastien
#Email: sachabastien@gmail.com
#Date: October 20, 2019
#ask the user to specify the input file,
#ask the user to specify the output file,
#make a plot of the fraction of the total population that are children over time from the data in input file, and
#store the plot in the output file the user sp... |
from Tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side = BOTTOM)
def button(buttonText, fgcolour,bgcolour):
button1 = Button(topFrame, text= buttonText, fg = fgcolour, bg = bgcolour)
button1.pack(side = LEFT)
def label(textOne):
labe... |
def is_palindrome(text):
end = len(text)
for i in range(0, int(end/2)):
if not text[i] == text[end-1-i]:
return False
return True
def binary_str(num):
exp = 0
while 2**exp <= num:
exp = exp + 1
result = ""
while exp > 0:
exp = exp - 1
mult ... |
import math
def list_of_primes(max_prime):
if max_prime < 2:
return []
primes = [2]
for i in range(3,max_prime+1):
is_prime = True
square = math.sqrt(i)
for prime in primes:
if i % prime == 0:
is_prime = False
break
eli... |
def contains_same_digits(num1, num2):
str1 = str(num1)
str2 = str(num2)
if not len(str1) == len(str2):
return False
for i in range(0, len(str1)):
if not str1.count(str1[i]) == str2.count(str1[i]):
return False
return True
not_found = True
num = 10
while not_found is Tr... |
def numDivisors(x):
numDiv = 1;
i = 2;
while i < x**(1/2.0):
if x%i==0:
numDiv+=2;
i+=1;
return numDiv;
sum = 0;
num = 0;
bool = True;
max_divisors = 0;
while bool:
sum = sum + num;
num+=1;
z = numDivisors(sum);
if z > max_divisors:
max_divisors = z;
... |
# -*- coding: utf-8 -*-
"""
iter_fibo.py
Created on Sat Apr 23 11:19:17 2019
@author: madhu
"""
#%%
class TestIterator:
value = 0
def __next__(self):
self.value += 1
if self.value > 10: raise StopIteration
return self.value
def __iter__(self):
return self
print('-'*30)
t... |
# https://www.hackerrank.com/challenges/string-validators/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
if __name__ == '__main__':
s = input()
halnum =[ 1 if x.isalnum()==True else 0 for x in s ]
print('True' if sum(halnum)>=1 else 'False')
halpha =[ 1 i... |
# link https://www.hackerrank.com/challenges/nested-list/problem?h_r=next-challenge&h_v=zen
# Nested List
'''
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
'''
if __name__ == '__main__':
score = []
for _ in range(0,int(input())):
sco... |
# -*- coding: utf-8 -*
import urllib
import urllib2
import requests
class DownloadFile:
def __init__(self):
self.downloadPath="F:\\Development\\DownloadsTest\\20171119"
def downloadOneFileWithUrlLib(self,url,fileName):
urllib.urlretrieve(url, self.downloadPath + fileName)
def downloadOneFi... |
def count_consonants(str):
consonants = "bcdfghjklmnqrstvwxz"
count = 0
for iter in str:
for item in consonants:
if iter == item:
count = count + 1
return count
def main():
print(count_consonants("choise"))
if __name__ == '__main__':
main() |
def sum_of_min_and_max(arr):
min = arr[0]
max = arr[0]
for item in arr:
if item < min:
min = item
if item > max:
max = item
sum = min + max
return sum
def main():
print(sum_of_min_and_max([1,2,3]))
print(sum_of_min_and_max([1,2,3,4,5,6,8,9]))
print(sum_of_min_and_max([-10,5,10,100]))
print(sum_of_... |
def is_decreasing(seq):
iter = 0
while iter <= len(seq) - 2:
if seq[iter] <= seq[iter + 1]:
return False
else:
iter = iter + 1
return True
def main():
print(is_decreasing([5,4,3,2,1]))
print(is_decreasing([1,2,3]))
print(is_decreasing([100, 50, 20]))
print(is_decreasing([1,1,1,1]))
if __name__ == '__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.