text stringlengths 37 1.41M |
|---|
def convertBinToHex(bin):
hex = " "
if bin == "0000":
hex = "0"
elif bin == "0001":
hex = "1"
elif bin == "0010":
hex = "2"
elif bin == "0011":
hex = "3"
elif bin == "0100":
hex = "4"
elif bin == "0101":
hex = "5"
elif bin == "0110":
... |
# Example input
L = [1,2,3,4]
x = 10
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def poly(base):
""" base: int
Returns the polynome valuation a... |
# word bank to look for keywords
from collections import namedtuple
import itertools
class Aspect():
def __init__(self, key, representation, keywords):
self.key = key
self.representation = representation
self.keywords = keywords
def __repr__(self):
return 'Aspect with key: {... |
# -*- coding: utf-8 -*-
# This script analyzes text data based on lexicons
# Usage: python analyze_data.py output/moby_dick_data.csv output/moby_dick_analysis.json 400 200
import csv
import json
import sys
# Files
CATEGORIES_FILE = 'data/categories.json'
# Input
if len(sys.argv) < 4:
print "Usage: %s <data cs... |
import sqlite3
from datetime import datetime
# This class is a simple handler for all of our SQL database actions
# Practicing a good separation of concerns, we should only ever call
# These functions from our models
# If you notice anything out of place here, consider it to your advantage and don't spoil the s... |
from typing import List
class Solution:
"""
@title 350. 两个数组的交集 II
@method 哈希表
定义哈希表存储 nums1 每个元素出现的次数,
遍历 nums2,如果当前元素在 nums1 中出现次数大于 0,
则将当前元素加入返回列表中,并将哈希表中记录的次数减 1。
"""
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
hash, result = {}, []
for ... |
import random
import time
def dice():
player = random.randint(1,6)
print("You rolled " + str(player) )
ai = random.randint(1,6)
print("The computer rolls...." )
time.sleep(2)
print("The computer has rolled a " + str(ai) )
if player > ai :
print("You win") # notice indentation
... |
import hello
"""
Tests the hello module
"""
def test_hello_no_name():
"""
Checks that if no name passed we get hello, world
"""
assert hello.hello() == 'Hello, World'
def test_hello_with_name():
"""
If passed a name returns, "Hello, name"
"""
assert hello.hello('Olly') == 'Hello, ... |
import sys
v = sys.argv[1]
o = ["[","{","("]
c = ["]","}",")"]
q = []
if len(v)==0:
print("true")
exit()
for i in v:
if i in o:
q.append(i)
if i in c:
if i == c[o.index(q[-1])]:
q.pop()
else:
print("false")
exit()
if len(q)==... |
'''
A simple set of functions to determine whether a string of text is saying it is
a test or not
@author: Peter
'''
def thisQ(line):
if line == None:
return ("Contains \"this\"", "Does not contain \"this\"")
if "This" in line or "this" in line:
return "Contains \"this\""
else:
... |
from dataclasses import dataclass
@dataclass
class StatCard:
player = str
power = int
stability = float
def __init__(self, player, power, stability):
self.player = player
self.power = power
self.stability = stability
def __str__(self):
return str(self.player) + " ... |
class dog:
# Class Attribute
species = "mammal"
# Initializer / Instance Attributes
def __init__ (self, name, age):
self.name = name
self.age = age
#Instantiate the Dog object
phillo = dog("Phillo", 5)
mikey = dog("Mikey", 6)
doug = dog("Doug", 4)
# Access the instance attribute... |
import random
from Hero import Hero
from Weapon import Weapon
class Tavern():
def __init__(self, hero):
print(hero.char.name + " walks into the tavern, it's dark and smoky.")
print("You make your way to the bar.")
input()
self.tavern_menu(hero)
def tavern_menu(self, hero):
... |
import random
from Battle import Battle
from Enemy import Enemy
from Weapon import weapon_pile
class Castle():
def __init__(self, hero):
print("You walk up to the castle")
if random.randrange(0, 100) > 90:
print("The guards determine you're a threat, and want to fight!")
g... |
i = 1
print(id(i), i)
i += 1 # equivalente a i = i + 1
print(id(i), i)
print("------------------------")
for _ in range(0, 3):
i *= 2 # equivalente a i = i * 2
print(id(i), i)
# augmented assignment |
"""
Colecciones de datos
4 - List
5 - Tuples (son inmutables)
6 - Sets (conjunto unico de elementos)
7 - Dictionary (llave-valor)
(tb se puede iterar en las llaves/valores de los diccionarios y los sets)
"""
miLista = list()
miLista2 = list([1, "uno", "1"]) # list es una funcion que coge solo un argumento: list(algo... |
"""
Manejo y control de Errores
"""
def divide(x, y):
print("%s/%s" %(x, y), end= ": ")
try:
result = x / y
except TypeError:
"""cuando se de un error de tipo entro en esta parte"""
print("Estas dividiendo un string por un numero")
except ZeroDivisionError:
# raise ZeroD... |
import unittest
import intro_lists
class MyTestCase(unittest.TestCase):
def test_swap_one(self):
list1 = [12, 35, 9, 56, 24]
expected = [24, 35, 9, 56, 12]
self.assertEqual(expected,intro_lists.swap(list1))
def test_swap_two(self):
list1 = ["pie", "apple"]
expected = [... |
import sys
import time
'''显示出python所有的内建函数【内嵌的函数】'''
print(dir(__builtins__))
'''
新建对象后,对象都有一个唯一的身份标识自己ID,对象一旦建立,ID永远不会改变。
如果对象的类型被改变。如从list变为tuple,那么对象的ID和类型就变了。以前的ID将会被收回。
引用计数器:此对象再被调用,如被方法使用、对象再次改变、或者去给其他变量赋值时,这个引用计数属性值就会加1
'''
a=[1,2,3]
print(id(a),type(a),sys.getrefcount(a))
a.append(4)
time.sleep(1)
a=tuple(... |
#encoding=utf-8
import os
'''
OS库:主要是python与操作系统之间的交互
操作系统主要的功能就是读、写、执行一些文件和程序
主要就是获取文件的一些基础信息:如路径、时间、属性、大小、判断时=是目录还是文件
判断文件路径是否存在,
'''
print( os.getcwd(),"获取当前工作目录")
os.mkdir("mk")
os.rmdir("mk")
print("执行创建目录,删除目录")
print(os.path.curdir ,".号 可与join进行拼接 代表当前目录 ,可以用在join内做第二... |
import threading
lock=threading.Lock()
def p(x):
global zer
zer=1000
while zer>0:
#lock.acquire() # 第一种方式
try:
zer=zer-x
print(zer,threading.current_thread())
finally:
#lock.release()
if zer< 0:
print("over",threading.cur... |
import threading
def p():
# global timer
timer = threading.Timer(2.0, p)
timer.start()
p()
# if __name__ == "__main__":
#
# timer = threading.Timer(2.0, p, ["Hawk"]) ##每隔两秒调用函数hello
#
# timer.start()
# #timer.cancel()
def fun_timer():
print("hello timer!")
# 定义全局变量
... |
import pickle
import json
class lei:
def __init__(self,name,age):
self.name=name
self.age=age
# def __str__(self):
# return '[%s : name %s age %s ]' %(self.__class__,self.name,self.age)
if __name__ == '__main__':
'''
当对象没有被序列化时,是无法直接写入文件中,如果想写入文件中,即使是定义__... |
list1=[1,2,3,4,5,6,8,9]
#列表追加append方式,可以追加任意类型,相当于将内容当做一个整体了
list1.append([8,9])
list1.extend([3,4]) # extend 将可迭代对象依次进行添加类型,如字符串,元祖,列表等
listv=[1,2,3,4,9]
tuplev=('a','1ab','c','o')
print(max(listv))#求列表中最大值
print(min(tuplev))#求元祖中最大值,必须保证类型相同
print(list1) #list列表内的元素是可重复的
print(list1.count(3)) #求列表内元素出现的次数
list1.ex... |
''''
#Write a Python program to find the first repeated character in a given string
'''
string_val = "world hello"
# print(len(string_val))
for index in range(0,len(string_val)):
# print(string_val[index])
count_repitions = int(string_val.count(string_val[index]))
if count_repitions > 1:
print("fir... |
import string
import random
allList=[string.digits,string.ascii_lowercase, string.ascii_uppercase, string.punctuation]
def generate(length):
X=[]
for i in range(length):
if(i>3):
i=random.randint(0,3)
X.append(allList[i][random.randint(0,len(allList[i])-1)])
random.shuffle(X)... |
import numpy as np
a= np.linspace(0,1,100)
# plt.show(block=False) #let the code continun
n=np.zeros(10)
n=np.append(1,n)
n=np.append(n,1)
print(n)
m=np.roll(n,3)
print(m) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
QUESTION = "1.4"
import time
def solve_it(str):
chars = {}
lowercase = str.lower()
for char in lowercase:
if char.isalpha() == False:
continue
elif char in chars:
count = chars[char]
count += 1
... |
# n this quiz, you should identify ways in which the implementation of this function could be improved, without removing its current usage.
# Here are some questions to get you started thinking about this, but you should use your own judgement!
# Reading the code, is it clear what each piece does? How could it be be ... |
# Write a function named population_density that takes two arguments,
# population and land_area (in square kilometres), and returns a population density calculated from those values.
# Code
def population_density(population, land_area):
return population/land_area
# To verify the results below are the test c... |
# lists to be shared by both
list_1 = ["My house is on fire.", "My, my you are a cute lion.", "Lion, tiger and bears.", " What a dark day.",
"Stuck in the sky", "More fire and dragon's breath.", "lions need snuggles."]
list_2 = ["A lion in time.", "What happened to the cat upstairs?", "Vern's untimely demis... |
#Kyle Grinstead/Josh Gladstone
#CS 1301 B04
#kylegrinstead@gatech.edu/marquis.gladstone@gatech.edu
#902983922/902985753
#We worked on this homework alone, using only this semester's course materials.
from Myro import *
init()
def makeWebPage(numberOfPictures):
html = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.... |
from Structs import TreeNode
"""
给定一个二叉树,返回每层的节点值(一层一层,从左到右)
Input:
3
/ \
9 20
/ \
15 7
OutPut:
[
[3],
[9,20],
[15,7]
]
Tips:
层序遍历二叉树是典型的广度优先搜索BFS的应用,但是这里稍微复杂一点的是,我们要把各个层数分开,存到一个二维向量里面
建立一个queue,先把根节点存放进去,这时候寻找左右两个子树,去掉根节点。
"""
class Solution:
def levelOrder(self, root):
... |
"""
给定一组不重复的值,返回所有可能的排列
递归实现
"""
class Solution:
def permute(self, nums):
self.res = []
sub = []
self.dfs(nums, sub)
return self.res
def dfs(self, nums, subList):
if len(subList) == len(nums):
# 如果组成的组合长度等于给定的,就添加到res中
self.res.append(subList[... |
"""
宝石最优的购买和销售时机
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
思路:
循环一次,分别记录目前为止的最大收益sofarMax,以及实际的最大收益totolMax(最终的返回值)
针对每个循环值:尝试更新最大收益,... |
'''
有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
括号必须以正确的顺序关闭,"()" 和 "()[]{}" 是有效的但是 "(]" 和 "([)]" 不是。
'''
class Solution(object):
def isValid(self, s: str) -> bool:
stack = []
info = {')': '(',
']': '[',
'}': '{'}
for char in s:
if c... |
"""
最小栈
设计一个栈结构, 支持以下操作
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
"""
class MinStack(object):
def __init__(self):
self.stack = []
def push(self, x):
#self.stack.... |
"""
给定一个数字的数组,返回两个数字的索引,是的这两个数字的和正好是目标值
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路,利用hashtable保存每个数字的计算信息,其中 key 是to_find, value 是cur的索引
"""
class Solution(object):
def twoSum(self, nums: [int], target: int) -> [int]:
result = [] # 结果集合
... |
"""
返回一句话中出现次数最多的单词,不在禁用词列表中
"""
class Solution:
def mostCommonWord(self, paragraph, banned):
def cleanChar(w):
content = "!?',;."
for c in content:
if c in w:
w = w[:-1]
w = w.lower()
return w
maxcur = 0
... |
"""
统计数字的二进制的和
e.g:
num=5
:return [0,1,1,2,1,2]
在循环中,在循环数的二进制表示中, 1出现的次数分别为0,1,1,2,1,2次
"""
class Solution(object):
def countingBits(self,nums) -> [int]:
result = []
for index in range(nums+1):
bina = bin(index)
result.append(bina.count('1'))
return result
if ... |
import helpers
class Card:
"""
Card object representing a single playing card.
"""
def __init__(self, suit, value):
self.suit = suit if suit in helpers.SUITS.keys() else None
self.value = value if value in helpers.VALUES.keys() else None
def __str__(self):
return f"{helpe... |
#bubble sort algorithm
import time
def bubbleSort(arr):
print ("##BubbleSort algorithm##")
isSorted = False
while (not isSorted):
isSorted = True
for i in range (0, len (arr) - 1):
if arr[i] > arr[i + 1]:
x = arr[i]
arr[i] = arr[i + 1]
... |
#number_cakes = 6
#cake_price = 3.10
#bill = number_cakes * cake_price
#print("The price of", number_cakes, "cakes is", bill, "pounds.")
number_cakes = int(input("How many cakes did you buy?"))
cake_price = 3.10
bill = number_cakes * cake_price
if number_cakes == 1:
print("The price of", number_cakes, "ca... |
file = 'precipitations-Europe.txt'
file = open(file,'r')
file_info = file.readlines()
##print(file_info)
info_list = []
for line in file_info:
info_list.append(str(line).strip('\n').split()) # appends everything to a list and removes \n
del(info_list[0]) # removes first comment line of text file
file.close(... |
##scalar = 2.5
##vector = [1,2,3]
##def scalar_product(scalar, vector):
## new_vector = []
##
## for i in range(len(vector)):
## scalar_product = vector[i] * scalar
## new_vector.append(scalar_product)
## print(new_vector)
##
##scalar_product(scalar, vector)
vector1 = [1,2,3]
ve... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
size = 0
node = head
while node:
size += 1
node = nod... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:
return None
size = 0
fast_node = he... |
n=int(input("nhap n "))
while n >=0:
print (n)
n=n-1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
start = "hit"
end = "cog"
a_list = ["hit", "hot", "dot", "dog", "lot", "log", "cog"]
a_dict = {}
def find_path(path):
length = len(path)
node = path[length-1]
# 如果节点为终点就返回
if node == end:
print(path,"该路径可以从",start,"到",end)
return
... |
import argparse
import re
def is_naughty(string):
naughty = ['ab', 'cd', 'pq', 'xy']
for n in naughty:
if n in string:
return True
return False
def has_doubles(string):
for i in range(len(string) - 1):
if string[i] == string[i + 1]:
return True
return Fals... |
str = 'Hello World!'
print str
print str[0]
print str[2:5]
print str[2:]
print str * 2
print str + "TEST"
|
class BankAccount:
def __init__(self, name, balance, currency):
if name == "":
raise ValueError
if balance < 0:
raise ValueError
if currency == "":
raise ValueError
self.__name = str(name)
self.__balance = balance
self.__currency = ... |
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def fibonacciHelper(n):
if n == 1:
return 1
if n == 2:
return 1
if n > 2:
return fibonacciHelper(n-1) + fibonacciHelper(n-2)
def fibonacci(n):
lst = []
for i in range(1, n+1):
... |
print('Algoritmos de Backtracking')
print('---------- -- ------------\n')
print('Caixeiro Viajante')
solucao = None
def caixeiroBaB(pilha, candidato):
if len(candidato) == G.n \
and custo(candidato) < custo(solucao):
solucao = candidato
return
elif custo(candidato) >= custo(solucao):
return
for tentativa in... |
#Upload the error free program on LMS.
class employee:
def __init__(self, name, sal):
self.__name=name # private attribute
self.__salary=sal # private attribute
>>>e1=employee("Bill",10000)
>>>e1.__salary
AttributeError: 'employee' object has no attribute '__salary'
|
a = float(input('Введите число:'))
a2 = a * a
a3 = a2 * a
a5 = a3 * a2
a10 = a5 * a5
print(a10)
|
def is_square(n):
if int(n**0.5)==n**0.5:
return True
else:
return False
def is_even(n):
if n%2:
return False
else:
return True
n=int(input("Enter the upper limit"))
for i in range(2,n+1,2):
if is_even(i) and is_square(i):
print(i,end=" ") |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 18 10:52:18 2018
@author: Sankalp
"""
l=['a',0,2]
for i in l:
try:
print("Reciprocal is:",1/i)
except ZeroDivisionError as e:
print("Cannot divide by 0:",e)
except TypeError as e:
print("Only numbe... |
from hashtable import HashTable
import json
import matplotlib.pyplot as plt
from typing import List
def uniformity_test(table_size: int) -> float:
"""
Uniformity test for hash fn using Pearson's Chi squared test
The returned value should be within 0.95 <= r <= 1.05 for a good hash function
"""
tab... |
#!/usr/bin/python2.7
import crypt ,zipfile,sys
def extractfile(zfile,password):
try:
zfile.extractall(pwd=password)
return password
except Exception,e:
print e
def main():
if len(sys.argv)==3:
zfile=zipfile.ZipFile(sys.argv[1])
passfile=open(sys.argv[2])
for line in passfile.readlines():
password=lin... |
def add(n1,n2):
return n1+n2
def multiply(n1,n2):
return n1*n2
def subtract(n1,n2):
return n1-n2
def devide(n1,n2):
return n1/n2
def power(n1,n2):
return n1**n2
def floordiv(n1,n2):
return n1//n2
def enter():
n = input()
if n.isdigit():
return int(n)
elif n.isdecimal():
... |
#Program Filename: stoogesort.py (Assignment2)
#Author: Mario Franco-Munoz
#Due Date: 4/15/2018
#Description: This file implements the "stooge sort" function. Reads numeric values from a text file
#loads the values into an array and applies the sort. Output is then stored to merge.out file.
import random
import sys
... |
from pyspark.sql import SparkSession
from pyspark.sql.functions import format_number
from pyspark.sql.functions import mean
from pyspark.sql.functions import year,month,
spark=SparkSession.builder.appName("Walmart").getOrCreate()
df=spark.read.csv("walmart_stock.csv",header=True,inferSchema=True)
df.printSchema()
df.... |
#!/usr/bin/python3
from pymongo import MongoClient
import random
import sys
#variable
nMin = 0
nMax = 99
title = r'''
\\\\================================////
|||| ||||
Welcome to BiiLotto
Author: Bii811
|||| ||||
////=========... |
import random
from collections import Counter
someWords = '''kartheek kamala chilla venkat srikar siddarth manikanta'''
someWords = someWords.split('')
word = random.choice(someWords)
if _name_ == ' _main_ ':
print(' Guess the words from the fill blanks ! The HINT is they are my family names')
for i in word... |
# 1 Countdown - Create a function that accepts a number as an input. Return a new list that
# counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countDown(n):
list=[]
for i in range(n,-1, -1):
list.append(i)
... |
#8/3/2020
# Hi, my name is Morley Tatro, and I have been coding seriously for 8 years.
# The other day, I was hoping to buy toilet paper, and I went to 3 stores: Ralphs, CVS, and Walgreens.
# Unfortunately, I wasn't able to find any. Instead, I bought the following 2 items:
# 6 bananas, at a price of .25, for a total o... |
'''
Plan:
Store each weight as a key, the index location as the value
Iterate through the list of weights
for each weight:
see if there is a key such that (limit - weight = key)
return the weight and the key (both weights)
Search the dictionary for the values of each key
... |
for num in range(50,200):
i=num
count=0
while(i>=1):
if(num%i==0):
count=count+1
i=i-1
if(count==2):
print(num)
|
# Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.
# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
# Но если вместо числа вводит... |
import torch
import torch.nn as nn
def positive_elu(x, alpha):
"""An elu translated of +1. This provides an activation function that:
- is not capped at 1
- never returns negative values
- never returns exactly 0
"""
return torch.nn.ELU(alpha)(x) + 1
class PositiveELU(nn.Module):
def __i... |
"""
Michael Connolly
Alorithmic Thinking, Part 2
Project 3
"""
import urllib2
import math
import alg_cluster
import random
import time
import matplotlib.pyplot as plt
#import alg_project3_solution
#import alg_project3_viz
def slow_closest_pair(cluster_list):
"""
Takes a list of Cluster objects an... |
def isAnagram(s, t):
if len(s) != len(t): return False
for i in range (ord('a'), ord('z') + 1):
letter = chr(i)
if s.count(letter) != t.count(letter): return False
return True
print(isAnagram('barbie', 'oppenheimer')) # False
print(isAnagram('race', 'care')) # True |
from matplotlib import pyplot as plt
import environment as env
import trajectory as tj
import functions as fn
def convergence_speed():
"""
Computes and display the convergence of p and r
"""
p_error = []
r_error = []
T = [i for i in range(100, 1200, 50)]
# we compute the error of the appr... |
############################# problem 1 ########################
### Multinomial Regression ####
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
Mdata = pd.read_csv("C:/... |
def max_len(list) :
m_len = list[0]
for word in list :
if len(word) > len(m_len):
m_len = word
return m_len
def dic_sort(list_) :
al_str = ("AaBbCcDdEeFfGgHhIiJjKk\
LlMmNnOoPpQqRrSsTtUuVv\
WwXxYyZz")
al_list = list(al_str)
list_len = len(list_)
... |
from math import *
def triArea(b, h) :
return 0.5 * b * h
def volCone(r, h) :
vol = (1/3) * h * pi * r**2
return round(vol, 5)
def divisor(n) :
for i in range(1, n+1) :
if n % i == 0 :
print(i)
def is_prime(i) :
for j in range(2, i) :
if i % j == 0 :
retur... |
name = input("What is your name? ")
print("Glad to meet you",name,"!")
age = input("And can you tell me your age as well? ")
print("Okay, then you're already",age,"Mr.",name,"!")
|
MAX_RATE = int(input("최댓값을 입력하세요. "))
num = int(input("무엇의 배수를 출력할까요? "))
i = 1
while i <= MAX_RATE :
print("%s * %s = %s" % (num, i, num*i))
i += 1
|
from Vehicle import Vehicle
class Truck(Vehicle):
def __init__(self, make, model, color, price, payload):
super().__init__(make, model, color, price)
self.__payload = payload
def setPayload(self, payload): # setter
self.__payload = payload
def getPayload(self): ... |
x = int(input("첫 번째 정수: ")) # x = input("첫 번째 정수: ")는 문자열을 저장함
y = int(input("두 번째 정수: ")) # 따라서 int() 함수를 이용하여 정수로 바꿔주어야 함
sum = x + y
print("합은",sum)
|
a = 1
b = a
print(a) # This means it prints the number 1.
a = 2
print(b) # What will be printed?
|
x = int(input("첫 번째 정수: "))
y = int(input("두 번째 정수: "))
z = int(input("세 번째 정수: "))
if (x > y) :
max = x
else :
max = y
if z > max :
max = z
print(max)
|
import csv
from trie import Trie
''' arquivo que guardara a tabela hash utilizada no projeto '''
class ElemHash():
def __init__(self):
self.movieid = 0
self.generos = None
self.raiting = 0.0
self.num_aval = 0
self.filme = None
# calcula a hash de acordo com o movieid do usuario
def hashing_function(siz... |
def main(n):
square_sum = 0
sum_of_sqr = 0
for i in range(n):
sum_of_sqr += i * i
square_sum += i
square_sum *= square_sum
return square_sum - sum_of_sqr
if __name__ == '__main__':
print(main(1000))
|
#!/Users/fritjof/anaconda3/bin/python3
n = int(input())
for _ in range(n):
s = input().split()
if " ".join(s[0:2]) == "Simon says":
print(" ".join(s[2:len(s)]))
|
#!/Users/fritjof/anaconda3/bin/python3
# problem: judgingmoose, rating: 1.4
l, r = [int(_) for _ in input().split()]
if l == 0 and r == 0:
print('Not a moose')
elif l - r == 0:
print(f'Even {l*2}')
elif abs(l-r) >= 1:
print(f'Odd {max(l, r)*2}')
|
#!/bin/python3
n = 0
while n < 10:
travelled = 0
last_time = 0
x = int(input())
if x == -1: break
for i in range(x):
speed, time = [int(i) for i in input().split()]
travelled += speed * (time - last_time)
last_time = time
print(f'{travelled} miles')
n += 1
|
#!/Users/fritjof/anaconda3/bin/python3
# problem: anthonyanddiablo, rating: 2.4
from math import pi
a, n = [float(_) for _ in input().split()]
def circle(c):
r = c/(2*pi)
return (r**2)*pi
if circle(n) >= a:
print('Diablo is happy!')
else:
print('Need more materials!')
|
s = input()
p = input()
if len(s) > len(p) + 1:
print('No')
elif s == p or p.swapcase() == s or (p == s[0:-1] and s[-1].isdigit()) or (p == s[1:] and s[0].isdigit()):
print('Yes')
else:
print('No')
|
#!/Users/fritjof/anaconda3/bin/python3
# problem: datum, rating: 1.4
import datetime
d, m = [int(_) for _ in input().split()]
d = datetime.date(2009, m, d).weekday()
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print(weekdays[d])
|
class Node:
def __init__(self,data=None, key=None):
self.data=data
self.next=key
class LinkedList:
def __init__(self,data=None):
if data==None:
self.head=None
else:
self.head=Node(data)
def __repr__(self):
return 'LinkedL... |
'''
Created on 20-Mar-2019
@author: guruk
'''
from time import sleep
def sort(nums):
for i in range(len(nums)):
minpos = i
for j in range(i+1 ,len(nums)):
if nums[j] < nums[minpos]:
minpos = j
nums[i],nums[minpos]=nums[minpos],nums... |
'''
Created on 29-Mar-2019
@author: guruk
'''
import os
filen = 'mydata.txt'
print('Join path >>>')
print(os.path.join('folder1','folder2 in folder1','folder3 in folder2','samsung.jpeg -in folder3-'))
print(os.path.join('W:\\Python\\Programs',filen))
print()
print('Current working directory >>>')
print(o... |
'''
Created on 09-Mar-2019
@author: guruk
'''
a = 15 #Global Variable
def update():
a= 10 #Local Variable
print('Inside function ' ,a)
update()
print('Outside function ', a)
print('------------------------')
c = 15 ... |
def greet():
print('Hello')
print("Good morning")
greet()
def add(x,y):
z= x+y
print('added using function - ', z)
add(4, 2)
def subtract(x,y):
z= x-y
return z
res = subtract(4, 2)
print('subtracted using function - ',res)
def mul_divide(x,y):
z= x*y
a= x/y... |
'''
Created on 27-Mar-2019
@author: guruk
'''
#Lesson 27 of Automate the boring stuff
import re
#'^' used outside character class to indicate use of the following text at the
#beginning of the search string
startRegEx = re.compile(r'^Hello')
mo = startRegEx.search("Hello amazing World")
if mo == Non... |
"""Service for validating book's ISBN"""
from re import match
REGEX = '^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})\
[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)\
(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$'
def is_valid(isbn: str) -> bool:
return bool(mat... |
def main():
userInput=input("String:")
print("No of Spaces", count_spaces(userInput))
# Counts the number of spaces
def count_spaces(string):
spaces=0
for char in string:
if char == " " :
spaces = spaces+1
return spaces
main()
|
from turtle import Turtle, Screen
import random
is_race_on = False
my_screen = Screen()
my_screen.setup(width=500, height=400)
user_bet = my_screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "green", "blue", "purple", "grey"]
y_positions = [-12... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.