text stringlengths 37 1.41M |
|---|
## def binary(s,e):
## last = s[-1]
## first = s[0]
## if len(s) == 2 and (s[0] == e or s[1] == e):
## return True
## else:
## mid = int(first+last+1)/2
## if e<= mid:
## last = mid
## else:
## first = mid
def selection_sort(l):
for i in range(0,len... |
# Finding if a given year is a leap year or not
##
##y = 1600
##if y%4 == 0:
## if y%100 == 0:
## if y%400 == 0:
## print ('Leap year')
## else:
## print ('Not a leap year')
## else:
## print ('Leap year')
##else:
## print ('Not a leap year')
y = 1664
if y%4 ... |
# This program gives nth prime number.
# For example here n=1000
def prime(x):
i = 2 # loop variable - divisor
if x < 2 or isinstance (x,float):
return False
elif x==2 or x==3:
return True
else:
while i <= (x**0.5):
if x%i == 0:
return ... |
# University Grading system
A=75
B=45
if A>=55 and B>=45:
print ('Passed with good grades')
elif A>=45 and B>=65:
print ('Passed')
elif A>=65 and B<=45:
print ('Reappear for B')
else:
print ('Fail')
|
# Each new term in the Fibonaccisequence is generated by adding the previous
# two terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
# write a program to generate nth term of fibbonacci series using recursion.
def fib(n):
if n == 1 or n == 0 :
return 1
... |
def partirLista(lista):
if isinstance(lista,list):
return PL_aux(lista,[],[])
def PL_aux(lista,sublista,resultado):
if lista==[]:
return resultado + [sublista]
elif lista[0]>=0:
return PL_aux(lista[1:],sublista+[lista[0]],resultado)
else:
return PL_au... |
"""csvFilter
Filters out unneccsary rows from large csv files.
"""
import csv, itertools
import sys, os
def sortcsv(path, sortkey):
directory = os.path.dirname(path)
filename = os.path.basename(path)
outpath = os.path.join(directory, "SORTED_" + filename)
with open(path,'r') as fin, open(outpa... |
import cv2
import numpy as np
def view_face_frame(face, frame):
"""
View face frame.
:param face: face from faces
:param frame: frame you want to view face to
"""
x, y = face.left(), face.top()
x1, y1 = face.right(), face.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
... |
r=5
h=10
Vwtr=15
t=eval(input('enter the time'))
Vc=3.14*r**2*h
Vwtr= 15*t
if Vwtr > Vc:
print('overflow')
elif Vwtr==Vc:
print('tank is full')
else:
print('underflow')
|
#03 - Utilizando estruturas de repetição com teste lógico, faça um programa que peça uma senha para iniciar seu processamento, só deixe o usuário continuar se a senha estiver correta, após entrar dê boas vindas a seu usuário e apresente a ele o jogo da advinhação, onde o computador vai “pensar” em um número entre 0 e 1... |
vowels1 = ['a', 'e', 'i', 'o', 'u']
print(vowels1) # ['a', 'e', 'i', 'o', 'u']
print(type(vowels1)) # class list
vowels2 = ('a', 'e', 'i', 'o', 'u')
print(vowels2) # ('a', 'e', 'i', 'o', 'u')
print(type(vowels2)) # class tuple
# vowels2[2] = 'I' # tuple is immutable type, we can't change tupl... |
for number in range(5):
print(number)
#####################################
b = list(range(1, 10, 2))
print(b) # [1, 3, 5, 7, 9]
for number in [0, 1, 2, 3, 4]:
print(number)
#####################################
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 6:
print("Item found!")
b... |
def outer():
def inner():
print('This is inner.')
print('This is outer, invoking inner.')
# Функцію inner можно викликати лише з тіла функції outer, тому що inner знаходиться в області видимості outer
inner()
outer()
|
def ordered_sequential_search(alist, item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
else:
# check if item searched is greater than item at a particiular index
# stop if t... |
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
while first <= last:
mid = (first + last)//2
if input_array[mid] == value:
return input_array.index(value)
elif input_array[mid] < value:
first = mid + 1
elif input_arra... |
from tkinter import *
from tkinter import ttk, messagebox
import csv
from datetime import datetime
##########
import sqlite3
# create data base
conn = sqlite3.connect('Expense.db')
# create operater
c = conn.cursor()
# create table
'''
'Details(details)'
'Rate(rate)'
'Quantity(quantity)'
'Discou... |
def findGCD(n1, n2):
while(n2 != 0):
if n1 > n2:
n1 , n2 = n2, n1 % n2
else:
n1, n2 = n1, n2 % n1
return n1
def modInverse(a, m):
m0 = m
y = 0
x = 1
# For (n mod 1) for any n will always be equal to zero
if (m == 1):
return 0
while (a >... |
"""
dictionary comprehension
"""
numbers = [1,2,3,4,5]
names = ['a','b','c','d','e']
students = {}
for i in range(len(names)):
students[numbers[i]] = names[i]
print(students)
students2 ={numbers[i]:names[i] for i in range(len(names))}
print(students2)
# num_name = zip(numbers, names)
# print(num_name)
for x in ... |
"""
scikit-learn 패키지를 이용한 knn(k Nearest Neighbor : 최근접이웃)
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, classification_report
import numpy as n... |
for i in range(5):
print(i, end = ' ')
print()
for i in range(1,5):
print(i, end=' ')
print()
for i in range(1,5,2):
print(i, end=' ')
print()
for s in 'Hello, Python!':
print(s, end=' ')
print()
lang = ['pl/sql', 'r', 'python', 'java']
for l in lang:
print(l, end=' ')
print()
for i in range(le... |
# ---BIRTHYEAR EXTRACTION---
# Extracts the birthyear from the birthdate and copies it into the birthyear column
# if the latter is empty or has a different birthyear
# In CSV: birthDate is position 4, birthYear is position 5
with open('creator_data.csv', encoding = 'utf-8') as creator_input:
with open('creator_da... |
'''
Example to send file object through queue and consumer will process the file object received i.e basically a json file
'''
import json
import concurrent.futures
import logging
import queue
import random
import threading
import time
#Sample data of data2.json
'''
data = {}
data['people'] = []
data... |
# For Lists/Looping
# iterating through two lists
# m1
from collections import defaultdict, ChainMap
list_a = ['a', 'b', 'c']
list_b = [1, 2, 3, 4]
for i in range(min(len(list_a), len(list_b))):
print(list_a[i], list_b[i])
# better way of doing this is using zip.
for a, b in zip(list_a, list_b):
print(a, b... |
"""A python program that implements dutch national flag algorithm i.e sorts the arrays of 0s, 1s and 2s in single pass and
using constant space.
The algorithm which I am going to implement works as follows -
1. It makes use of three pointers namely 0's pointer, 1's pointer and Traversing pointer which traverses through... |
current_level = [[A]
next_level = deque()
paths = []
while current_level:
node = current_level.pop()
if node == p or node == q:
ans.apend(current_level)
next_level.extend([node.left, node.right])
if not current_level:
if next_level:
current_level = next_level
for a,b in zip(reversed(path[0]),reversed(path[1... |
class Node(object):
def __init__(self,val):
self.val = val
self.leader = None
self.finish = None
self.visited = False
def __str__(self):
return str(self.val)+","+str(self.finish)
class Edge(object):
def __init__(self,start,end):
self.start = start
self... |
# implementation of topological sort using a. Vertex Deletion Algo and b. DFS implementation
class Node(object):
def __init__(self, value):
self.value = value
self.visited = None
self.order = None
def __str__(self):
return str(self.value)
class Edge(object):
def __init__(s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Tomada de decisoes utilizando IF, ELIF e ELSE. """
"""
Ex:
if (True):
realizar esta tarefa
elif (True):
realizar esta tarefa
else:
realizar esta tarefa / ou sair
"""
print("\n ======== Perguntando ao usuário ========")
acao = (input("Digite [1] para SIM ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Herança - Exemplo Eletrônicos."""
# Criando classe PAI "Eletronico"
class Eletronico:
def __init__(self):
self.ligado = "Desligada"
return False
def ligar(self):
self.ligado = "Ligada"
return True
def desligar(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" FOR - Percorrendo uma lista. """
names = ["Adam", "Alex", "Mariah", "Martine", "Columbus"]
for nome in names:
print(nome)
|
# Convertendo STRING para INTEIRO
numero = int("12")
# Mostra na tela o conteudo da varial "numero"
print("O número convertido é: {}" .format(numero))
# Outra maneira utilizando (input)
valor_digitado = int(input("Digite um número inteiro: "))
print("O número inteiro digitado é: {}" .format(valor_digitado))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Função enumerate() em Python. """
# a função "enumerate()" retorna o "indice e o valor"
# contidos em uma "lista, tupla ou string"
tupla = (11, 3, 4, 55, 77)
lista = ["casa", "batata"]
for indice, valor in enumerate(tupla):
print(f"Índice {indice} - {valor}")
t1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dicionários de Dados."""
"""
Operadores de Identidade
is - avalia se ambos os lados têm a mesma identidade
is not - avalia se ambos os lados têm identidades diferentes
"""
# as chaves podem ser de qualquer tipo imutável
elementos = {
# chave: valor
# ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Dicionários de dados, listas e funções."""
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
for chave in prices:
print(f"=> {chave} <=")
print("Preço: ", prices[chav... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Utilizando a função "enumerate()". """
print("==== Exemplo | Função enumerate() ====")
lista_numeros = [100, 200, 300, 400, 500, 600, 700, 800]
for index, item in enumerate(lista_numeros):
lista_numeros[index] += 1000
print(index, item)
print(lista_numeros)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Interagindo com usuário. """
print("==== Testando o FOR e Função range() ====")
inicio = int(input("Digite o INÍCIO: "))
fim = int(input("Digite o FIM: "))
passo = int(input("Digite o PASSO: "))
loop = [inicio, fim, passo]
for item in range(*loop):
print(item)
p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Funções: Parâmetros x Argumentos. """
# definindo uma função
# com "dois parâmetros"
def soma(num1, num2):
"""
Esta função soma dois numeros
e imprime o resultado
"""
resultado = num1 + num2
print(f"Soma de {num1} + {num2} = {resultado}")
#... |
import random
# I created this as a way to practice powers of 2 for a CS class
def powerof2():
keep_going = True
userRange = input("What range of powers of 2? ")
userRange = int(userRange)
while keep_going:
for i in range(userRange):
power = random.randint(0,10)
... |
def day_month(n):
if n == 0:
print("Sunday")
elif n == 1:
print("Monday")
elif n == 2:
print("Tuesday")
elif n == 3:
print("Wednesday")
elif n == 4:
print("Thursday")
elif n == 5:
print("Friday")
else:
print("Saturday")
print(day_month... |
def converter(list2):
list2 = [int(i) for i in list2] # Converts each item in the list to an integer
list3 = sum(list2) # Adds the numbers in the list
return list3
print(converter([1, 2, "3", 4, "5", 10, "12"]))
|
""" Detemine if a list is sorted using a generator defined by comprehension"""
items1 = [6, 8, 19, 20, 23, 41, 49, 53, 60, 71]
items2 = [2, 23, 34, 12, 45, 56, 78, 89, 94, 97]
def is_sorted(itemList):
return all(itemList[i] <= itemList[i+1] for i in range(len(itemList)-1))
print(is_sorted(items1))
print(is_sorte... |
"""
Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.
Input:
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'N' denoting the size of array. The second l... |
# https://www.hackerrank.com/contests/bppc14/challenges/string-and-performing-queries
s = input()
Q = int(input())
for i in range(Q):
q = [i for i in input().split()]
if q[0] == "1":
s = s[::-1] #reverse
else:
if q[1] == "1":
s = q[2] + s
elif q[1] == "2":
s =... |
def swap(x,i,j):
"""
交换x的i,j位置元素
"""
temp = x[i]
x[i] = x[j]
x[j] = temp
|
a = input().rstrip()
b = input().rstrip()
if a[-1] == b[0] and b[-1] != 'n':
print('OK')
else:
print('NG')
|
s = input().rstrip()
if s == 'candy' or s=='chocolate':
print('Thanks!')
else:
print('No!')
|
c1,c2 = input().split()
if c1 == 'J' and c2 =='J':
c2 = 'Q'
print(c1,c2)
|
c = int(input())
if c == 0:
c = 1
else:
c = 3*c
print(c)
|
exit = 1
while exit == 1:
summ = float(input ('Vvedite summu: '))
ostatok = summ
nominals = [500, 200, 100, 50, 20, 10, 5, 1]
nominalIndex = 0
while ostatok > 0 and nominalIndex < len (nominals):
x = ostatok // nominals[nominalIndex]
ostatok = ostatok - (x * nominals[nom... |
def isNatural(n):
#
lst = []
# k
k = 0
# 2 N
for i in range(2, n + 1):
# 2
for j in range(2, i):
#
if i % j == 0:
k = k + 1
# ,
if k == 0:
lst.append(i)
else:
k = 0
if n in lst:
return True
else:
return False |
def pow(x, n):
y = x
# вычисление функции x^n
for _ in range(n - 1):
y = y * x
return y
# вычисление функции x^n другим способом
def pow2(x, n):
if n == 0:
return 1
else:
return x * pow2(x, n - 1)
# вычисление функции n!
def faktorial(n):
if n == 0:
return 1
return n * faktorial(n - 1) |
# coding: utf-8
# A regular expression is a text matching pattern that is described in a
# specialized syntax. The pattern has instructions, which are executed with a
# string as an input to produce a matching subset. The Python module to perform
# regular expression is re. Typically, re is used to match or find s... |
# coding: utf-8
# In this notebook we will discuss:
# 1. Functions
# 2. Arguments and outputs
# 3. default argument
# 4. keyword based arguments
# In[29]:
'''
Syntax for function
def name_of_the_function(list of arguments):
statements that need to be executed
return value
'''
def increment(a):
b = a+1... |
import os
from abstract import module
class resultor(module):
"""
Resultor of the network saves down resultor. The initilizer initializes the directories
for storing results.
Args:
verbose: Similar to any 3-level verbose... |
import math
n = int(input())
count = 0
for i in range(1, n + 1, 2):
divisors = 0
for j in range(1, int(math.sqrt(i)) + 1):
if i % j == 0:
if j * j == i:
divisors += 1
else:
divisors += 2
if divisors == 8:
count += 1
print(count) |
"""
1) We are going to sum each day’s sales into an accumulator/sum variable for display.
2) Make sure the user enters a valid number.
3) Step 1: Initialize input variables:
daysOfWeek[] – holds our 7 days
dailySales[] – holds our sales for each day of week
totalSales – accumulator to hold total sales
Step 2... |
import datetime
from datetime import datetime
import tkinter as tk
from tkinter import *
from re import findall
us_holidays = {'Christmas': [12,25,datetime.now().year], 'Halloween': [10,31,datetime.now().year], 'Independence Day': [7,4,datetime.now().year],
'New Year': [1,1,datetime.now().year], 'MLK Day': [1,15,date... |
"""
Original gumball machine (without patterns)
Author: tuanla
Date: 2018
"""
class GumballMachine:
SOLD_OUT = 0
NO_QUARTER = 1
HAS_QUARTER = 2
SOLD = 3
def __init__(self, count):
self._count = count
if count > 0:
self._state = GumballMachine.NO_QUARTER
else:... |
import multiprocessing
import threading
import time
# 线程是cpu调度的最小单位,进程是操作系统分配资源和调度的最小单位
# 进程和线程都是一个时间段的描述,是CPU工作时间段的描述,不过是颗粒大小不同
class SubThread(threading.Thread):
'''
用 threading.Thread 创建进程,一种方法是传递 callable 对象,另一种是在子类中覆盖 run 方法
'''
def __init__(self):
threading.Thread.__init__(self)
def ru... |
from helpers import check_user_existence, get_user
from auth import login
username = input("Enter your username: ")
password = input("Enter your password: ")
if check_user_existence(username):
user = get_user(username)
logged_in = login(user, password)
if logged_in:
user["logged_in"] = True
... |
s = input()
total=0
for x in range(len(s)):
if ((x %2) !=0):
if int(s[x])*2>9:
total+= int(s[x])*2%10+int(int(s[x])*2/10)
else:
total+=int(s[x])*2
else:
total+=int(s[x])
print(total)
if total%10 ==0:
print("Your number ID is okay!")
|
"""
Prints the internal representation of a document as a string
"""
import sys
from Element import Element
from AztexCompiler import AztexCompiler
def is_text_file(filename):
return filename.endswith('.txt')
def input_text(argv):
""" gets input text from command line args """
inputf = input_file(argv)
if inpu... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Find all duplicates in an array where the numbers in the array are in the
range of 0 to n-1 where n is the size of the array. For example: [1, 2, 3, 3]
is okay but [1, 2, 6, 3] is not. In this version of the challenge there can
be multiple duplicate numbers as well.
"... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Check if a string contains only balanced delimiters (eg. (), [], {}).
"""
import unittest
import sys
def is_balanced(string: str) -> bool:
"""
Time: O(n), where n=string length
Space: O(n), worst-case it consists of open delimiters only
"""
ope... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
List all permutations of `string`.
Time: O(n^2) where n = len(string)
"""
import unittest
def permutate(string):
if string == '':
return ['']
permutations = []
for i, char in enumerate(string):
for permutation in permutate(string[:i] +... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Insert and delete a node from a linked list.
"""
from typing import List, Optional
import unittest
class Node:
def __init__(self, value, next: Optional['Node'] = None):
self.value = value
self.next = next
def to_array(self) -> List:
... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Calculate the `n`-th value of the Fibonacci sequence.
Time: O(n)
Memory: O(1)
"""
import sys
import unittest
def calculate(n, result = 0, nxt = 1):
if n == 0:
return result
else:
return calculate(n - 1, nxt, nxt + result)
class Test (unitte... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Pick `count` randomly selected items from `array`.
(Uses Fisher-Yates shuffle algorithm.)
Time: O(count)
"""
import random
import unittest
def pick_random(array, count):
shuffled_by_pos = {}
elems = []
for i in range(0, len(array)):
if len(ele... |
arsenal = input().split(":")
commands = input().split()
the_deck = []
while not commands[0] == "Ready":
command = commands[0]
card = commands[1]
if command == "Add":
if card in arsenal:
the_deck.append(card)
else:
print("Card not found.")
elif command == "Inser... |
# nai barzoto reshenie
# divizor = int(input())
# bound = int(input())
# res = int(bound / divizor) * divizor
# print(res)
divizor = int(input())
bound = int(input())
for num in range(bound, 0, -1):
if num % divizor == 0:
print(num)
break
|
class Zoo:
__animals = 0
def __int__(self, name):
self.name = name
self.mammals = []
self.fishes = []
self.birds = []
def add_animal(self, species, names):
if species == 'mammal':
self.mammals.append(names)
elif species == 'fish':
sel... |
text = input()
if text == 'Johnny':
print(f'Hello, my love!')
elif text == text:
print(f'Hello, {text}!')
|
number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
def sum_numbers(num_1, num_2):
return num_1 + num_2
def subtract(sum, three_num):
return sum - three_num
def add_and_subtract(one, two, three):
sum = sum_numbers(one, two, )
res = subtract(sum, number_3)
print(res)
add_a... |
string = input()
digits = []
letters = []
other = []
for char in string:
if char.isalpha():
letters.append(char)
elif char.isdigit():
digits.append(char)
else:
other.append(char)
print(''.join(digits))
print(''.join(letters))
print(''.join(other)) |
budget = float(input())
flour = float(input())
cozunak_count = 0
eggs_count = 0
praice_eggs = flour * 0.75
praice_milk = (flour * 0.25) + flour
milk_needet = praice_milk *0.25
cozunak_praice = praice_eggs + milk_needet + flour
while budget > cozunak_praice:
cozunak_count +=1
eggs_count += 3
budget -= coz... |
num_wagons = int(input())
list_wagons = [0] * num_wagons
command = input()
while command != 'End':
token = command.split()
if token[0] == 'add':
number_of_people = int(token[1])
list_wagons[-1] += number_of_people
elif token[0] == 'insert':
index = int(token[1])
number_of_p... |
n = int(input())
for row in range(1, n + 1):
print("*" * row)
for negative_row in range(n-1, 0, -1):
print('*' * negative_row)
|
text = input()
result = text.split()
test = []
for num in result:
num = int(num)
num *= -1
test.append(num)
print(test) |
number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
#
#
# def smallest_num(num_1, num_2, num_3):
# smolest = 0
# if num_1 < num_2 and num_1 < num_3:
# smolest = num_1
# if num_2 < num_1 and num_2 < num_3:
# smolest = num_2
# if num_3 < num_1 and num_3 < num_2:
# ... |
#wap to print first three elements of list
list=[1,2,3,4]
print(list[0:3])
#wap to print last 3 elements from list
list=[1,2,3,4]
print(list[-3:])
#wap to print only even position elements from the list -index-0,2,4
list=[1,2,3,4]
print(list[0::2])
#wap to print only odd position from list
list=[1,2,3,4]
print(list[... |
"""
LeetCode 791. Custom Sort String
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
S was sorted in some custom order previously. We want to permute the characters of T so
that they match the order that S was sorted. More specifically, if x occurs before y in... |
"""
LeetCode 434. Number of Segments in a String
Count the number of segments in a string, where a segment is defined to be a
contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
O... |
"""
LeetCode 461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Expla... |
"""
LeetCode 922. Sort Array By Parity II
Given an array A of non-negative integers, half of the integers in A are odd,
and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies th... |
"""
LeetCode 345. Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
"""... |
# Data inspection
# Variables can be inspected in the VARIABLES section of the Run view or by hovering over their source in the editor
# Variables and expressions can also be evaluated and watched in the Run view's WATCH section.
# By using the Call Stack window, you can view the function or procedure calls that are cu... |
# WORKING WITH STRINGS
# Printing a string
# print("Giraffe Academy")
# Create a new line in string
# print("Giraffe\nAcademy")
# Putting a quotation mark inside a string
# print("Giraffe\"Academy")
# String variable
# phrase = "Giraffe Academy"
# print(phrase)
# Concatenation
# phrase = "Giraffe Academy"
# print(... |
import sys
def fixSentance(aString):
x = 0
while (x != 1):
temp = aString
temp.split('.')
print temp.split('.')
temp = temp.replace('_',' ').strip().lower().capitalize()
if ((temp[-1] != '.') & (temp[-1] != '!') & (temp[-1] != '?')):
temp = temp + '.'
return temp
stringToFix = str(sys.argv[1])
print... |
import re
def camel_to_lowdash(word):
word=word.group(0)
res=''+word[0].lower()
for letter in word[1:]:
if letter.isupper():
res+='_'+letter.lower()
else:
res+=letter
return res
def remove_camel(text_string):
camel=re.compile(r"([a-z]+([A-Z][a-z... |
#Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
#Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
#Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", ... |
n1 = input("Enter the no 1")
n2 = input("Enter the no 2")
n3 = input("Enter the no 3")
if (n1<n2 and n1<n3):
l1 = n1
elif (n2<n1 and n2<n3):
l1 = n2
elif (n3<n1 and n3<n2):
l1 = n3
print ("Small est Number", l1) |
class Animal(object):
def __init__(self, species):
self.species = species
def display(self):
print(self.species)
obj = Animal(species="Lion")
obj.display()
class Parent(object):
def __init__(self):
print("Parent")
def parentfunc(self):
print("Parent Fun")
class Child(P... |
# -*- coding: utf-8 -*-
"""Demonstrate high quality docstrings."""
from random import randint
def quickselect(arr, k):
"""Doc String."""
pivot = randint(0, len(arr))
sub_min = [i for i in arr if i < arr[pivot]]
sub_pls = [i for i in arr if i > arr[pivot]]
v = len(sub_min) + 1
if v == k:
... |
# This function finds the square root of a number to within 0.0001
# This does not use anything imported from math
import sys
def toBRooted():
"""
This function takes the number to be square rooted from the user
Input: None
Output: User defined number and whether it is positive or negative
"""
t... |
from tkinter import *
ventana =Tk()
ventana.title("Calculadora")
ventana.configure(bg="grey")
#recursos
mensaje = StringVar()
#Funciones a usar para las cuatro operaciones aritmentias
def sumar():
a=int(e_texto.get())
b=int(e_texto2.get())
print(a," + ",b)
print('la suma es: ',a+b)
mensaje.set(a+... |
# Scrape the NASA Web Page
# and collect the latest News Title and Paragraph Text.
# Assign the text to variables that you can reference later.
def init_browser():
executable_path = {"executable_path": "mission_to_mars\chromedriver"}
return Browser("chrome", **executable_path, headless=False)
def scrape_info... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the bonAppetit function below.
def bonAppetit(bill, k, b):
total=0
i=0
while i<(len(bill)):
if(i!=k):
total=total+int( bill[i])
i+=1
else:
i+=1
if((total//2)-b==0)... |
########################################
# PROJECT XXX - Min Heap and Sort
# Author:
# PID:
########################################
class Heap:
# DO NOT MODIFY THIS CLASS #
def __init__(self, size=0):
"""
Creates an empty hash table with a fixed capacity
:param capacity: Initial size ... |
def init(data):
data['first'] = {}
data['middle'] = {}
data['last'] = {}
def lookup(data, label, name):
return data[label].get(name)
def store(data, *full_names):
for full_name in full_names:
names = full_name.split()
if len(names) == 2:
names.insert(1, '')
... |
print("Hello World")
print("Amorcito")
print("teamo mas que tu ami")
print(type("Amorcito"))
# El simbolo mas puede servir para contactenar o sumar
# va depender si son numeros o texto
print("Bye" + "World")
# Numeros enteros o Integer
print (30)
print (30.5)
# Numeros decimales o FLOAT
print(type(30.5))
Print(t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.