text stringlengths 37 1.41M |
|---|
# Double-base palindromes Q36
# Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
def isPalindrome(n) :
num = str(n)
numLen = len(num)
if numLen == 1:
return True
numTest = False
for i in range(0, int(numLen/2)): # range half the number
... |
def helloWorld(x):
text ='. Hello World'
count = 1
for i in range (x):
print (f"{count}{text}")
count = count + 1
helloWorld(7) |
DAYS_OF_WEEK = {
1: "MON",
2: "TUE",
3: "WED",
4: "THU",
5: "FRI",
6: "SAT",
7: "SUN"
}
# The functions must all take a datetime object and they must all
# return a string
def week_number(date_time):
return "{week_number}".format(week_number=date_time.strftime("%V"))
def week_day(d... |
import sqlite3
def getdb():
conn = sqlite3.connect('../data/purchasing.db')
return(conn)
def printdb():
with open('file.txt.', 'w') as f:
c = getdb().cursor()
c.execute('''select * from items where br10qty > 0''')
towrite = c.fetchall()
for num, supp, prod, code, name, br, ... |
#Lárus Ármann Kjartansson
#5.11.2020
import random
#### KLASAR ####
#### TRAPEZOID CLASS ###
class Trapisa:
numer = 1
def __init__(self,a=0.0,b=0.0,c=0.0,d=0.0,h=0.0):
self.a = a
self.b = b
self.c = c
self.d = d
self.h = h
self.nafn = "NN"
self.numer=Tra... |
#!/usr/bin/python3
def read_lines(filename="", nb_lines=0):
"""Function that reads n lines of a text file (UTF8)
and prints it to stdout"""
line_number = 0
with open(filename, encoding='utf-8') as f:
for line in f:
line_number += 1
if (nb_lines <= 0) or (nb_lines >= line... |
#!/usr/bin/python3
"""Unittest for max_integer
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""unittests for the function def max_integer(list=[])"""
def test_max_integer(self):
self.assertEqual(max_integer([1, 2, 3]), 3)
... |
#!/usr/bin/python3
def is_kind_of_class(obj, a_class):
""" check if an object is an instance of a class
that inherited from the class"""
if isinstance(obj, a_class):
return True
return False
|
"""
Un telefono depende del estado del telefono/linea
-Si suena lo puedes coger
Se trata de un patron donde el comportamiento de un determinado estado está determinado por su propio estado.
Hay un disparado de un estado a otro => state machine
"""
#LIGHT SWITCH
from abc import ABC
class Switch:
def __init__(sel... |
#Un adaptador es una pieza que permite adaptar una interfaz existente para
#que funcione de acuerdo a lo requerido por una interfaz Y
class Point:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
def draw_point(p):
print(".", end= "")
#Tenemos al API anterior
#Tenemos la siguient... |
#Motivacion:
"""
clickas a un elemento en el form => quien gestiona el click
- el boton
-el group box
-underlaying window
Esencialmente, encadenar componenetes para que todos tengan la oportunidad de
realizar algún procesamiento. Opcionalmente con la capacidad de terminar la
cadena
"""
class Creature:
def __ini... |
class Company(object):
def __init__(self, company_id, company_name, company_type, company_email):
self.Company_id = company_id
self.Company_name = company_name
self.company_type = company_type
self.company_email = company_email
def __str__(self):
return "Company ... |
class programming():
count=0
def __init__(self,interpreter):
self.interpreter=interpreter
programming.count+=1
def print_progarm(self):
print(self.interpreter)
class python(programming):
count=0
def __init__(self,name,interpreter):
self.name=name
... |
def load_file():
try:
f = open('input.txt', 'r+')#open file
except NoSuchFile:
return "No Such File"
for lines in f.readlines():#for loop to read through txt file
data = lines[0:4]#splice txt file from 0 to 3
data2 = lines[4:]#splice txt file index 4 to end
... |
#비밀번호 찾기
from sys import stdin,stdout
rd = lambda:stdin.readline()
wr = stdout.write
N,M = map(int, rd().split())
account = dict()
for i in range(0, N):
id, pw = rd().split()
account[id] = pw
for i in range(0, M):
id = rd().rstrip() #끝의 개행문자 제거
print(f"{account[id]}") |
driving = input('你有沒有開過車?')
if driving != ('有') and driving != ('沒有'):
print('只能回答"有"或"沒有"')
raise SystemExit
age = input('請輸入年齡: ')
age = int(age)
if driving == '有':
if age > 18:
print('恭喜你!通過測驗了!')
else:
print('未滿18歲怎麼會開過車呢?')
elif driving == '沒有':
if age > 18:
print('成年了可以考駕照了')
e... |
def fatorial(n):
produto = n
for i in range (1, n):
produto = produto * (n-1)
return produto
def main():
for i in range (10):
print (fatorial(i))
main()
|
# Possible_inputs = ['Scissor', 'Rock', 'Paper']
def whowin(human, cpu):
if human == cpu:
return 0
elif human == 'Scissor' and cpu == 'Rock':
return -1
elif human == 'Scissor' and cpu == 'Paper':
return +1
elif human == 'Rock' and cpu == 'Scissor':
return +1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import re
def count_key_words(key_words):
contents = []
for file_name in glob.glob('*.txt'):
with open(file_name, 'r') as file:
contents.append(file.read())
str = ''.join(contents).lower()
return dict(map(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ast
import xlwt
def read_city(path):
with open(path, 'r') as file:
content = file.read()
return ast.literal_eval(content)
def write_city2xls(dic):
wb = xlwt.Workbook()
ws = wb.add_sheet('City')
for key, value in dic.item... |
def input_info():
name=str(input("enter your name: "))
age=float(input("enter your age: "))
weight=float(input("enter your weight: "))
system=str(input("enter your desired metrics: "))
return (name,age,weight,system)
def calculate_bmi(weight,age,system='metrics'):
if system.startswith('m'):
... |
'''def calc(num):
try:
if num > 9:
print(f"you provided num as ---->{num}")
except:
print("you provided not an int type")
a=calc(10)
b=calc('this')
'''
'''import json
import os
a=float(input("enter no"))
print(a)
with open('test_pra','w') as f:
json.dump(a,f)
path_of_file=os.p... |
class testing:
"This is for testing class concepts"
a=3
def __init__(self,firstname,lastname): ############# These is main class deinfition. Here, i am declaring two params to be needed and then will make use of those params
self.name_given_firstname=firstname ################ You can re-use these p... |
number = float(input("Please Enter any number : "))
if number > 0:
print("{0} is a positive number".format(number))
elif number == 0:
print("{0} is zero".format(number))
else:
print("{0} is a negative number".format(number))
|
list = [21, 54, 75, "JON", 30, "Nishit", 9]
print("list[1] : ", list[1])
print("list[2,5] : ", list[2, 5])
print("list[3:] : ", list[3:])
|
for x in range(15):
if x % 2 == 0:
continue
print("value is : ", x)
|
import prime
import randomnumber
import sys
if __name__ == '__main__':
arg = sys.argv[len(sys.argv)-1]
n = 0
is_prime = False
if arg == '--fermat':
while not is_prime:
n = randomnumber.multiply_with_carry()
is_prime = prime.fermat(n)
print('Random number genera... |
ip = '10.1.1.1'
mask = 4
print(f'IP: {ip} mask {mask}')
# Same with .format
# print("IP: {ip}, mask: {mask}".format(ip=ip, mask=mask))
'''Очень важное отличие f-строк от format: f-строки это выражение, которое выполняется, а не просто строка. То есть,
в случае с ipython, как только мы написали выражение и нажали Ent... |
# for num in range(5):
# print(num)
# else:
# print("Числа закончились")
for num in range(5):
if num == 3:
break
else:
print(num)
else:
print("Числа закончились") |
# ip = input("Введите ip-адрес: ")
#
# for octet in ip:
# print(octet)
# if ip == '':
# ip = '192.168.120.1'
# print("IP по умолчанию: " + ip)
"""
„unicast“ - если первый байт в диапазоне 1-223
„multicast“ - если первый байт в диапазоне 224-239
„local broadcast“ - если IP-адрес равен 255.255.255.255
„unass... |
# ZeroDivisionError: division by zero
# print(2/0)
# TypeError: can only concatenate str (not "int") to str
# print('test' + 2)
# try:
# 2 / 0
#
# except:
# print("You can't divide by zero")
#
try:
print("Let's divide some numbers")
#Всё выполниться до этого выражения
2/0
print("Cool!")
except ... |
"""
What is the largest prime factor of the number 600851475143 ?
"""
def main():
num = 600851475143
for x in range(2, num):
if(num % x == 0):
num /= x;
print(num)
main()
|
from unittest import TestCase, skip
from unittest.mock import Mock
from collections import defaultdict, OrderedDict, Counter
suits = ['s', 'c', 'd', 'h']
def parse_cards(cards):
rank = {
'1': 10,
'J': 11,
'Q': 12,
'K': 13,
'A': 14
}
return sorted([(int(rank.get(c[0... |
'''
Created on Sep 16, 2018
@author: rachelk4
'''
import unittest
from geeksforgeeks.algorithm import isTriplet
class isTripletTest(unittest.TestCase):
def test(self):
ar = [3, 1, 4, 6, 5]
ar_size = len(ar)
self.assertEqual(isTriplet(ar, ar_size), True)
if __name__ == "__main__":
#imp... |
while True:
dice_to_filter = [5, 2, 3, 1, 4]
drop_lowest_number = 100000000;
for eachNumber in dice_to_filter:
print(eachNumber)
def drop_lowest_number(dice_to_filter):
drop_lowest_number = eachNumber
print("lowest number to drop: ", drop_lowest_number)
if dice_... |
while True:
answer1 = input ("Which direction do you want to go? (R for right and L for left) ")
if answer1 == "r" or answer1 == "R":
print("You go right and encounter a person")
print("")
print("You talk to the person and they give you a free sword. ")
print("")
... |
n=input()
n1,n2 = "", ""
for i in range(0,len(n),2):
n1=n1+n[i]
for i in range(1,len(n),2):
n2=n2+n[i]
print(n1,n2)
|
k=int(input())
while(k%2==0):
k=k//2
print(k)
|
import numpy as np
import random
n_strain = 2 #starting off with 2 strains
max_strain = 10
#ASSUMPTION: we are assuming a disease with mutation that happens when more than one strain is in the same person's body at the same time (which is totally not necessarily the case)
a = np.random.rand(max_strain) #i... |
print("""
****************************************
*** PROGRAMACIÓN ORIENTADA A OBJETOS ***
****************************************\n""")
#POLIMORFISMO
class auto():
def desplazamiento(self):
print("Un auto se desplaza utilizando 4 ruedas")
class moto():
def desplazamiento(self):
print("Una mot... |
print("""
****************************************
*** PROGRAMACIÓN ORIENTADA A OBJETOS ***
****************************************\n""")
#Con funciones
print("SEGUNDA PARTE:\n")
class persona1():
def __init__(self,nombre,edad,residencia):
self.nombre=nombre
self.edad=edad
self.resindencia... |
#Decoradores I
def fun_decoradora(funcion_parametro):
def fun_interna():
print("Vamos a ralizar un cálculo:")
funcion_parametro()
print("Hemos terminado el cálculo")
return fun_interna
@fun_decoradora #Con esto ("@ejemplofuncion") llamamos a nuestra función decoradora, en este caso se ... |
from io import open
archivo_texto=open("#29_archivo2.txt","r")
archivo_texto.seek(6)
print(archivo_texto.read())
#Vamos a ver como desplazar el puntero y escribir en donde nosotros queramos con el método "seek(posición_deseada)"
archivo_texto.seek(len(archivo_texto.read())/2) #Esto sirve para posicionar el cursor en... |
print("""
****************************************
*** PROGRAMACIÓN ORIENTADA A OBJETOS ***
****************************************\n""")
#Encapsulamiento en chequeo interno
class Automovil():
def __init__ (self):
self.__largoChasis=250
self.__anchoChasis=120
self.__ruedas=4
self.__... |
print("************************")
print("*** CLASE OPERADORES ***")
print("************************\n")
print("PROGRAMA DE BECAS")
print("")
distancia=int(input("A que distancia vive de la escuela en km? "))
print(distancia)
num_herm=int(input("Cuántos hermanos tiene? "))
print(num_herm)
sala_fam=int(input("Cúal es ... |
print("""
***********************************
*** BUCLE WHILE (Indeterminado) ***
***********************************\n""")
a=1
while a<=10:
print("Ejecución "+str(a))
a+=1 #Es muy necesario agregarle algo que impida que sea un bucle infinito, sino el uso de recursos de la pc causaría un desastre
print("Ejec... |
import numpy as np
data = np.load('monthdata.npz')
#Each column in a month Jan-Dec of a particular year
totals = data['totals'] #total precipitation in a year, jan-dec
counts = data['counts'] #number of oberservations recorded in a given month
# #print(totals)
# print(counts)
# 1) Which city had the lowest total pre... |
fname = input("Enter file name: ")
count = 0
if len(fname) < 1 : fname = "mbox-short.txt"
fn = open(fname)
for line in fn:
line = line.rstrip()
if line.startswith('From:'):continue
if line.startswith('From'):
count+=1
spl = line.split()
print(spl[1])
print("There were", count, ... |
while True:
line = input('>')
if line[0] == '#':
continue #Возвращает обратнов начало
if line == 'done':
break #Если done то срабатывает брейк и работает последний принт
print (line)
print('Done!') |
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 20:34:59 2021
@author: siddh
"""
#https://www.techgig.com/codegladiators/dashboard problem 1
def comp(V,S):
i,j=0,0
m=len(S)
n=len(V)
while j<m and i<n:
if S[j]==V[i]:
j=j+1
i=i+1
r... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 21 19:33:22 2021
@author: siddh
"""
#https://www.codechef.com/problems/LETSC001
def sieve(n):
l=[True for _ in range(n+1)]
l[0],l[1]=False,False
for i in range(2,int(n**.5)+1):
for j in range(2*i,n+1,i):
l[j]=False
return l... |
from typing import List
class Index:
def __init__(self, table, num_columns, primary_key_index: int):
"""
Args:
num_columns: number of columns for users
primary_key_index: which column is primary key
Attributes:
map_list: List of Dict
Dict: k... |
class Rectangle:
def __init__(self,length,width):
self.L = length
self.W = width
def area(self):
area = self.L * self.W
return (area)
def isSquare(self):
if self.L == self.W:
return True
else:
return False
def main():
Squareish = R... |
# -*- coding:utf-8 -*-
"""
@Author:gaopan
@Time:2019/9/16-10:30
@Project:learn_test_develop
@Purpose:
1.对phonebook_1改造
融合手机号查找和姓名查找
增加简单确认选择
对手机号非数字做容错
支持简单的模糊查找
"""
class PhoneBook:
def __init__(self):
# self.phonebook = [{'name': 'a', 'phone': '1'}, {'name': 'b', 'phone': '1'}, {'name': 'a', 'phone': '... |
a=int(input("sizze?"))
b=1
for i in range(a):
for j in range(b):
print("*", end =" ")
print("\n")
if b<=a:
b=b+1
|
numbers = [1, 5, 3, -1, 2]
def max(numbers):
nowmax=numbers[0]
for i in range(len(numbers)):
if nowmax<numbers[i]:
nowmax=numbers[i]
index=i
return nowmax,i
max_number = max(numbers)
print(max_number)
numbers = [123, 100, 345, 200, 5, 500]
def num(numbers):
new=list(r... |
import re
class IgnoreList:
def ignoreDict(il):
with open(r"ignoreList.txt", "r", encoding="utf-8") as fp:
contain = fp.readline()
while contain:
qwe = contain.replace('_'," ")
b = re.findall(r"\w+", qwe)
il.extend(b)
contain = fp.readli... |
# N disk are placed on tower A in decesing order from bottom and we have to move all these disk to Tower C in same oder as in A.
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 1:
print "Move disk 1 from rod",from_rod,"to rod",to_rod
return
TowerOfHanoi(n-1, from_rod, aux_rod, t... |
list2 =[1,2,5,7,9,11,25,67,77,89,94,101]
num = int(input("Enter the number to be searched:"))
n = len(list2)
min =0
max =n-1
for i in range(n):
avg = (min + max)//2
if num == list2[max] :
print("Number found at : ",max)
break
elif num == list2[min] :
print("Number found ",min)
... |
class node :
def __init__(self,key):
self.data = key
self.left = None
self.right = None
def insert(self,key):
if self.data :
if key < self.data :
if self.left is None:
self.left = node(key)
else:
... |
balance = float(input("Enter your balance"))
withdrawal = 500
class MyError(Exception):
def __init__(self,val):
self.val = val
try:
if balance > withdrawal:
print(balance - withdrawal)
else :
#raise NameError
raise MyError("bad")
except NameError:
print("Insuffecient Bal... |
#mouse click events ...left click , right click and middle click all will trigger different events
from tkinter import *
root = Tk(className='click window ')
def leftclick(event):
print("LEFT ")
def rightclick(event):
print("RIGHT ")
def click(event):
print("CENTER ")
frame = Frame(root,width =300,he... |
from tkinter import *
root = Tk(className='click window ')
one = Label(root,text ="Enter your name" , bg = 'red',fg = 'white')
#one.pack()
one.grid(row =0 ,column = 0)
one = Label(root,text ="HELLO UNKNOWN" , bg = 'red',fg = 'white')
#one.pack()
one.grid(row =1 ,column = 1)
#lets create entry box
Tk()
name = StringVar... |
#we have to find the number of distinct common element between 2 arrays assuming the first array has larger length
a = [10,5,20,15,30,30,5]
b=[30,5,80,15,30]
count = 0
for i in range(len(a)):
flag =True
for j in range(i-1,-1,-1):
if a[j] == a[i]:
flag = False
break
if flag... |
# codes from practice on trees on geeks for geeks
#Determine if Two Trees are Identical Method 1 - compare inorder/preorder/postorder/level order of both trees if same both trees are identical
def inorder(root,queue):
if root is None :
return
else :
inorder(root.left,queue)
queue.a... |
#left rotate by 1
def rotateby1(arr):
temp = arr[0]
for i in range(1,len(arr)):
arr[i-1] = arr[i]
arr[len(arr) -1 ] = temp
return arr
l1 = [1,2,3,4,5]
#print(rotateby1(l1))
# rotate by d using rotate by 1
def rotatebyd(arr,d):
for i in range(0,d):
rotateby1(arr)
return arr
#... |
#try except finallly
a = int(input("Enter the 1st number:"))
b = int(input("Enter the 2nd number:"))
try :
print(a/b)
except Exception as e :
print("Error --" ,e)
finally:
print("Job done ") |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'equalStacks' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY h1
# 2. INTEGER_ARRAY h2
# 3. INTEGER_ARRAY h3
#
def equalStac... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'decentNumber' function below.
#
# The function accepts INTEGER n as parameter.
#
def decentNumber(n):
# Write your code here
if n%3==0:
print('5'*n)
else:
a=0
while a<n+1:... |
#!/bin/python3
import os
import sys
# Complete the solve function below.
def solve(n):
#we need to check if n=(m(m+1))//2 --> m^2 + m - 2n = 0 for some natural no. m
# m = (-b+-(D^0.5))/2a
D=1+(8*n)
m=(-1+(D**0.5))/2
ans='Better Luck Next Time'
if m==int(m):
ans='Go On Bob... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'extraLongFactorials' function below.
#
# The function accepts INTEGER n as parameter.
#
def extraLongFactorials(n):
# Write your code here
ans=1
for i in range(2,n+1):
ans*=i
print(ans... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=int(input())
a=[]
for i in range(t):
b=[]
b=list(map(str, input().split()))
a.append(b)
for x in range(len(a)):
try:
print(int(a[x][0])//int(a[x][1]))
except ZeroDivisionError:
print ("Error Code: inte... |
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'pickingNumbers' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#
def pickingNumbers(a):
# Write your ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
ans=0
for i in range(n):
ans+=int(input())
print(str(ans)[:10])
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'funnyString' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
def funnyString(s):
# Write your code here
normal=[ord(i) for i in s]
d... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'encryption' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING s as parameter.
#
def encryption(s):
# Write your code here
s=s.replace(' ','')
row=math.f... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
arr.sort()
minimum=sum(arr[0:4])
maximum=sum(arr[1:5])
ans=[]
ans.append(str(minimum))
ans.append(str(maximum))
print(' '.join(ans))
if ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
arr=list(map(int,input().split()))
if all(i>0 for i in arr):
if any(str(i)==str(i)[::-1] for i in arr):
print('True')
else:
print('False')
else:
print('False') |
#Variables and data types
i = 20
print(type(i))
j="Hello"
print(type(j))
x,y,z = 8, 12.4 , 'hello'
print(type(x),type(y),type(z))
a = b = c = "Orange"
print(a)
print(b)
print(c)
x = "awesome"
print("Python is " + x)
#A variable name must start with a letter or the underscore character
#A variable name cannot start... |
#Loops
#FOR
#Includes 2, excludes 6
for x in range(2, 6):
print(x)
#Step value
for x in range(2, 10, 2):
print(x)
#Looping through each letter of a string
for x in "banana":
print(x)
#Break
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
#Continue
fruits = ["... |
#1. Dadas as variáveis:
Planeta = "Terra"
Diametro = 12742
#Use format() para printar a seguinte frase:
#O diâmetro da terra é de 12742 kilômetros.
print('O diâmetro da {} é de {} kilômetros. '.format(Planeta, Diametro)) |
"""
Find The Percentage
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.
"""
if __name__ == '__main__':
n = int(input())
student_marks = {... |
print("hello")
print("Saya sedang belajar python")
a = 8
b = 6
print("variable a = ", a)
print("variable b = ", b)
print("Hasil penjumlahan a+b = ", a+b)
a = (input("masukan nilai a : "))
b = (input("masukan nilai b : "))
print("variable a = ", a)
print("variable b = ", b)
print("Hasil penggabungan {0}&{1}=%s".format... |
from itertools import count
from functools import reduce
def trees_on_slope(tree_map, slope):
height, width = len(tree_map), len(tree_map[0])
x_coord_cnt, y_coords = count(0, slope[0]), range(0, height, slope[1])
xy_coords = map(lambda y: (next(x_coord_cnt) % width, y), y_coords)
return sum(map(lambd... |
a = input('Введите массив\n')
squares = set()
# Функция form из исходной строки с числами заданного массива
# формирует матрицу смежности являющуюся входными данными
# для задачи поиска гамильтонова пути
def form(stroka):
b = list()
for i in stroka.split():
b.append(int(i))
b.sort()
# squares ... |
# -* - coding: UTF-8 -* -
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
# 这是类的变量
print "gexing class set"
population = 0
# 构造函数
def __init__(self, name):
'''Initializes the person's data.''' #类的文档字符串
import ipdb; ipdb.set_trace()
prin... |
'''Given a sqlite database file, will convert the database to a CSV file.
Takes two command line arguments:
1) The path to the database file (Mandatory argument).
2) The path or name of a CSV file (optional).
'''
# Standard modules
import sys
import sqlite3
# Non-standard modules
import pandas.io.sql as sql
__author... |
def spiralMatrixPrint(endRowIndex,endColIndex,matrix) :
startRowIndex = 0
startColIndex = 0
while (startRowIndex < endRowIndex and startColIndex < endColIndex):
for i in range (startColIndex,endColIndex+1):
print(matrix[startRowIndex][i],end =' ')
#print(" ")
s... |
# A:Apple, Avocado
# B : Banana, Berry
def countElements(inpFruits):
dict = {}
maxCount=0
for ele in inpFruits:
firstChar = ele[0:1]
if firstChar in dict:
dict[firstChar].append(ele)
currentListCount= len(dict[firstChar])
if(currentListCount> maxCount):
... |
from histogram import *
from sample import random_sentence
from sentence_generator import markov, random_word
def random_walk_sentence():
word_list = read_word_file('poemtest.txt')
histogram = make_histogram(word_list)
starting_word = random_word_frequency(histogram)
markovv = markov(word_list)
sen... |
# shekhar r vanjarapu
#
# Program for an time counter
# This program is an example for recurssion
#
n = input("Enter the no. of seconds you would like to countdown")
def count_down(n):
if n == 0:
print "Blast Off!!!"
else:
print n
count_down(n-1)
|
def problem3_3(month, day, year):
""" Takes date of form mm/dd/yyyy and writes it in form June 17, 2016
Example3_3: problem3_3(6, 17, 2016) gives June 17, 2016 """
month_list=("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
m... |
import sqlite3
# DB 연결하기
dbpath = "test2.sqlite"
conn = sqlite3.connect(dbpath)
# 테이블 생성하기
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS items")
cur.execute("""CREATE TABLE items (
item_id INTEGER PRIMARY KEY,
name TEXT,
price INTEGER)""")
conn.commit()
# 데이터 넣기
cur = conn.cursor()
cur.execute(
... |
# cs212 ; Unit 2 ; 41
# --------------
# User Instructions
#
# Write a function, compile_word(word), that compiles a word
# of UPPERCASE letters as numeric digits. For example:
# compile_word('YOU') => '(1*U + 10*O +100*Y)'
# Non-uppercase words should remain unchaged.
def compile_word(word):
"""Compile a word of... |
# cs215 ; Final Exam ; 5
#
# Design and implement an algorithm that can preprocess a
# graph and then answer the question "is x connected to y in the
# graph" for any x and y in constant time Theta(1).
#
#
# `process_graph` will be called only once on each graph. If you want,
# you can store whatever information you ... |
# cs215 ; Unit 1: A Social Network Magic Trick ; 15
# counting steps in naive as a function of a
def naive(a, b):
x = a
y = b
z = 0
while x > 0:
z = z + y
x = x - 1
return z
def time(a):
# The number of steps it takes to execute naive(a, b)
# as a function of a
steps = ... |
# cs215 ; Unit 1: A Social Network Magic Trick ; 14
import math
def time(n):
""" Return the number of steps
necessary to calculate
`print countdown(n)`"""
steps = 0
# YOUR CODE HERE
return steps
def countdown(x):
y = 0
while x > 0:
x = x - 5
y = y + 1
print y
prin... |
#!/usr/bin/env python3
import turtle
import math
def raute(size, winkel):
turtle.right(winkel / 2.0)
for w in [winkel, 180 - winkel, winkel, 180 - winkel / 2.0]:
turtle.forward(size)
turtle.left(w)
def timmer_raute(n, size, winkel):
for i in range(n):
raute(size, winkel)
... |
import definitions
import random
#api example sine = definitions.trig["functions"]["sine"]["name"]
def triviaChoice(triv):
'''
Randomly generates and returns a random piece of data.
:type triv: string
:param triv: key used to access data interface subject of choice
'''
subject = definitions.tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.