text stringlengths 37 1.41M |
|---|
try:
import numpy as np
def rotate(times,dir="right"):
np_dir= np.empty(9)
np_matrix= np.arange(1,10)
np_changer= np.arange(1,10)
#EX: right(-2) == left(+2)
if times < 0:
times= abs(times)
if dir == "right": dir = "left"
elif dir == "left": dir ... |
#Functions only for list manupulation
#Copies data from list to other list and deletes original
def cutlist(froms, to):
try:
for x in range(len(froms)):
to.append(froms[x])
for x in range(len(to)):
froms.remove(froms[0])
return to;
except IndexError:
... |
word = str(input("Enter word: "))
letter = str(input('Enter letter to search from word: '))
count = 0
for ltr in word:
if ltr == letter:
count+=1
print(f"Letter '{letter}' was repeated {count} times in the word")
|
"""
Objective
Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then ... |
# Return none if arguments or flags are not valid
# george
import random
def SpONgeBoBtEXt(args):
#initialize spongetext variable
spongetext = ""
for char in args[0]:
#check if the character is in the alphabet
if char.isalpha():
random_num = random.random()
#change the character to a capital letter... |
import torch
from myModel import Net
from utils.utils import *
import matplotlib.pyplot
class TrainModel:
def __init__(self):
self.lossFunction = torch.nn.MSELoss()
self.neuralNetwork = Net(INPUT_LAYER_SIZE, HIDDEN_LAYER_SIZE, OUTPUT_LAYER_SIZE).double()
self.optimizerBatch = torch.optim.S... |
stack = []
# Add in entries
stack.append('a')
stack.append('b')
stack.append('c')
# The last entry added was 'c' so the first entry that comes out will be 'c'
out = stack.pop()
print(out) # 'c' |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# 986. Interval List Intersections
class Solution(object):
def intervalIntersection(self, firstList, secondList):
"""
:type firstList: List[List[int]]
:type secondList: List[List[int]]
:rtype: List[List[int]]
"""
# AN... |
#!/usr/bin/env python
# coding: utf-8
# In[6]:
# 57. Insert Interval
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
# SECOND TRY 03132021
new_st... |
# 基于个人理解的深度优先算法 20210520 TianzeGao
def search_depth_first(g, s):
s -= 1
marked_nodes = [s]
node_list = [s]
current_node=s
while len(node_list) != 0:
for arc in range(0, len(g[0])):
if g[current_node][arc] == 1:
g[current_node][arc] = 0
for node in ... |
#Import required modules and classes
import time
from datetime import datetime, timedelta
import csv
from flight_search import FlightSearch
from notification_manager import NotificationManager
#Create search and notification objects
notification_manager = NotificationManager()
flight_search = FlightSearch()... |
x = 1
if x == 1:
# indented four spaces
print("x is 1.")
print("Hello World")
print(x)
myfloat = 1.2
print(myfloat)
myfloat = float(1.2)
print(myfloat)
mystring = 'hi'
print(mystring)
one = 1
two = 2
three = one + two
print(three)
hello = "hello"
world = "world"
helloWorld = hell... |
class User:
"""
Class that generates new instances of users
"""
user_list = [] # Empty user list
def __init__(self,first_name,last_name,number,email):
def test_save_user(self):
"""def test_save_user(self):
"""
test_save_user test case to test if the user object is... |
import re
class Set:
def __init__(self, parent, rank):
self.parent = parent
self.rank = rank # Размер дерева
def find_set(set, a):
if a == set[a].parent:
return a
set[a].parent = find_set(set, set[a].parent)
return set[a].parent
def union_set(set, a, b):
a =... |
#3-8
travel = ['shanghai','xian','beijing','xizang','xinjiang']
print(travel)
print(sorted(travel))
print(travel)
print(sorted(travel,reverse=True))
print(travel)
travel.reverse()
print(travel)
travel.reverse()
print(travel)
travel.sort()
print(travel)
travel.sort(reverse=True)
print(travel)
#3-9
invite = ['teddy','j... |
import random
N_GAME=3
def main():
"""
Rock Paper Scissor Game
Game:
Each player chooses a move simultaneously from the choices:
Rock Paper Scissors
if they choose the same move its a tie
rock beats scissor
scissor beats paper
paper beats rock
In this game... |
def czyAnagram():
s1 = input("wpisz słowo, sprawdzę czy jest anagramem ")
s2 = input("wpisz drugie słowo ")
alist1 = list(s1)
alist2 = list(s2)
alist1.sort()
alist2.sort()
#print (alist1)
pos = 0
matches = True
while pos < len(s1) and matches:
if alist1[pos]==alist2[po... |
##
## Author: Kristina Striegnitz
##
## Version: Fall 2011
##
## This file defines a ball class that can move in two dimensions and
## can bounce off other balls. It also bounces off the edges of the
## screen.
import pygame
import math
from vector import Vector
class MovingBall :
r = 25
... |
locations = ['Alaska', 'Ireland', 'New Zealand', 'Antartica', 'The Moon']
print(locations)
print(sorted(locations))
print(locations)
print(sorted(locations, reverse=True))
print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
locations.sort(... |
pets = []
August = {'kind': 'dog', 'owner_name': 'Douglas'}
sammy = {'kind': 'cat', 'owner_name': 'David'}
JJ = {'kind': 'cat', 'owner_name': 'Oliver'}
pets.append(August)
pets.append(sammy)
pets.append(JJ)
for pet in pets:
print("\nkind: " + pet['kind'])
print("belongs to: " + pet['owner_name'])
|
current_users = ['gusgus', 'frogger', 'Dtucker', 'miranda', 'admin']
current_users_lower = []
for user in current_users:
current_users_lower.append(user.lower())
new_users = ['Gusgus', 'frogger', 'firefly', 'parsival', 'gregory']
for user in new_users:
if user.lower() in current_users_lower:
print("U... |
usernames = ['gusgus', 'frogger', 'Dtucker', 'miranda', 'firefly', 'admin']
if usernames:
for user in usernames:
if user == "admin":
print("hello admin, would you like to see a status report?")
else:
print("greetings " + user + "! thank you for logging in.")
else:
print... |
cities = {
"Manteca": {'country': 'USA', 'population': 120000, 'fact': 'home town'},
"Fresno": {'country': 'USA', 'population': 1200000, 'fact': 'College'},
"Boise": {'country': 'USA', 'population': 180000, 'fact': 'New home'},
}
for city, info in cities.items():
print(city)
print("\t" + info['coun... |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for numb in numbers:
if numb == 1:
print(str(numb) + "st")
elif numb == 2:
print(str(numb) + "nd")
elif numb == 3:
print(str(numb) + "rd")
else:
print(str(numb) + "th")
|
import numpy
n,m = map(int, input().split(" "));
matrix = []
for i in range(n):
matrix.append(list(map(int, input().split(" "))))
matrix = numpy.array(matrix);
print(numpy.transpose(matrix))
print(matrix.flatten())
|
'''
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 ... |
'''
some fucking boy was playing with the natural numbers and trying to rearrange them
so he has come up with a silly idea to to put the odd numbers first and then the even numbers
like this 1 2 3 4 5 5 6 7 8
after rearranging
1 3 5 7 2 4 6 8
'''
def nonOptimaGetPos(n, k):
h = {}
# check upon the number ran... |
def formTeams(students):
teams = { 1: [], 2: [], 3: [] }
# encode the students into the dict
for i in range(len(students)):
if students[i] == 1:
teams[1].append(i+1)
elif students[i] == 2:
teams[2].append(i+1)
elif students[i] == 3:
teams[3].appe... |
'''
here you are going to iterate over the n and check if the guess is valid or not
'''
def getSqrt(n):
guess = 1
while guess ** 2 != n:
guess += 1
return guess
if __name__ == '__main__':
num = int(input())
print(getSqrt(num))
'''
the runtime for this algorithm is O(sqrt(n)) because th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 21 16:28:27 2018
@author: xingyichong
"""
import math
HANDLE_MISSING = '' # define the way to handle the node without right child.
class Tree:
def __init__(self, value = None, left = None, right = None):
self.value = value
se... |
"""
9. 점수 구간에 해당하는 학점이 아래와 같이 정의되어 있다.
점수를 입력했을 때 해당 학점이 출력되도록 하시오.
81~100 : A
61~80 : B
41~60 : C
21~40 : D
0~20 : F
"""
num = int(input('점수를 입력해주세요 : '))
if 80 < num < 101 :
print('A')
elif 60 < num < 81 :
print('B')
elif 40 < num < 61 :
print('C')
elif 20 < num < 41 :
print('D')
elif 0 <= num < 10... |
"""4. 삼각형의 가로와 높이를 받아서 넓이를 출력하는 함수를 작성하시오."""
width = float(input('삼각형의 가로를 입력하세요 : '))
height = float(input('삼각형의 높이를 입력하세요 : '))
print('삼각형의 넓이 : {}'.format(round(width*height/2, 3))) |
num =int(input("enter a number:"))
result = num**0.5
print("the square root of %0.3f is %f"%(num,result)) |
import os
import csv
#Creating a path for the budget data
bankbudget = os.path.join("budget_data.csv")
# Open csv file
with open(bankbudget, 'r') as csvfile:
#Split the csv file
readCSV = csv.reader(csvfile, delimiter=',')
#Read header first
csv_header= next(readCSV)
#Get the number of months
row... |
import heapq
import argparse
import sys
import os.path
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('Path')
args = parser.parse_args()
string = str(args)
#a,'\'',c,'\'',d = string
a,b,c = string.split('\'')
print "Your file is : "+b
if not os.path.exists(b): raise ... |
import sys
import os
import re
def doStuff(orig,list2):
checker = []
def replaceOkay(orig,el0,el1):
def allGood(checker,pos,l1):
for i in range(0,l1):
if pos+i in checker: return False
for i in range(0,l1):
checker.append(pos+i)
return True
#First find the occurences of su... |
import exifread
from File import File
""" Purpose: This class defines a picture file, as distinguished by the "*.jpg"
file extension. This class inherits from the File class.
"""
class PictureFile(File):
# Constructor
def __init__(self, filename, source_directory, destination_directory):
... |
#use of zip function
a=[1,2,3] #list
b=(7,8,9) #tuple
for i,j in zip(a,b): #zip is used to aggregate values in a n b
print(i+j)
#
import string
file=open('new.txt','w')
for l,k in zip(string.ascii_lowercase[0::2],string.ascii_lowercase[1::2]):
file.write(l + k + "\n" )
file.close()
#abc3.tx... |
#find the error and solve
def foo(a=1, b=2):
return a + b
x = foo() - 1 #a function should always have paranthesis
print(x)
#alternative
def foo():
global c
c = 1
return c
foo()
print(c)
#create a function that takes any string as input
# and return the number of words in the string... |
def student_discount(price):
price = price - (price * 10) / 100
return price
def additional_discount(newprice):
newprice = newprice - (newprice * 5) / 100
return newprice
selling_price = 600
# applying both discounts simultaneously
print(additional_discount(student_discount(selling_p... |
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
#print out the second item of the list
print(letters[1])
#expected output [d,e,f] using slicing
print(letters[3:6])
#expected output [a,b,c] using slicing
print(letters[:3])
#expected output[i]
print(letters[8:9])
#expected output [i] using negative ... |
def arithmetic_arranger(problems, isResult = False):
row1 = ""
row2 = ""
separator = ""
result = ""
def addColumn(row):
column = " " # four space character
if row != "":
row += column
return row
def addOperandus(row, len1, len2, rightAlign, operandus):
if len1 > len2:
row +=... |
import deck
from player_class import Player
d = deck.create_deck()
#d= [('Spades', 10), ('Diamonds', 'King'), ('Hearts', 'Ace'), ('Spades', 'Ace'), ('Diamonds', 7), ('Diamonds', 4)]
deck.shuffle_deck(d)
print(d)
def check_total(a,b):
if a > 21 and b is True:
print("You Lost")
exit()
... |
# Petit programme pour calculer si M1 ou M2 a le plus d'influence sur la plage.
"""Entrée"""
M1 = float(input())
M2 = float(input())
N = float(input())
"""AIRE ENTRE M1 ET M2 = (M2-M1)"""
"""Aire de M1"""
AM1 = M1+((M2-M1)/2)
"""Aire de M2"""
AM2 = N - M2 +((M2-M1)/2)
winner = 5
if AM2 < AM1:
winner = 1
elif ... |
def binary_search (arr, n):
mid = arr[len(arr)//2]
print (mid)
arr = [1,2,3,4,5,6]
binary_search (arr,6)
# 1st: what if the search number isn't in the array?
# 2nd: what if the number is found?
# 3rd: conditional for the lower and upper half based on our find input
|
import unittest
import pytest
from myparser import *
class ParserTest(unittest.TestCase):
def test_init(self):
text = "1+1"
i = Parser(text)
assert(i._current_token.value == 1)
assert(i._current_token.type == INTEGER)
def test_eat_happy(s... |
import numpy as np
a = np.zeros((3, 3))
n = 0
for i in range(3):
for j in range(3):
a[i, j] = n
n += 1
print(a)
print(np.sum(a, axis=0)) |
#!/usr/bin/python3
def multiply_by_2(my_dict):
new_dict = {}
for n in my_dict:
new_dict[n] = my_dict[n] * 2
return new_dict
|
#!/usr/bin/python3
"""
Input/ output module
"""
def number_of_lines(filename=""):
"""
Number of lines in a file function
"""
with open(filename, encoding="utf-8") as my_file:
l = 0
for line in my_file:
l += 1
return l
|
#!/usr/bin/python3
"""
Input output module
"""
def read_file(filename=""):
"""
Read a file with a with statement
"""
with open(filename, encoding="utf-8") as my_file:
print(my_file.read())
|
class Vehicle: # 定义交通工具类
Country = 'China'
def __init__(self, name, speed, load, power):
self.name = name
self.speed = speed
self.load = load
self.power = power
def run(self):
print('开动啦...')
class Subway(Vehicle): # 地铁
def __init__(self, name, speed, load, ... |
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))
# 执行结果如下: JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...
# 其中第二个函数是替换后的字符串;本例中为'-' 第四个参数指替换个数。默认为0,表示每个匹配项都替换。
# 使用re替换string中每一个匹配的子串后返回替换后的字符串。
# 格式: re.sub(pattern, repl, string, count)
# re.... |
# n = 10
# while True:
# n = int(n/2)
# print(n)
# if n == 0:
# break
# def trues(n):
# n = int(n/2)
# return n
# result = trues(10)
# result2 = trues(result)
# result3 = trues(result2)
# print( result,"\n",result2,"\n",result3)
# import sys
# sys.setrecursionlimit(100)
# def trues(n):
# ... |
# 给你一个整数数组 arr,请你帮忙统计数组中每个数的出现次数。
#
# 如果每个数的出现次数都是独一无二的,就返回 true;否则返回 false。
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
res=dict()
for i in arr:
res[i]=res.get(i,0)+1
temp=res.values()
if len(temp)==len(set(temp)):
return True
... |
import datetime
ano = datetime.date.today().year
entrada = input('Digite o nome do arquivo que deseja abrir, juntamente com sua extensão: ')
saida = input('Digite o nome da saída: ')
lista1 = list()
lista2 = list()
with open(f'{entrada}', 'w') as arq:
for r in range(2):
nome = input('Digite seu nome: ')
... |
"""
Try, Except, Else, Finally
Dica de quando e onde tratar código:
TODA ENTRADA DO USUARIO DEVE SER TRATADA!
OBS.: A função do usuário é DESTRUIR seu sistema
num = 0
# Else -> É executado somente se nao ocorrer o erro.
try:
num = int(input('Informe um numero: '))
except ValueError:
print('Valor incorreto')... |
cont = 0
lista_dicionario = []
while True:
variavel = 'variavel_' + str(cont)
# valor pode ser substituido por pegar valor automaticamente
valor = input('Digite valor: ')
if valor:
lista_dicionario.append({variavel: valor})
cont += 1
else:
break
# Verificando se está tudo cer... |
"""
Dunder Main e Dunder Name
Dunder -> Double Under
Dunder Name -> __name__
Dunder Main -> __main__
Em Python, são utilizados Dunder para criar funções, atributos, propriedades e etc utilizando Double Under para
não gerar conflito com os nomes desses elementos na programação.
# Na linguagem C, temos um programa da... |
"""
_Loop for_
Loop -> Estrutura de repetição
For -> Uma dessas estruturas
#Python
for item in interavel:
//execução do loop
Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis
Exemplos de iteráveis:
- String
nome = 'Geek University'
- String
lista = [1, 3, 5, 7, 9]
- Range
nume... |
"""
Reversed
Obs.: Não confunda com a função reverse() que estudamos em listas
A função reverse() só funciona em listas.
Já a função reversed() funciona com qualquer iterável.
Sua função é inverter o iterável.
A função reversed() retorna um iteravel chamado List Reverse Iterator
# Exemplos
listas = [1, 2, 3, 4, 5]... |
"""
Função com retorno
numeros = [1, 2, 3]
ret_pop = numeros.pop()
print(f'Retorno de pop: {ret_pop}')
ret_pr = print(numeros)
print(f'Retorno de print: {ret_pop}')
# Exemplo função
def quadrado_de_7():
print(7 * 7)
ret = quadrado_de_7()
print(f'Retorno {ret}')
OBS.: Em Python, quando uma função não retor... |
"""
Verificar se o numero é quadrado perfeito
"""
def quadrado_perfeito(n):
if n == int(n) and n != 0:
raiz = n ** 0.5
if raiz == int(raiz) and n > 0:
return f'O número {n} é um quadrado perfeito'
else:
return f'O número {n} não é um quadrado perfeito'
n = int(inp... |
"""
Módulo Collection - Deque
https://docs.python.org/3/library/collections.html#collections.deque
Podemos dizer que o deque é uma lista de alta performance.
# Importa
from collection import deque
# Criando deques
deq = deque('geek')
print(deq)
# Adicionando elementos no deque
deq.append('y') # Adiciona no f... |
"""
Soma dos elementos acima da diagonal principal da matriz
"""
from random import randint
def soma_diag_superior(matriz):
acima_diagonal_principal = []
for l in range(0, 3):
for c in range(0, 3):
if l < c:
acima_diagonal_principal.append(matriz[l][c])
return f'A soma ... |
"""
Soma de algarismos
"""
def soma(num):
result = 0
while num > 0:
result += num % 10
num = num // 10
return result
n = int(input('Digite um numero para saber a soma de algarismos: '))
print(f'A soma dos algarismos de "{n}" é {soma(n)} ')
|
"""
Pacotes
Módulo -> É apenas um arquivo Python, que pode ter diversas funções para utilizarmos
Pacote -> É um diretório contendo uma coleção de módulos
Obs.: Nas versões 2.X do Pthon, um pacote Python deveria conter dentro dele um arquivo chamado __init__.py
Nas versões do Python 3.x não é mais obrigatória a utol... |
X = list(map(int, input().split()))
if X[0] == X[1]:
print(X[2])
elif X[1] == X[2]:
print(X[0])
elif X[0] == X[2]:
print(X[1])
else:
print(0)
|
# Helper functions are placed here so as not to clutter main files
import numpy as np
# Converts various types of input data to a binary representation
def to_binary(data):
if isinstance(data, str):
return ''.join([ format(ord(i), "08b") for i in data ])
elif isinstance(data, bytes) or isinstance(d... |
def fizzbuzz():
fizz_string = ""
for i in range(1,101):
if(i % 3 == 0) and (i % 5 == 0):
fizz_string = fizz_string + " fizzbuzz"
elif(i % 3 == 0):
fizz_string = fizz_string + " fizz"
elif(i % 5 == 0):
fizz_string = fizz_string + " buzz"
else:
... |
class Solution:
def CheckPermutation(self, s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
else:
for i in s1:
if s1.count(i)!=s2.count(i):
return False
return True
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 18:57:54 2020
@author: CALVIN
"""
import turtle
a=turtle.Turtle()
bg=turtle.Screen()
bg.bgcolor('black')
a.color('red')
a.shape('turtle')
a.penup()
for i in range(1,150):
a.stamp()
a.forward(10+i)
a.left(20)
turtle.done() |
#!python
class BinaryTreeNode(object):
def __init__(self, data):
"""Initialize this binary tree node with the given data."""
self.data = data
self.left = None
self.right = None
def __repr__(self):
"""Return a string representation of this binary tree node."""
... |
class BinaryNode(object):
def __init__(self, data):
'''Initalize the binary node with the given data'''
self.previous_pointer=None
self.data = data
self.next_pointer=None
def __repr__(self):
'''Return a string representation of this node'''
return 'Node({!r})'.fo... |
class Athlete:
def __init__(self,ht,wt,bodyfat):
self.__ht = ht
self.__wt = wt
self.__bf = bodyfat
def get_ht(self):
return self.__ht
def get_wt(self):
return self.__wt
def get_bf(self):
return self.__bf
class Football_Player(Athlete):
# inherites a... |
def sleep():
print("You go to sleep after a long day. Get some well deserved rest :)\n\nPlay again? (y/n)\n")
choice = input().lower()
while True:
if choice == "y":
return "initial_room"
elif choice == "n":
return "end"
else:
print("I don't underst... |
import sys
n = int(sys.stdin.readline())
def level(x, y, divider):
divider //= 3
while divider > 1:
if (x // divider) % 3 == 1 and (y // divider) % 3 == 1:
return divider
else:
divider //= 3
return 1
def isMidpos(x, y, lv):
return (x // lv) % 3 == 1 and (y // lv) % 3 == 1
for y in r... |
class Position:
x: int
y: int
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def manhattan(a: Position, b: Position):
return abs(a.x - b.x) + abs(a.y - b.y)
def middle(a: Position, b: Position):
if a.x == b.x:
return [Position(a.x, (a.y + b.y) // 2)]
if a.... |
# 심심
from abc import *
class Phone:
@staticmethod
def row(button):
return (button - 1) / 3
@staticmethod
def col(button):
return (button - 1) % 3
@staticmethod
def button_distance(src, dst):
return abs(Phone.row(src) - Phone.row(dst)) + abs(Phone.col(src) - Phone.col(... |
def solution(s):
st = []
for ch in s:
if st[-1:] == [ch]:
st.pop()
else:
st.append(ch)
return 0 if st else 1
def main():
assert solution("baabaa") == 1
assert solution("cdcd") == 0
if __name__ == '__main__':
main()
|
def is_prime(n):
if n < 2:
return False
sq = int(n ** 0.5)
for i in range(2, sq + 1):
if n % i == 0:
return False
return True
def solution(n):
answer = 0
for i in range(2, n + 1):
if is_prime(i):
answer += 1
return answer
def main():
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/31 14:39
# @File : leetCode_541.py
'''
思路:
从0开始,步长为 2k,
取前k个字段反转,后k个字段保持
'''
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
res = ""
fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/17 16:52
# @File : leetCode_20.py
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) < 1:
return True
if len(s) == 1:
return False
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/26 14:32
# @File : leetCode_13.py
'''
罗马数字转换为int
思路:从头向后转,定义一个转换字典
如果新的数比 已经转换的最后一个数大,则已经转换的最后一个数设置为负,
最后求和
'''
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roma = {... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/6 16:55
# @File : leetCode_557.py
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
#ss = s.split(" ")
return " ".join([t[::-1] for t in s.split(" ")])
# ... |
person={
"name": "luis",
"last_name": "salazar",
"age": "35",
"favorite_movies": ['uno', 'dos', 'tres'],
"favorites_books":[{
"title":"primer libro",
"author": "primer autor"
},
{
"title":"segundo libro",
"author": "segundo autor"
... |
import numpy as np
import math
class Line:
def __init__(self, a, b):
"""Two endpoints in the form of [x, y]"""
self.a = list(a)
self.b = list(b)
def is_vertical(self):
if self.a[0] == self.b[0]:
return True
return abs((self.a[1] - self.b[1]) / (... |
# create a mapping of state to abbriavation
states= {
'Oregon' : 'OR',
'Florida' : 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
#create a basic set of status and some cities in them
cities= {
'CA': 'San Fransisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
#add some more cities
cities['NY']= 'New Y... |
#This is butifull example illustrating the Reccursion, extend and append
def flat_list(li):
res=[]
for el in li:
if type(el) is list:
res.extend(flat_list(el))
else:
res.append(el)
return res
if __name__=="__main__":
li=[['a',['b',['c','d'],'e'],'f']]
v0=flat_list(li)
print v0
|
#국민대학교 20113274 김한결
# 로또 번호 생성기
import random
s = set()
times = 50
while times:
while s.__len__() <6: #집합의 원소가 6개가 될때까지 반복
s.add(random.randrange(1,47))
print(s)
s.clear()
times -=1 |
import sqlite3
from tkinter import Tk, Text, BOTH, W, N, E, S, Listbox, StringVar,END
from tkinter.ttk import Frame, Button, Label, Style, Entry
#UI 클래
class BookManagerUi(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.d... |
class GeographicPoint(object):
def __init__(self, lat, lon, alt):
self._latitude = lat
self._longitude = lon
self._altitude = alt
@property
def latitude(self):
return self._latitude
@property
def longitude(self):
return self._longitude
@property
def... |
from Node import Node
class printCommonPart(object):
def print_common_part(self, head1: Node, head2: Node):
while head1 is not None and head2 is not None:
if head1.value < head2.value:
head1 = head1.next
elif head1.value > head2.value:
head2 = head2.n... |
class TwoNumSum(object):
# 暴力解法
def two_num_sum1(self, nums: list, target: int) -> list:
if nums.__len__() < 2:
return []
for i in range(0, nums.__len__()):
for j in range(i+1, nums.__len__()):
if nums[i] + nums[j] == target:
retur... |
from math import sqrt, ceil
import random
# We can generate a random number using the randint method
random_number = random.randint(0, 10)
print(random_number)
x = sqrt(9)
print(x)
y = ceil(x)
print(y) |
# print product of elements in a list and even numbers in it
def mult(r):
mux=1
for i in r:
mux=mux*i
print("mult result is : ",mux)
print("even numbers : ")
for i in r:
if i%2==0:
print(i)
# reverse the string
def strrec(sad):
print(sad)
mad=""
for i in range(len(sad)-1,-1,-1):
mad=mad+sad[i]
p... |
var=int(input("enter a number"))
#increasing stars
for i in range(1,var+1):
print("*"*i)
#other format of incresing stars(this is standard format from youtube)
for i in range(1,var+1):
for j in range(1,i+1):
print("*",end="")
print()
# #decreasing stars
for i in range(var,0,-1):
print("*"*i)
#to print 1,2... |
# find an element in a list
L=["digital","lync","hyderabad","gachibowli","kukatpally"]
A="Lync"
flag1=0
for i in L:
if i is A:
flag1=flag1+1
if flag1>=1:
print("present in the sequence")
else:
print("not present in the sequence")
# perform bitwise operations
a=45
b=65
print("bitwise and = ",a&b)
print("bi... |
n=int(input("enter a number : "))
# to print stars first inc then dec
for i in range(1,n+1):
if i!=n:
print("*"*i)
else:
for j in range(n,0,-1):
print("*"*j)
print()
# to print stars from right side
for r in range(1,n+1):
print(" "*(n-r)+"*"*r)
print()
#to print abcde
for s in range(ord("a"),ord("a")+n):... |
# print('hello world')
# name=input('what is your name:\n')
# print('hi,%s'%name)
# last=input('ur surname:')
# print('%s' %last)
# x=int(input('enter integer:'))
# y=float(input('enter a float:'))
# print(x+y)
# r=float(input('enter a radius of circle:'))
# print('area:',3.14*r**2)
# print('perimeter:',2... |
# nums1=list(map(float,input('enter nums1:').split()))
# nums2=list(map(float,input("enter nums2:").split()))
# sum = len(nums1) + len(nums2)
# merged = []
# l, r = 0, 0
# if sum % 2 != 0:
# # index = [sum / 2]
# while (l + r) < (sum / 2):
# if nums1[l] < nums2[r]:
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.