text stringlengths 37 1.41M |
|---|
"""Group Anagrams
Write a method to sort an array of strings so that all the anagrams are next to
each other.
Hints:
#177
How do you check if two words are anagrams of each other? Think about what the definition
of "anagram" is. Explain it in your own words.
#182
Two words are anagrams if they contain the same chara... |
def merge_sort(alist):
print("Splitting ",alist)
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
merge_sort(lefthalf)
merge_sort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(right... |
"""Permutations without Dups
Write a method to compute all permutations of a string of unique characters.
Hints:
#150
Approach 1: Suppose you had all permutations of abc. How can you use that to get all
permutations of abcd?
#185
Approach 1 :The permutations of abc represent all ways of ordering abc. Now, we want
to... |
"""Delete Middle Node
Implement an algorithm to delete a node in the middle
(i.e., any node but the first and last node, not necessarily the exact middle)
of a singly linked list, given only access to that node.
EXAMPLE
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, b... |
import unittest
'''Method 1
Time complexity : O(2^n)
'''
def fibonacci(n):
if n == 0 or n == 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
'''Method 2
Time complexity : O(n)
'''
def fibonacci_top_down(n):
return __fibonacci_top_down(n, {})
def __fibonacci_top_down(n, memo):
if n == 0 o... |
# Below is a link to a 10-day weather forecast at weather.com
# Use urllib and BeautifulSoup to scrape data from the weather table.
# Print a brief synopsis of the weather for the next 10 days.
# Include the day, date, high temp, low temp, and chance of rain.
# You can customize the text as you like, but it should be ... |
# def addN(n):
# def add(x):
# return x+n
# return add
class addN(object):
def __init__(self, n):
self.n = n
# 括号运算符
def __call__(self, x):
return x+self.n
add3 = addN(3)
add4 = addN(4)
print(add3(42), add4(42))
|
# 25. Reverse Nodes in k-Group
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 分开成小块,每一块执行反转,画图解释for循环里面的
# 两个指针pre,cur一直往后移动
# 1->2->3->4->5 k = 3举这个例子,先变成2->1->3->4->5,再变成3->2->1->4->5
def reverseKGroup(self, head, k):
h = ListN... |
# 92. Reverse Linked List II
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# Input: 1->2->3->4->5->NULL, m = 2, n = 4
# Output: 1->4->3->2->5->NULL
# pre,cur一直往后移动
# t1 t2 pre cur lat
# 1 <- 2 <- 3 <- 4 5 -> null
# t1.... |
# 82. Remove Duplicates from Sorted List II
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 两个指针来存储位置, 两个指针,一个一直找到next不重复的然后另一个直接next到这个下面。
def deleteDuplicates(self, head):
dummy = ListNode(0)
dummy.next = head
pre = dummy... |
# 503. Next Greater Element II
# 输入: [1,2,1]
# 输出: [2,-1,2]
class Solution:
def nextGreaterElements(self, nums):
# 对于循环数组的问题一个常见的处理手段就是通过余数,
# 然后将数组的长度扩大两倍即可
stack, nums_len = list(), len(nums)
res = [-1] * nums_len
for i in range(nums_len * 2):
while stack and ... |
# 9. Palindrome Number
class Solution:
# int 转 string解决
# def isPalindrome1(self, x):
# strx = str(x)
# return strx == strx[::-1]
# 将数字倒过来比较
def isPalindrome(self, x):
temp = x
ans = 0
while temp > 0:
ans = ans * 10 + temp % 10
temp //=... |
# 344. Reverse String
class Solution:
def reverseString(self, s):
l = 0
r = len(s) - 1
s = list(s)
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return ''.join(s)
s = Solution()
print(s.reverseString(["h","e","l","l","o"])) |
# 300. Longest Increasing Subsequence
class Solution:
# [1, 1, 1, 1, 1]然后每次迭代增加
# [1, 2, 2, 1, 2]
# [1, 2, 3, 1, 3]
# [1, 2, 3, 1, 4]
# [1, 2, 3, 1, 4] max(2, 4)
def lengthOfLIS(self, nums):
if not nums:
return 0
result = [1]*len(nums)
for i in range(len(nu... |
# 234. Palindrome Linked List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 快慢指针找到中点,栈弹出判断
def isPalindrome(self, head):
if head == None or head.next == None:
return True
fast, slow = head, head
reverse_node = ... |
# 46. Permutations
class Solution:
# 递归遍历谁把谁拿出来然后剩下的继续递归
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
def permute(self, nums):
if len(nums) <= 1:
return [nums]
ans = []
for i, num in enumerate(nums):
extra = nums[:i] + nums[i+1:]
... |
# 128. Longest Consecutive Sequence
class Solution:
# 先找到最小的数,然后递增到不存在
def longestConsecutive(self, nums):
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
b... |
# 69. Sqrt(x)
class Solution:
def mySqrt(self, x):
if x < 0:
return -1
elif x == 0:
return 0
l, r = 1, x
while l+1 < r:
mid = (l+r)//2
if mid**2 == x:
return mid
elif mid**2 > x:
r = mid
... |
# las funciones en python con ciudadanas de primera clase
# first class citizens
# definimos la funcion
def sumar(a, b):
return a + b
# asignar funcion a variable
mi_funcion = sumar
# verificar el tipo de la variable
print(type(mi_funcion))
resultado = mi_funcion(3, 5)
print(resultado)
# funcion como argument... |
variable = ''
if bool(variable):
print('Verdadera')
else:
print('falsa')
'''
Ocho formas de generar un bool False en python
1. Comilla simple o doble ''/""
2. Lista vacia []
3. Tupla vacia ()
4. Diccionario vacio {}
5. Entero con 0
6. Flotante 0.0
7. bool False
8. Objeto None
''' |
class MiClase:
# variable estatica
variable_clase = 'Valor variable clase'
def __init__(self, variable_instancia):
self.variable_instancia = variable_instancia
# metodos estaticos
@staticmethod
def metodo_estatico():
print(MiClase.variable_clase)
# emtodos de clase cls es... |
# operador de suma esta sobrecargado
a = 2
b = 3
print(a + b)
a = 'hola '
b = 'mundo '
print(a + b)
a = [1, 2, 3]
b = [6, 7, 8]
print(a + b)
# sobreescribir el metodo heredado de la clase object
|
# listas
nombres = ['Juan', 'Karla', 'Ricardo', 'Maria']
# imprimir la lista
print(nombres)
print(nombres[0])
print(nombres[1])
# acceder a elementos de manera inversa
print(nombres[-1])
print(nombres[-2])
# rangos de 0 a 2 sin incluir 2
print(nombres[0:2])
# ir del inicio de la lista al indice sin incluirlo
# desde el... |
import itertools, time
def imright(h1, h2):
# House h1 is immediately right of h2 if h1-h2 == 1."
return h1-h2 == 1
def nextto(h1, h2):
# Two houses are next to each other if they differ by 1."
return abs(h1-h2) == 1
def zebra_puzzle_fast():
# Return a tuple (WATER, ZEBRA) indicating their house num... |
print("Hallo! Mit diesem Konverter kannst du Kilometer in Meilen umwandeln.")
while True:
print("Bitte gib eine Zahl in Kilometer an, welche du umgewandelt haben willst. Bitte nur Zahlen eingeben!")
km = input("Kilometer: ")
km = float(km.replace(",", "."))
miles = km * 0.621371
print(f"{km} Ki... |
dic01 = {'name':'John', 'phone':'0933980284', 'height':'170cm', 'age':'15', 'course': ['Math', 'History']}
dic01['gender'] = 'Female'
print(dic01.get('ddd', 'Not Found'))
age = dic01.pop('age')
print(age)
print (dic01.items())
for key, value in dic01.items():
print (key, value) |
'''
# self 像是 this一樣傳入物件本身,
# 類似於 Person.getAge(person) 這樣
class Person:
def getName(self):
print ("Avi")
def getAge(self):
print ("16")
person = Person()
person.getName()
person.getAge()
'''
'''
# Initialization function : Takes parameters you want to pass in when creating the object.
class Person:
de... |
'''
The net class defines the overall topology of a neural networks, be it
directed or undirected. This is a very flexible setup which should give
the user a high degree of manipulative ability over the various aspects
of neural net training.
'''
import numpy as np
import cPickle
import gzip
import theano
import thea... |
import wikipedia
import wikipediaapi
import requests
# Setting up requests, sessions, and urls for Media Wiki API
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
# Setting up wikipedia API library
wiki_wiki = wikipediaapi.Wikipedia('en')
# Getting the list of queries to search wikipedia
queries = ... |
import json
WIDTH = 9
FULLSUDOKU = {1, 2, 3, 4, 5, 6, 7, 8, 9}
FILE = 'sudoku1.json'
FILL = "x"
matrix = [[FILL]*WIDTH for i in range(9)]
borders = [2,5,8]
counter = 0
class Sudoku:
def __init__(self):
self.matrix = [[FILL]*WIDTH for i in range(WIDTH)]
with open(FILE) as data_file:
js... |
import random
class GenericTyle:
def __init__(self, type, value):
self.type = type
self.value = value
self.clicked = False
def getType(self):
return self.type
def setType(self, type):
self.type = type
return True
def getValue(self):
return self.... |
import math
from display import *
def magnitude(vector):
magnitude = math.sqrt(math.pow(vector[0], 2) + math.pow(vector[1], 2) + math.pow(vector[2], 2))
#vector functions
#normalize vetor, should modify the parameter
def normalize(vector):
for i in vector:
vector[i] = vector[i] / magnitude
#Return th... |
from typing import List
from src.morse_alphabet import morse_code, PAUSE
def translate_marks(input_text: str):
"""method translates the input string into the morse alphabet
Args:
input (str): string, that will be translated to morse alphabet
Returns:
[list]: list of morse code sequence
... |
# Step 1 - Scraping
# Complete your initial scraping using Jupyter Notebook, BeautifulSoup, Pandas, and Requests/Splinter.
# Create a Jupyter Notebook file called mission_to_mars.ipynb and use this to complete all of your scraping and analysis tasks. The following outlines what you need to scrape.
# NASA Mars News
... |
class Animal:
animal_type = 'mamma'
counter = 0
def __init__(self, name):
self.name = name
Animal.counter += 1
animal_one = Animal('rat')
animal_two = Animal('cat')
print(animal_one.animal_type)
print(animal_two.animal_type)
print(animal_one.counter)
# to check how many times an object ... |
# register
# - first name, last name, password and email
# - generate userAccount
# login
# - account number and password
# bank operations
# Initializing the system
import random
import database
import validation
from getpass import getpass
# dictionary
def init():
print('Welcome to Zuri Bank')
have_acco... |
"""
Problem Statement
James found a love letter his friend Harry has written for his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.
To do this, he follows two rules:
He can reduce the value of a letter, e.g. he can change d to c, but h... |
"""
Problem Statement
You are given two strings, A and B. Find if there is a substring that appears in both A and B.
Input Format
Several test cases will be given to you in a single file. The first line of the input will contain a single integer T, the number of test cases
Then there will be T descriptions of the test ... |
'''
=====================
`logger` module
=====================
A simplified interface to the standard library's logging module.
Summary
-------
Two handlers are attached to the root logger, one logs to a file and the other
logs to the console. Log levels of the two handlers can be set independently
by calling `set... |
#!/usr/bin/python
print "Summing 1 to 1000";
#Learning: Newline is printed at the end of each print statement
sum = 0;
for i in range (1, 1000, 1):
#Learning: Range excludes the last number, here it excludes 1000
print i
sum = sum + i
# New Block
print "Sum is ", sum
|
Can you find the needle in the haystack?
Write a function findNeedle() that takes an array full of junk but containing one "needle"
After your function finds the needle it should return a message (as a string) that says:
"found the needle at position " plus the index it found the needle
So
should return
def find... |
def check_palindromo(frase):
"""
Función que recibe una frase, es decir un conjunto de palabras separadas
por espacio y devuelve True si es un palíndromo y False en caso contrario.
Recibe por parámetro la frase que debe ser de tipo string, de lo contrario
devuelve TypeError.
La función devuelv... |
def contar_vocales(palabra):
"""
Función que recibe una palabra y decide si tiene mas letras "e" o mas
letras "a".
Recibe como parámetro un solo dato de tipo string, en caso contrario
devuelve TypeError.
La función devuelve una letra, que hace referencia a la mayor cantidad de
vocales que ... |
#!/usr/bin/env python
# coding: utf-8
# # House Price Predictor
# ## Data ananysis using jupytor
# Here we are taking data from uci repository for housing price
#
#
# link : http://archive.ics.uci.edu/ml/machine-learning-databases/housing/
#
# housing.data
#
#
# housing.names
#
# copy these files in the working... |
#! python3
# EnglishTools.py - some helpful english tools
def Usage():
print("""
Usage:
#1
Thesaurus(word: "the word you want to search")
==> open thesaurus.com to find the thesaurus for the word
#2
Dictionary(word: "the word you want to search")
==> open dictionary.com to find the defin... |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
nums = set(nums)
return sorted(nums, reverse=True)[2] if len(nums) > 2 else max(nums)
|
from math import sqrt
class Vec():
@staticmethod
def distance(v1, v2):
delta = v1 - v2
return sqrt(delta.x ** 2.0 + delta.y ** 2.0)
@staticmethod
def zero():
return Vec(0.0, 0.0)
def __init__(self, x, y):
self.x = x
self.y = y
def magnitude(s... |
from Room import Room
from Guest import Guest
from Booking import Booking
from inputHandler import handleInput
from utilityFunctions import *
guestObjList = [];
roomObjList = [];
bookingObjList = [];
def addGuest():
while(True):
guestName = handleInput("Please enter guest name:", "string", [1,1], None)
... |
import copy
file_input = 'input.txt'
with open(file_input, encoding='utf-8') as file:
contents = file.read()
inputs = contents.split('\n')
for i in range(len(inputs)):
inputs[i] = inputs[i].replace(' ', '')
def calculate_end_parenthesis(expression):
level = 0
for i in range(len(expression)):
... |
# Disciplina: Bioinformática
# Professor: Luiz Cláudio Demes
# Aluno: Hilderlan
######### Programa que faz a transcrição de DNA para RNAm ##########
arq = open('input.txt', 'r')
dna = arq.read()
arq.close()
rna = ''
print('Molécula de DNA a ser transcrita: {}'.format(dna))
for i in dna:
if (i == 'A'):
... |
# -*-coding=utf-8-*-
__author__ = 'Rocky'
import sqlite3
def create_table():
conn = sqlite3.connect('shenzhen_house.db')
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS HOUSE
('日期' TEXT,
'一手房套数' TEXT,
'一手房面积' TEXT,
'二手房套数' TEXT,
'二手房面积' TEXT);
'... |
print("Enter the number")
num=input()
i=int(int(num)/int(num))
while i<int(num)+int(i/i):
if i%((i/i)+(i/i)+(i/i))==i-i:
if i%((i/i)+(i/i)+(i/i)+(i/i)+(i/i))==i-i:print("Fizz\nBuzz")
else:print("Fizz")
else:
if i%((i/i)+(i/i)+(i/i)+(i/i)+(i/i))==i-i:print("Buzz")
else:pr... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 10:29:24 2018
@author: yatheen!
"""
"""Step 1: Import the neccessary Packages """
import cv2 #OpenCv to handle and process the images
import numpy as np #Images are stores as numpy arrays
import matplotlib.pyplot as plt # to plot the image we have to use matplotlib
#... |
import turtle
turtle.bgcolor("black")
turtle.width(2)
turtle.color("red","yellow")
def trifun(size):
for i in range(3):
turtle.fd(size)
turtle.left(120)
size = size-5
for i in range(5):
trifun(150)
trifun(135)
trifun(120)
turtle.done() |
'''
@author: Mateus Araujo
'''
nomes_proprios = ["carlos", "antonio", "paulo", "pedro", "maria", "chico", "chica"]
s1 = "Antonio comprou dois livros sobre a vida de chico"
s2 = "paulo joga muito bem, mas pedro joga melhor"
s3 = "antonio não sabe brincar, é um brutamonte..."
def capitalize_names(s, lista):
alt... |
r1=int(input())
r2=1
for j in range(1,r1+1):
r2=r2*j
print(r2)
|
#Return the items from the beginning to "green": ["black", "yellow", "pink", "green", "purple", "white", "grey"]
thislist =["black", "yellow", "pink", "green", "purple", "white", "grey"]
print(thislist[:4])
|
import tkinter as TK
from tkinter import ttk
import crud as crud
class interface:
def __init__(self, janela):
print("--------------------- CONSTRUCTOR ---------------------")
self.objeto_bd = crud.AppBD()
#----------- COMPONENTES ----------- #
self.label_codigo = TK.Label(janela, ... |
from inheritance_intro import Decimal
class Leg:
def __init__(self):
self.length = 0
def set_leg_length(self, length):
self.length = length
def __repr__(self):
return "A leg {} inches long".format(Decimal(self.length, 2))
class Back:
pass
class Chair:
def __init__(sel... |
def rev_string(input):
str = ""
for i in input:
str = i + str
return str
s=input("Please type someting here to reverse : ")
rmv_space=s.replace(" ", "")
lower_string=rmv_space.lower()
rev_string_display=rev_string(lower_string)
print(rev_string_display)
import sys
sys.exit(0)
|
x = 5
y = 2
z = (f"P({x},{y})")
if x>0 and y>0:
print(f'Punkt {z} znajduje się w pierwszej ćwiartce układu współrzędnych')
elif x<0 and y>0:
print(f'Punkt {z} znajduje się w drugiej ćwiartce układu współrzędnych')
elif x<0 and y<0:
print(f'Punkt {z} znajduje się w trzeciej ćwiartce układu współrzędnych')
el... |
print('Książka e-book')
print(15 * '=')
class Ksiazka_elektroniczna():
def __init__(self, tytul, autor, liczba_stron):
self.stan_k = False
self.tytul = tytul
self.autor = autor
self.liczba_stron = liczba_stron
self.nr_bieżącej_strony = 1
def otwarta(self):
se... |
x = int(input("Wprowadź liczbę: "))
y = int(input("Wprowadź liczbę: "))
if x < 0 or y < 0:
print("Jedna lub dwie z wprowadonych liczb są ujemne")
else:
print("Żadna z wprowadonych liczb nie jest ujemna") |
a = input('Podaj liczbe a: ')
b = input('Podaj liczbe b: ')
c = input('Podaj liczbe c: ')
import math
a = int(a)
b = int(b)
c = int(c)
d = b**2 - 4*a*c
D = math.sqrt(d)
x1 = (-b+D)/2*a
x2 = (-b-D)/2*a
print(a, 'x^2', '+', b, 'x', '+', c, '=', '0', end='')
print(f'D = {D}')
print(f'X1 = {x1}')
print(f'X2 = {x2}')
|
def binary_search(alist, item):
#二分查找,递归版本
n = len(alist)
if n > 0:
mid = n // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
return binary_search(alist[:mid], item)
else:
return binary_search(alist[mid+1:], item)
return F... |
class Deque(object):
#双端队列
def __init__(self):
self.__list = []#创建一个私有容器
# 如果出队的频率比入队的频率大得多,那就从列表的尾部弹出,头部进入队列
# 反之的话,就从头部弹出,尾部进入,与具体的应用相关
def add_front(self, item):
# 头部进队列
# self.__list.append(item)
self.__list.insert(0, item)
def add_rear(self, item):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class calc:
def suma(self, x, y):
'''argumentos de entrada: dos listas, cada una con un polinomio
retorna: la suma de los dos polinomios
'''
may = x
men = y
sum = [0]*len(may)
if len(x) < len(y):
men ... |
'''
@amoghari
Determin average salary of a driver in a given year, month and over all.
'''
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import month,year
conf = SparkConf().setAppName('Sample Program')
sc = SparkContext(conf=conf)
sqlContext = SQLContext(... |
# number = input("Pick a number?")
# for x in range(1,number + 1):
# print number
# number = number - 1
# print "boom!"
x = input("pick a number?")
while x > 0:
print x
x = x - 1
print "boom!"
|
test = int(input())
while test:
val = 0
test -= 1
TS = int(input())
while TS % 2 == 0:
# '//' is a floor division and is used to give the quotient as integer since sometimes......
# it cannot handle large float numbers
TS = TS//2
val = TS//2
print(val) |
x = eval(input('Enter the first no:'))
y = eval(input('Enter the second no:'))
z = x - y
print('The diff is',z)
|
import numpy
import math
from math import *
import os
import sys
os.chdir("C:\\Users\\justi_jtw\\OneDrive\\Documents\\GitHub\\Coding\\Python\\Python Tutorials\\FreeCodeCamp Tutorial\\python")
send = print
say = print
# input("Enter anything to continue ")
# class hello_world:
# print(f"Hello World")
# clas... |
import random
import csv
from cryptography.fernet import Fernet
##PY3
#name = input("Name: ")
#password = input("password: ")
#def Create():
# email = input("e-mail: ")
# password = input("password: ")
# return(email, passowrd)
class Account():
def __init__(self, login, email = None, password = None): ... |
from itertools import (
accumulate,
chain,
repeat,
tee,
)
from typing import List
class ListUtils(object):
"""
List Utils
"""
@classmethod
def flatten(cls, value: List) -> List:
"""
Flatten a list recursively
"""
if value is None:
return... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
"""
# M = L[i(1+i)n] / [(1+i)n-1]
# M = monthly payment
# L = Loan amount
# i = interest rate (for an interest rate of 5%, i = 0.05)
# n = number of payments
M =L =I = N = loanduration = 0
L = input('How much loan you want?\n')
I = input('Interest rate on the loan?\n')
l... |
"""
Shutterflly challenge to Calculate Life time value of given customers to predict his future purchase power index
In this part of code we are generating Fake date to build our model to Calculate Life Time Value of Customer
Author: Rajesh Jaiswal
Dated: 10th June 2017
"""
import random
import string
from datetime imp... |
nome="raul"
anos=8
print(nome+str(anos))
nome="raul"
anos=8
print(nome+" "+str(anos)+"!")
nome1="raul varela"
print(nome1)
print(nome1.upper())
print(nome1.lower())
print(nome1.title())
print("raul\n varela")
print("raul\tvarela")
print("\\novo")
|
# Napisz program do sprawdzania czy liczba jest podzielna przez 3 lub 5 lub 7
num = float(input("Podaj liczbę: "))
if num % 3 == 0 or num % 5 == 0 or num % 7 == 0:
print("Ta liczba jest podzielna przez 3, 5 lub 7")
else:
print("Ta liczba nie jest podzielna ani przez 3, ani przez 5, ani przez 7") |
import Excercises.Moduly.games as games
from random import randint
def rand():
wybor = randint(1, 15)
wybor = str(wybor)
print(f"Wylosowano numer {wybor}")
programy[wybor]['call']()
def leave():
print("Do zobaczenia!")
exit()
def menu(programy):
print('MultiTOOL\nMenu:')
for key, pr... |
# Program przyjmuje kwotę w parametrze i wylicza jak rozmienić to na monety: 5, 2, 1, 0.5, 0.2, 0.1 wydając ich jak najmniej.
def coins_change():
money = (float(input("Podaj kwotę, którą chcesz rozmienić: "))) * 100
div_list = (500, 200, 100, 50, 20, 10, 5, 2, 1)
while money >= 1:
for i in div_list... |
import csv
class Item():
"""
"""
def __init__(self, id, name, price, amount, created_at, last_buy_at, pic):
self.id = id
self.name = name
self.price = price
self.amount = amount
self.created_at = created_at
self.last_buy_at = last_buy_at
self.pic = pi... |
def is_num(num):
try:
num = float(num)
return True
except:
return False
print(is_num(5.6)) |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if not head:
return None
slow = head
fast = head
... |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
... |
import random
door =9
livesLeft=3
x=300
def intro ():
print("Welcome to the game Andrew, Gloria or housecats.")
print("U, the great Elizabeth Li is infront of 9 great doors.")
print("Behind one of the doors is Gloria Zhu.")
print("After marrying Gloria each time, you will lose a life.")
... |
import cryptography
from cryptography.fernet import Fernet
k = Fernet.generate_key()
f = open('key.txt' , 'wb' )
f.write(k)
f.close()
def enc():
datafile = open('data.txt', 'rb')
data = datafile.read()
u = Fernet(k)
x = u.encrypt(data)
cipher = open('encdata.txt' , 'wb')
ci... |
# python3
# Description: edX UCSanDiegoX: ALGS201x PA#1
# Problem 2: Tree Height
# given: #of nodes and parents index
# compute tree height, using recursion
#
# For submission 10,
# computeHeight - starting from root and looking at kids at each level
# (instead of going through leaves)
#
# main datastruc... |
#Autor: Juan Sebastián Lozano Derbez
#Se calcula el cosato total de la compra de unos asientos
def calcboletosa(cantidada, cantidadb, cantidadc): #Se calcula el total de todos los asientos
total = 925*(cantidada) + 775*(cantidadb) + 360*(cantidadc)
return total
#Se reciben las entradas y se imprime ... |
import os # This module use for create and delete the file in location
import pickle # This module use for getting the user data dump to another file and again getting the same data and secure purpose
import pathlib #This module use for create file path and take the file path
class Bank_system():
def Cr... |
# a piece of text with leading spaces
def useless_function():
a = 123
ab =927
abc = 215
if abc <= 500:
abcd = ab + abc
abcd += a
if abcd == abc:
abcd = 0
|
array=[11,5,8,9,7]
def selectionsort(array):
n = len(array)
for i in range(n):
for j in range(0,n-i-1):
if array[j]>array[j+1]:
array[j], array[j+1]=array[j+1],array[j]
print(array)
return array
print(selectionsort(array))
|
import numpy as np
class NN:
"""
Arguments:
data: data
labels: labels
layers: List (of lists) of net layer sizes and activation functions, e.g.
[[8,"relu"],
[5,"relu"],
[3,"relu"],
[2, "sigmoid"]]
Currently supported functions: "relu", "tanh", "... |
import math
def to_minute(time):
time = time.replace(" ", "")
hour = int(time[:-2].split(":")[0])
minute = int(time[:-2].split(":")[1])
if time[-2:] == 'am':
hour = hour + 12
print("time in hours: {} hour: {} minute: {}".format(time, hour, minute))
return hour*60+minute
def to_hour(t... |
import statistics as stats
#ejercicios medidas de dispersion
'''
1.1 What is the range for the data set?
1.2 How does the standard deviation change when 6 is replaced with 12? Does it increase, or decrease, or it remains the same?
1.3 Is is possible to have a dataset with 0 standard deviation or variance?
If y... |
# Fizz Buzz & Make String Lowercase
zahl = int(input("Geben Sie bitte eine Zahl zw. 1 und 100 ein: "))
while zahl > 0:
if zahl % zahl == 0 and zahl % 3 == 0 and zahl % 5 == 0:
print("FizzBuzz")
elif zahl % 5 == 0:
print("Buzz")
elif zahl % 3 == 0:
print("Fizz")
else:
p... |
#!/usr/bin/python3
row_column = input("please input row and column: ")
dimension = [int(i) for i in row_column.split(',')]
dimension_row = dimension[0]
dimension_column = dimension[1]
Matrix = [[0 for x in range(dimension_column)] for y in range(dimension_row)]
for row in range(dimension_row):
for column in range... |
#!/usr/bin/python3
"""input a number to calculate"""
n = input("please input a number to compute: ")
n = int(n)
d = dict()
for i in range(1, n+1):
d[i] = i*i
print(d)
|
#!/usr/bin/python3
str_input = str(input("please input letters and digits: "))
letters = 0
digits = 0
for i in str_input:
if i.isdigit():
digits += 1
elif i.isalpha():
letters += 1
else:
pass
print("LETTERS", letters)
print("DIGITS", digits)
|
#!/usr/bin/python3
values = input("please input a list of number: ")
numbers = [x for x in values.split(",") if int(x) % 2 != 0]
print(",".join(numbers))
|
#!/usr/bin/python3
number = int(input("please input a number: "))
new_list = input("please input a list of number: ")
new_list = new_list.split(",")
def get_number_list(): # get number list_number
list_number = []
for i in new_list:
numbers = int(i)
list_number.append(num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.