text stringlengths 37 1.41M |
|---|
class Solution:
"""
[3,3,3,3,3,1,3]
0 1 2 3 4 5 6
3: [0,1,2,3,4,6]
1: [5]
append [0,1,2] to res, then next three item
# guaranteed that there exists at least one solution.
"""
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
mp = collections.defaultd... |
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
l = [(s.lower(), s.upper()) if s.isalpha() else s for s in S]
return ["".join(i) for i in itertools.product(*l)]
|
class Solution:
"""
video watched by your friends, the level 1 is your directly friend, and level > 1
so not include you
friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i
not relation
"""
def watchedVideosByFriends(self, watch... |
import unittest
import bowling
class BowlingTest(unittest.TestCase):
def test_scoring(self):
result = bowling.get_score('Х4/34-4------------')
# TODO везде говорится, что эначение для проверки передаётся первым параметром, аожидаемый результат - вторым.
# Но если посмотреть результат тест... |
# -*- coding: utf-8 -*-
# (цикл for)
import simple_draw
import random
import pygame
SPRITE_SCALE = 0.3
BRICK_WIDTH = 100
BRICK_HEIGHT = 50
RAINBOW_COLORS = [simple_draw.COLOR_RED, simple_draw.COLOR_ORANGE, simple_draw.COLOR_YELLOW, simple_draw.COLOR_GREEN,
simple_draw.COLOR_CYAN, simple_draw.COLOR_B... |
# -*- coding: utf-8 -*-
import simple_draw as sd
import snowfall
# На основе кода из lesson_004/05_snowfall.py
# сделать модуль snowfall.py в котором реализовать следующие функции
# создать_снежинки(N) - создает N снежинок
# нарисовать_снежинки_цветом(color) - отрисовывает все снежинки цветом color
# сдвинуть_снеж... |
# -*- coding: utf-8 -*-
####ID add-numbers
#### Άσκηση
####
#### Σε ένα αρχείο βρίσκονται γραμμένοι αριθμοί (floats) και μόνο, χωρισμένοι από κενά. Κάθε γραμμή περιέχει αριθμούς (ίσως και κανέναν)
#### και μόνο. Γράψτε μια συνάρτηση
####
#### addnumbers(s)
####
#### που να παίρνει ως μοναδικό όρισμα το ... |
def fact(num):
result=1
for i in range(1,num):
result=result*num
num=num-1
print(result)
b=int(input("enter"))
fact(b)
def c(n):
if n==1:
return 1
else:
return n * c(n-1)
print(c(5)) |
class classonlymethod(classmethod):
'''
Descriptor for making class only methods.
A `classonly` method is a class method, which can be called only from the
class itself and not from instances. If called from an instance will
raise ``AttributeError``.
'''
def __get__(self, instance, owner):... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 2 12:05:33 2020
@author: Sena-2
"""
#a = 'first'
#b = 'last'
#c = a+ ','+ b
#
#print(c)
strn = 'mehmet'
#
#strn.replace('m', 'z')
#
#print(strn)
#print('{} is everything for {}'.format('PRACTICE', 'ME'))
fruits = ['apple', 'orange', 'banana', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 15:33:03 2019
@author: Mehmet
"""
# 1 Ask the user for the radius of a circle and then print the area
#import math
#radius = int(input('Enter the radius'))
#pi = math.pi
#area = pi * (radius ** 2)
#
#print('The area is : {}'.format(area))
# 3 ... |
class BankAccount:
# don't forget to add some default values for these parameters!
accounts = []
def __init__(self, int_rate, balance = 0):
# don't worry about user info here; we'll involve the User class soon
self.int_rate = int_rate
self.balance = balance
self.accounts.app... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
class Student(object):
"""docstring for Student"""
def __init__(self, name, arg, score):
self.name = name
self.arg = arg
self.score = score
s= Student('Mac', 20, 88)
# 序列化对象
print(json.dumps(s, default=lambda obj: obj.__dict__))
# 将JSON反序列化为St... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#可以直接作用于for循环的数据类型有以下几种:
#一类是集合数据类型,如list、tuple、dict、set、str等;
#一类是generator,包括生成器和带yield的generator function。
#这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
#可以使用isinstance()判断一个对象是否是Iterable对象
from collections import Iterable, Iterator
def g():
yield 1
yield 2
... |
# Lexical analyzer
# Copyright 2019 Art Layese <artiskool@gmail.com>
from constants import *
from token import Token
class Lexer(object):
def __init__(self, text):
self.lines = text.split("\n")
if len(self.lines) == 0:
self.error()
self.line = -1
self.next_line()
... |
import math
import numpy as np
print("Введите аргумент интеграла:")
a = float(input())
I_0 = np.log(abs(a + 1)) - np.log(abs(a))
print("Введите рекуррентный номер интеграла")
k = int(input())
I = I_0
print("I_0 =", I_0, end="; ")
for i in range(0, k):
I = 1 / (i + 1) - a * I
print("I_", i+1, " = ", I, sep="", ... |
# -*- coding: utf-8 -*-
import csv
csvfile=open('dati.csv', 'r')
reader = csv.DictReader(csvfile, delimiter=";")
for row in reader:
print (row['nome'] + ' ' + row['cognome'])
|
#!/usr/bin/python3
# Tests were adjusted, original author is David Balvín
from Polynomial import *
import unittest
class TestPrintFormat(unittest.TestCase):
def test_params_basic(self):
self.assertEqual(str(Polynomial([1, -3, 0, 2])), "2x^3 - 3x + 1",
"Test 1 - Spatny vystupni f... |
toppings = "\nTell me which toppings you would like on your pizza: "
toppings += "\nEnter quit when that is enough."
while True:
message = input(toppings)
if message == 'quit':
break
else:
print("You'll add that to your toppings " + message)
|
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
def to_lower(string):
"""This method transforms an input string into a lower cased string.
Parameters
string : text of the string.
Returns:
a new string, in which all previous uppercased letters
are transf... |
#!/usr/bin/env python2
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.cache = {}
self.new_key = []
self.cache_len = capacity
# @return an integer
def get(self, key):
if key in self.cache.keys():
return self.cache[key]
... |
# import the random module
from random import randint
# set a variable to hold the random number 1-9
# chose a smaller number because it was easier to test
randomNumber = randint(0, 9)
# instantiate guess
guess = 0
print('Welcome to the guessing game...Guess a random number 1-9')
# goes through the users guesses
while... |
# Psuedo-code
# Create a Dictionary to store already seen numbers
# loop over array
# check if the difference number is in the Dictionary
# if not add the current number to the dictonary and continue
# if there is return the nums in an array
# Return empty array if no solution is found
def twoNumberSum(array, targe... |
import re
class CustomException(Exception):
pass
def get_string(main_str: str, what_to_do: str):
sec_str: list = list(main_str)
sec_arr: list = []
for i in sec_str:
# print(i)
if str.isdigit(i):
sec_arr.append(int(i))
res = 0
for i in sec_arr:
for j in ran... |
import random
class Flower:
type = 0
weather = 0
water_needs = 0
def __init__(self, type):
self.weather = random.randint(0, 2)
self.type = type
if self.type != 0:
self.water_needs = self.weather * self.type
else:
print("Не выбран тип")
s... |
# Basic probability functions
# Examples or practice test are taken from different
# resources like Peter Norvig's notebook
# A Concrete Introduction to Probability (using Python) at Jupyter
from fractions import Fraction
# Probability of an event
def Probability(event, space):
print event
print space
pri... |
__author__ = 'sukhanna'
class Node:
def __init__(self, data):
self.data = data
self.next = None
def set_next(self, new_next):
self.next = new_next
def get_next(self):
return self.next;
def set_data(self, data):
self.data = data
def get_data(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from base import Problem
class Solution(Problem):
def solve(self, input_):
print('Solve problem {}'.format(self.number))
for a in range(1, input_ + 1):
for b in range(a + 1, input_ + 1):
c = input_ - a - b
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from string import ascii_uppercase
from base import Problem
class Solution(Problem):
def point(self, word_):
return sum(ascii_uppercase.index(c) + 1
for c in word_.strip('"\n'))
def solve(self):
with open('names.txt') as f:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from base import Problem
class Solution(Problem):
def cal_decimal(self, n):
i = 10
j = 0
while (i != 10) or (j < 1):
i = (i % n) * 10
j += 1
return j
def solve(self, input_):
max_length = 0
... |
# name : Ritika Bajpai
# email : rib28@pitt.edu
# date : 10/27/2016
# class : CS0008-f2016
# instructor : Max Novelli (man8@pitt.edu)
#
# Description:
# This is the coding for the second assignment for class CS8 f2016
#
# We are required to write an application which loops indefinitely asking the... |
#intiated class called Author with one argument and empty book list
class Author:
def __init__(self, name):
self.name = name
self.books = []
#function publish adds title of the book to the book list
def pubish(self, title):
self.books.append(title)
#displays the author and list of book... |
# make a new list places
places = ["paris", "Barcelna","Lima","Busan"]
for place in places:
print ("I would like to visit" + place + " ")
#places = ["paris", "Barcelna","Lima","Busan"]
#Wish = ["I would like to visit" + " " + place for place in places]
#Wish = []
#Wish.append("I would like to visit")
#print(... |
## @file SeqServices.py
# @title Sequence Services Module
# @author Lucas Matthew Dutton
# @date February 5, 2018
##@brief Checks if the sequence is not descending, left to right
# @param X the sequence to check
# @return Returns true if the sequence is not descending, false otherwise
def isAscending(X):
for i ... |
from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 2
class CarManager(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.cars_list = []
self.create_car()
... |
import math
def isprime(no):
if no == 2:
return True
elif no % 2 == 0:
return False
sq = int(math.sqrt(no)) + 1
for i in range(3, sq, 2):
if no % i == 0:
return False
return True
def solution(n):
"""Returns the largest prime factor of a given number n.
... |
# -*- encoding: utf-8 -*-
#REF : http://www.mathwarehouse.com/algebra/linear_equation/write-equation/equation-of-line-given-two-points.php
#Accepting line 1 end point co-ordinates
l1_x1 = int(raw_input())
l1_y1 = int(raw_input())
l1_x2 = int(raw_input())
l1_y2 = int(raw_input())
#Accepting line 2 end point co-ordina... |
# -*- coding: utf-8 -*-
# Program to find factorial of a number
import types
def main():
try:
number = input()
factorial = 1
if type(number) == types.FloatType:
print "Please Enter Integer value!\n";
main();
elif type(number) not in (types.IntType,... |
import math
a = float(raw_input())
if a < 1.0:
print a * math.sqrt(2.0)
else :
x = 0.0
ans = 0.0
while x <= a:
y = math.sqrt(a * a - x * x)
ans = max(ans, x + y)
x += 1.0
x = 1.0
while x <= a:
if a * a - x * x < 1:
y = math.sqrt(a * a - x * x)
... |
def check_users(current_users, new_users):
new_us_lc = [new_users.lower() for new_users in new_us]
current_us_lc = [current_users.lower() for current_users in current_us]
xlist=[]
olist=[]
for new_users in new_us_lc:
if new_users in current_us_lc:
xlist.append(new_users)... |
'''
Write a program to obtain two-dimensional discrete Fourier transform and its
inverse of a gray level image of size 500*500. Also compute the magnitude,
phase angle and power spectrum of the Fourier transform.
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('gray2.jpg', 0)
df... |
def searchInSortedMatrix(matrix, target):
""" Search for given target in an sorted 2 dim array
with distinct integers. The matrix has shape of nxm where
Worst case: Time O(nm) and Space O(1)
Args:
param1(listoflisti): 2dim matrix sorted in ascend and distinct ints
param2(int): targ... |
# Copyright 2020
# Author: Christian Leininger <info2016frei@gmail.com>
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuffixTrieFrom(self, string):
"""
"""
for idx in r... |
# Copyright 2020
# Author: Christian Leininger <info2016frei@gmail.com>
def iterativeInOrderTraversal(tree, callback):
previous_node = None
current_node = tree
while current_node is not None:
if previous_node is None or previous_node == current_node.parent:
if current_node.left is not... |
def maxPathSum(tree):
"""
Path is a collection of nodes which each is not more then 2 other nodes are
connected
Args:
param1(BT): binary tree
Return: int represents sum of max path
"""
res = 0
return res
|
# Copyright 2020
# algo expert Fibonacci
# Author: Christian Leininger <info2016frei@gmail.com>
# O(2^n) time | O(1) space
def getNthFib(n):
""" Computes the n fibonacci number
implementation of Naive Recursion with runtime of O(2^n)
Args:
param1:(int) which fibonacci number to compute
Return... |
# Copyright 2020
# Author: Christian Leininger <info2016frei@gmail.com>
# implemention of Brunch sum
class BinaryTree():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, values, i=0):
if i >= len(values):
return
... |
def balancedBrackets(string):
"""
Checks the given string of balanced Brackets and returns True if it
In O(n) time and O(n) space where n is the length of the string
Args:
param1:(string) string to check
Returns: boolean
"""
brackets = "[](){}"
stack = []
stack.append(stri... |
# Feel free to add new properties and methods to the class.
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def setHead(self, node):
# Write your code here.
self.head = node
def setTail(self, node):
# Write your code here.
self.... |
"""
Oбчислення конкретної функції, в залежності від введеного значення х.
"""
import re
q = True
re_x = re.compile("^[-+]?\d+\.?\d*$")
def validator_1(pattern, promt):
text = input(promt)
while not bool(pattern.match(text)):
text = input(promt)
return text
def validator_2(prompt):
x = int(val... |
#sql1.py
import sqlite3
#conn=sqlite3.connect('test.db')
#cursor=conn.cursor()
#print cursor.execute('create table user (id varchar(20) primary key,name varchar(20))')
#print cursor.execute('insert into user (id,name) values(\'1\',\'Micheal\')')
#print cursor.rowcount
#cursor.close()
#conn.commit()
#conn.close()
con... |
#partial
print int('12345')
print int('12345',base=8)
print int('12345',16)
def int2(x,base=2):
return int(x,base)
print int2('1000000')
print int2('1010101')
import functools
int2=functools.partial(int,base=2)
print int2('1000000')
print int2('1010101')
max2=functools.partial(max,10)
print max2(5,6,7)
|
# recursion.py
def fact(n):
if n==1:
return 1
else :
return n*fact(n-1)
print fact(1)
print fact(5)
print fact(100)
def fact1(n):
return fact_item(n,1)
def fact_item(num,product):
if num==1:
return product
return fact_item(num-1,num*product)
print fact1(1)
print fact1(5)
print fact1(100) |
#type
from Hello1 import Hello
h=Hello()
h.hello()
print type(Hello)
print type(h)
def fn(self,name='WORLD'):
print 'Hello,%s' %name
Hello=type('Hello',(object,),dict(hello=fn))
h=Hello()
h.hello()
print type(Hello)
print type(h)
|
import re
import math
from environments.environment_abstract import Environment
def get_environment(env_name: str) -> Environment:
env_name = env_name.lower()
puzzle_n_regex = re.search("puzzle(\d+)", env_name)
env: Environment
if env_name == 'cube3': #cube3 is layer 3 environment. Solves entire cube... |
import os
import pyperclip
import random
import string
# global userAccountsInfo
class User:
"""
Class that generates new instances of user account
"""
user_holder =[]
def __init__(self,username,password):
'''
__init__ method that helps us define properties for our objects.
... |
'''
Problem Solution
1. Create a class BinomialTree with instance variables key, children and order.
children is set to an empty list and order is set to 0 when an object is
instantiated.
2. Define method add_at_end which takes a binomial tree of the same order as argument
and adds it to the current tree... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 00:57:59 2019
@author: saeem
"""
x = [1,2,3,4,5]
print(x)
str_arr = input().split(',')
arr = [int(num) for num in str_arr]
print(arr) |
########################################################
# Feel free to use, share, modify. #
# Author: Kaan Turkmen #
# github.com/katurkmen #
#########################################################
# Importing pygame.
impo... |
#!/usr/bin/env python3.6
from credentials import Password
import sys
import random
import string
from users import User
from termcolor import colored, cprint
# from termcolor import colored, cprint
def create_credential(sname, fname, lname, password):
'''
Function to create a new user credentials
'''
... |
'''
Given a sorted array of interger, write a function to find the index
of first element which is larger than or equal to another given interger
'''
def find_index(r, n):
'''
r[i-1] < n =< r[i]
reutn i
'''
start = 0
end = len(r) -1
while start <= end:
mid = (start + end)/2
... |
def printMatrix(m):
for row in m:
print(row)
def matrixMult(A, B):
if len(A[0])!=len(B):
print("Error: Number of columns for matrix A must = number of rows of matrix B")
return None
C = [[None for i in range(len(B[0]))] for j in range(len(A))]
for i in range(len(A))... |
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color="red", linewidth=1.0, linestyle="--")
plt.xlim((-1, 2))
plt.ylim((-2, 3))
new_ticks = np.linspace(-1, 2, 5) # 设置刻度范围,-1到2设置5个刻度
# print(ne... |
#!/usr/bin/env python
from machinelearning import mlgraph, examples, logisticregression
# Load the dataset, last column is the answer
data = examples.examples('../courses/ml-006/mlclass-ex2/ex2data1.txt')
#g = mlgraph.mlgraph()
#g.scatter('Exams', data.getX('train'), data.getY('train'), ['Exam 1 score', 'Exam 2 scor... |
from collections import Counter
class Resource:
def __init__(self, name='resource', density=1.0):
self.name=name
self.density=density
def __repr__(self):
return self.name
class Package(Counter):
"""
The Package class is a Counter object used when transferring resources between containers.
"""
d... |
Q1:
import csv
f = open("faculty.csv")
txt = f.read()[1:]
header = txt.splitlines()[:1]
lines = txt.splitlines()[1:]
csv_f = csv.reader(lines)
degree_list = []
for row in csv_f:
degree_list.append(row[1])
degree_dict = {x:degree_list.count(x) for x in degree_list}
print "There are %s different degrees" % len(de... |
from creature import *
pygame.display.set_caption("Simulated Evolution")
##### Main loop ######
def main():
global food_count
global run
global maxCreatures
global countLifeForGraph
global average
global max_life_cycle
global maxMoveCount
while run:
clock.tick(20)... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error,r2_score
diabetes=datasets.load_diabetes()
#using only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]
print(len(diabetes_X))
diabetes_X_train=diabetes_X[:-20]
diabete... |
#!/usr/bin/python
##CSV--Comma (or other delimiter) Separated Values
import csv
#Reading
with open(<filename>,<file_options>) as f:
reader = csv.reader(f, delimiter=',') #other possible options include: escapechar, quotechar, lineterminator, skipinitialwhitespace
for row in reader:
print row
#reader al... |
import numpy as np
import pylab
import matplotlib.pyplot as plt
# --------------------- Class for Taylor Method ---------------------- #
class TaylorMethod:
# Routine to initialize elements in class
def __init__(self, n, a, b, w_init):
# Initialize endpoints of interval
self.a = a
self... |
fname = input("Enter file name: ")
fh = open(fname)
# string -> list 변경
finlist = list()
for line in fh:
line = line.rstrip()
#각 line 들 split
lst = line.split()
#split 된 항목들을 finlist에 추가
for word in lst:
if word not in finlist:
finlist.append(word)
finlist.sort()
print(finli... |
class Queue:
def __init__(self):
self.store=[]
def add(self,val):
self.store = self.store + [val]
return True
def dele(self):
r = self.store[0]
self.store = self.store[1:len(self.store)]
return r
def empty(self):
if self.store == []:
return True
elif ... |
def cipher_encryption():
msg= input("Enter message: ")
#from random_number import msg
key = "5"
encrypt_hex = ""
key_itr = 0
for i in range(len(msg)):
temp = ord(msg[i]) ^ ord(key[key_itr])
# zfill will pad a single letter hex with 0, to make it two letter pair
... |
# ROT47 Encryption
from generate_random import y
def demo_var4():
from random_number import msg
demo_var4.msg = msg
def cipher_encryption_rot47():
# message = input("Enter message: ")
key = 5
msg = demo_var4.msg
encryp_text = ""
for i in range(len(msg)):
temp = o... |
# ceaser Decryption
from Decryption import x
def demo_var1():
from Decryption import msg
demo_var1.msg = msg
def cipher_decryption():
# msg = input("Enter message: ")
key = "5"
msg = demo_var1.msg
hex_to_uni = ""
for i in range(0, len(msg), 2):
hex_to_uni += ... |
import random
class Ship:
def __init__(self,x,y,val,orient):
#определям координаты и палубность корабля и его ориентацию (горизонт, вертикаль)
self.x = x
self.y = y
self.val =val
self.orient = orient
def get_ship(self):
return [self.x,self.y,self.val,self.orient]... |
# Design a calculator which will correctly solve all the problems except
# the following ones:
# 45 * 3 = 555, 56+9 = 77, 56/6 = 4
# Your program should take operator and the two numbers as input from the user
# and then return the result
print("Enter the operator you want want to solve" + ' +,-,/,*,%')
ope1= input()... |
"""
Quick & dirty date class with no validation.
The only useful thing here is the logic of day increment.
"""
class Date:
def __init__(self, day: int, month: int, year: int):
self._day = day
self._month = month
self._year = year
def __str__(self) -> str:
return (f'{str(self._... |
def adding_report(report = "T"):
total = 0
items = "Items"
while True:
answer = (input("Enter a integer or \"Q\": ")).upper()
if answer.isdigit() == True:
total += int(answer)
items += "\n" + answer
elif answer.startswith("Q"):
... |
def menorMaiorLista(lista):
maior = lista[0]
menor = lista[0]
for x in lista:
if x > maior:
maior = x
elif x < menor:
menor = x
return menor, maior
def main():
print("Entre com a lista: (separando os elementos por espaços)")
lista = list(map(int, input().... |
def somasegmento(ini,fim,L):
soma = 0.0
i = ini
while i < fim:
soma += L[i]
i += 1
return soma
# def somasegmento(ini,fim,L):
# soma = 0.0
# for i in range(ini, fim):
# soma += L[i]
# return soma
def main():
n = int(input("Digite n: "))
# lista = []
# ... |
import random# 引入模块random(作用:生成随机数)
数 = random.randint(1,10)# 生成一个1-10的随机数,赋值给数变量
print("作者:王楚铮")
次数 = 4
临时 = input("猜猜我想的是哪个数字(1-10):\n")
guess = int(临时)
while guess != 数 and 次数 != 0:
临时 = input("猜错啦,请重新输入吧:\n")
guess = int(临时)
if guess == 数:
print("Good\t")
次数 = 0
else:
... |
from choice import Choice,MethodDictionary,exitingChoice
class Menu():
def __init__(self,question):
self.question= question
self.choices=[]
def addChoice(self,choice):
self.choices.extend(choice)
def view(self):
choice_list = "\n".join(" {}){}".format(i, c.choiceDesc ... |
# Given a string and an integer number n,
# remove characters from a string starting from zero up to n and return a new string
# input
# logic
# output - print, return
user_string = input("Enter A String: ")
n = int(input("Enter a positive integer number: " ))
def removeChars(user_string, n):
if n < 0:
n2 ... |
# What is a function
# a function is a block of code that has some purpose
# Why do we use functions
# modularize/organize code
# How many steps are there to use functions
# What are the parts of a function
def print_hello_world():
print("Hello World")
print_hello_world()
print(23 * 16)
if 10 * 10 > 50:
... |
# Quang Trinh
# Socket Programming
# Client Program
import socket
import sys
# create socket object
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket successfully created")
except socket.error as err:
print("Failed to create socket. Error " + str(err))
sys.exit()
# get server_address
loc... |
numeroA = int(input("Enter one number: "))
while numeroA <= 0:
numberA = int(input("Error, enter one number"))
factorial = 1
while numeroA >= 1:
factorial += numeroA
numeroA -=1
print("El factorail es ", factorial) |
numero = 1
while numero <= 100:
if numero % 7 == 0 and numero % 13 == 0:
print("El numero ", numero, " es multiplo de 7 y 13")
else:
if numero % 7 == 0:
print("El numero ", numero , " es multiplo de 7")
else:
if numero % 13 == 0:
print("El numero "... |
def find_length(string):
return len(string)
print("**** Length of the String Program ****")
string = input("Enter the String: ")
print("Length of the given String is: " + str(find_length(string)))
|
import os
import csv
# Get File Path of election_data.csv dataset
csvpath = os.path.join('Resources','election_data.csv')
txtpath = os.path.join('Analysis','elec_analysis.txt')
# Open CSV
with open(csvpath) as csvFileStream:
csvreader = csv.reader(csvFileStream,delimiter=',')
csv_header = next(csvreader)
... |
#!/bin/python
import sys
def check(s, p):
i = 0
j = 0
while i < len(p):
while j < len(s) and s[j] != p[i]:
j += 1
if j == len(s):
break
i += 1
j += 1 # for repeated 'r'
return i == len(p)
q = int(raw_input().strip())
for a0 in xrange(q):
... |
# https://www.hackerrank.com/challenges/botclean
def next_move(posr, posc, board):
if board[posr][posc] == 'd':
print("CLEAN")
return
layer = 1
while True:
if posc - layer >= 0 and board[posr][posc - layer] == 'd':
print("LEFT")
return
if... |
#String Palindrome
x = "mom"
lw = 0
hg = len(x) - 1
while hg > 1:
if x[hg] != x[lw]:
hg-=1
lw+=1
print('No pali')
break
|
import random
import sys
words = ["python", "computer", "software", "desktop", "screen", "code",
"program", "mouse", "keyboard", "headphones", "dongle", "adapter",
"tablet", "socket", "cable"
]
guesses = []
secretword = random.choice(words)
length = len(secretword)
alphabet = "ab... |
import matplotlib.pyplot as plt
import collections
import numpy as np
path = "text.txt"
with open (path, 'r', encoding = "utf-8") as file:
string = file.read()
string_list = string.split()
string_dict = {}
for word in string_list:
if word in string_dict:
string_dict[word] = string_dict[word] ... |
def swap(items,left,right):
if left != right:
temp = items[left]
items[left] = items[right]
items[right] = temp
return items
def checkio(numbers_array):
dataresult = list(numbers_array)
i = 1
j = 0
swapbool = True
while swapbool:
swapbool = False
whil... |
#######################################################################
# File: client_handler.py
# Author: Raymond Rees Jr.
# Running: Python 2: python server.py
# Python 3: python3 server.py
# Note: Must run the server before the client.
#############... |
def listSum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listSum(numList[1:])
print(listSum([1,2,3,4,5]))
def move(x,y):
print("Move {} to {}".format(x,y))
def towersOfHanoi(diskQty, fromPos, midPos, targetPos):
if diskQty == 0:
pass
else:... |
#!/usr/bin/env python3
def basicStringSearch(searchString, target):
searchIndex = 0
while searchIndex + len(target) <= len(searchString):
targetIndex = 0
while (targetIndex < len(target)) and target[targetIndex] == searchString[targetIndex + searchIndex]:
targetIndex = targetIndex +... |
def partition(A, low, high):
pivot = A[high]
i = low -1
for j in range(low, high):
if A[j] <= pivot:
i = i + 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[high] = A[high], arr[i + 1]
return i + 1
def quickSort(A, low, high):
if low < high:
q = partition(A, low, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.