text stringlengths 37 1.41M |
|---|
# Punto 2
print('Punto 2:')
empresas = {'Google': 'Estados Unidos',
'La Locura': 'Colombia',
'Nokia': 'Finlandia',
'Sony': 'Japon'}
for key, values in empresas.items():
print(key, values)
#Punto 3
def Punto3(key):
return empresas.get(key)
# Punto 4
def Llav... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 21:41:11 2021
@author: Carlos Gustavo Vélez Manco, John Esteban Castro Ramírez
"""
def fizzArray(n):
nums=[0]*n #C1
for i in range(len(nums)): #C2*n
nums[i]=i #C3*n
return nums #C4
"""
CÁLCULO DE COMPLEJIDAD
T(n)=C1+C2*n+C3*n+C4
T(n)... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 11:11:49 2021
@author: LENOVO
"""
def permutations(base, cadena):
if len(cadena) == 0:
print (base)
else:
i = 0
while i < len(cadena):
permutations(base + cadena[i], cadena[0:i] + cadena[i+1:])
i = ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 3 12:16:02 2021
@author: Carlos Gustavo Vélez Manco, John Esteban Castro Ramírez
"""
def bigDiff(nums):
Diff= 0 #C1
for i in range (0,len(nums)): #C2*n
for j in range(0,len(nums)): #C3*n*n
if(nums[i]<nums[j]): #C4*n*n
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 21:42:51 2021
@author: Carlos Gustavo Vélez Manco, John Esteban Castro Ramírez
"""
def tripleUp(nums):
for i in range(len(nums)-2): #C1*(n-2)
if nums[i]==nums[i] and nums[i+1]==nums[i]+1 and nums[i+2]==nums[i]+2:#C2*(n-2)
return True ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 09:32:35 2021
@author: LENOVO
"""
class Fecha():
def __init__(self,dia,mes, anyo):
self.dia=dia
self.mes=mes
self.anyo=anyo
def dia(self):
return self.dia
def mes(self):
return s... |
#first we import pygame
import pygame
#then we have to initialize pygame
pygame.init()
#in this line we create our display "((800,600))"was pixels
screen=pygame.display.set_mode((800,600))
#this line creates game time
clock=pygame.time.Clock()
#in this line we we define bg variable as background img
bg=pygame.im... |
def double_char(str):
answer = ""
for i in str:
answer+=i*2
return answer |
import tkinter as tk
# Crear ventana root
root = tk.Tk()
# Modificar la ventana
root.title("Etiquetador")
root.geometry("200x50")
# Creamos un frame en la ventana
frame = tk.Frame(root)
frame.grid()
# Creamos una etiqueta en el frame
lbl = tk.Label(frame, text="¡Soy una etiqueta!")
lbl.grid()
# Lanzar el ciclo de ... |
import random
texto = input("Ingrese el texto: ")
maximo = len(texto)
minimo = -len(texto)
for i in range(10):
posicion = random.randrange(minimo, maximo)
print("texto[", posicion, "]", end="\t")
print(texto[posicion]) |
import tkinter as tk
class Aplicacion(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
self.crear_componentes()
def crear_componentes(self):
tk.Label(
self,
text="Elegí tu tipo de película favorita"
).grid(
... |
import tkinter as tk
class Aplicacion(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
self.crear_componentes()
def crear_componentes(self):
tk.Label(
self,
text="Elegí tu tipo de película favorita"
).grid(
... |
texto = input("Ingrese el texto: ")
print("Longitud del texto:", len(texto))
print("La letra E, la más común del Español, ", end="")
if 'e' in texto.lower():
print("está en el texto.")
else:
print("NO está en el texto.")
|
n = int(raw_input())
if n % 2 == 0:
print "white"
print 1, 2
else:
print "black"
|
while True:
n,s = raw_input().split()
if n == '0' and s == '0':
break
saida = ""
for e in s:
if e != n:
if e != '0' or (e == '0' and saida != ""):
saida += e
if saida == "":
saida = "0"
print saida
|
value = {}
answer = ""
def setUp():
answer = ""
aux = "qwertyuioplkjhgfdsazxcvbnm"
for e in aux:
value[e] = 0
def query(s):
for e in s:
value[e] += 1
def isPalindrome():
cont = 0
for key in value:
if value[key] % 2 == 1:
cont += 1
return (cont <= 1)
def answer():
cont = 0
while(not isPalindrome())... |
a = int(raw_input())
b = int(raw_input())
c = int(raw_input())
d = int(raw_input())
if a == b + c + d and b + c == d and b == c:
print 'S'
else:
print 'N'
|
def solve(x):
print 'I hate' if x % 2 == 0 else 'I love',
n = int(raw_input())
counter = 0
for i in xrange(n-1):
solve(counter)
print 'that',
counter += 1
solve(counter)
print 'it'
|
import sqlite3
class Review:
dbpath = "data/uva.db"
def __init__(self,pk,Rating,Food_name,Email,city,first,last,image):
self.pk = pk
self.Rating = Rating
self.Food_name = Food_name
self.Email = Email
self.city = city
self.first = first
self.last = last
... |
'''
Created on Dec 30, 2012
@author: keving
Algorithms follow those in Skiena's The Algorithm Design Manual, 2nd Ed
'''
from random import randrange, seed
from collections import deque
class SOSNode:
def __init__(self, value):
self.parent = self
self.value = value
self.ch... |
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(131)
ax2=fig.add_subplot(132)
ax3=fig.add_subplot(133)
ax1.bar([1,2,3],[3,4,5])
ax2.barh([0.5,1,2.5],[0,1,2])
ax2.axhline(0.45)
ax1.axvline(0.65)
ax3.scatter(np.linspace(0,1,5),np.linspace(0,5,5))
fig.delaxes(ax3)
plt.show()
x=... |
age=int(input('Enter your age: '))
name=input('Enter your name: ')
if age>18:
print(f'{name} You can drive')
elif age ==18:
print(f'{name}not decide')
else:
print(f'{name}You cannot drive')
class User:
pass
user1=User()
user2=User()
user1.name='Mike'
user1.age=33
user1.Available=False
user2.name='Ja... |
items={
1: 'car',
2: 'bike',
4:'buggy',
3: 'scooter'
}
for i in range (1,len(items)+1):
if items[i]=='buggy':
print(i)
parts = {
1: 'wire',
2:' motherboard',
3: 'harddrive',
4:' fan'
}
reguirrd_parts=["harddrive"]
print(reguirrd_parts)
for j in range(7,12):
large_number... |
'''
Created on 12 may. 2020
@author: Frodo
'''
import numpy as np
from numpy.lib.shape_base import column_stack
myList = [1, 2, 3]
type(myList)
print(type(myList))
# Las np arrays pueden tener varias dimensiones
array = np.array(myList)
print(type(array))
# Crear una matriz de tantas dimensiones, de 0 a 9, 10 elemen... |
# Logistic regression
#%%
# Importing libraries
import numpy as np
import random
from matplotlib import pyplot as plt
#%%
class LogisticRegression():
def __init__(self):
self.w = np.random.rand(1,1)
self.b = np.random.rand(1,1)
self.J = 0
def __sigmoid(self, z):
return 1 / ... |
'''
作者:wcz
版本:v4.0
日期:22/06/2018
v2.0:根据输入判断是人民币还是美元 进行相关的转换计算
v3.0:程序可以一直运行,直到用户选择退出
V4.0:将汇率兑换封装到函数中
V5.0:使程序结构化;使用lambda函数定义
知识点: 字符串的末三位截取 s[-3:]
字符串除了末3位 s[:-3]
函数名 = lambda <参数列表>: <表达式>
'''
def main():
"""
主函数
"""
# 汇率
USD_VS_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
560. 和为K的子数组
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
说明 :
数组的长度为 [1, 20,000]。
数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
链接:https://leetcode-cn.com/problems/subarray-sum-equals-k/
"""
from typi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
721. 账户合并
给定一个列表 accounts,每个元素 accounts[i] 是一个字符串列表,其中第一个元素 accounts[i][0] 是 名称 (name),
其余元素是 emails 表示该账户的邮箱地址。
现在,我们想合并这些账户。如果两个账户都有一些共同的邮箱地址,则两个账户必定属于同一个人。请注意,即使两个账户具有相同的名称,
它们也可能属于不同的人,因为人们可能具有相同的名称。一个人最初可以拥有任意数量的账户,但其所有账户都具有相同的名称。
合并账户后,按以下格式返回账户:每个账户的第一个元素是名称,其余... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
322. 零钱兑换
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。
如果没有任何一种硬币组合能组成总金额,返回 -1。
你可以认为每种硬币的数量是无限的。
示例 1:
输入:coins = [1, 2, 5], amount = 11
输出:3
解释:11 = 5 + 5 + 1
链接:https://leetcode-cn.com/problems/coin-change/description/
"""
from typing imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
链接:https://leetcode-cn.com/problems/rotate-array
"""
from typing im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
链接:https://leetcode-cn.com/problems/valid-perfect-square
"""
class Solution:
def isPerfectSquare(self, num: int) -> boo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
链接:https://leetcode-cn.com/problems/sqrtx
"""
class Solution:
def ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
33. 搜索旋转排序数组
整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,
使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。
例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
72. 编辑距离
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
- 插入一个字符
- 删除一个字符
- 替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
241. 为运算表达式设计优先级
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。
有效的运算符号包含 +, - 以及 * 。
示例 1:
输入:
"2-1-1"
输出:
[0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
链接: https://leetcode-cn.com/problems/different-ways-to-add-parentheses/
"""
from typing i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
归并排序
"""
def merge_sort(nums):
if len(nums) < 2:
return nums
mid = len(nums)//2
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
return merge(left, right)
def merge(left, right):
result = []
while left and right:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
33. 搜索旋转排序数组
升序排列的整数数组 nums 在预先未知的某个点上进行了旋转(例如, [0,1,2,4,5,6,7] 经旋转后可能变为 [4,5,6,7,0,1,2] )。
请你在数组中搜索 target ,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
示例 1:
输入:nums = [4,5,6,7,0,1,2], target = 0
输出:4
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
"""
from ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
45. 跳跃游戏 II
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
链接:https://leetcode-cn.com/problems/jump-game-ii/
"""
from t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
"""
from typing... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
842. 将数组拆分成斐波那契序列
给定一个数字字符串 S,比如 S = "123456579",我们可以将它分成斐波那契式的序列 [123, 456, 579]。
形式上,斐波那契式序列是一个非负整数列表 F,且满足:
0 <= F[i] <= 2^31 - 1,(也就是说,每个整数都符合 32 位有符号整数类型);
F.length >= 3;
对于所有的0 <= i < F.length - 2,都有 F[i] + F[i+1] = F[i+2] 成立。
另外,请注意,将字符串拆分成小块时,每个块的数字一定不要以零开头,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
链接:https://leetcode-cn.com/problems/trapping-rain-water
"""
from typing import List
class Solution:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
129. 求根节点到叶节点数字之和
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。
每条从根节点到叶节点的路径都代表一个数字:
例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。
计算从根节点到叶节点生成的 所有数字之和 。
叶节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3]
输出:25
解释:
从根到叶子节点路径 1->2 代表数字 12
从根到叶子节点路径 1->3 代表数字 13
... |
# Pre: Recibe dos palabras previamente inicializadas.
# Post: Devuelve la cantidad de letras que suman ambas palabras.
palabra_1 = input('Ingrese una palabra')
palabra_2 = input('Ingrese otra palabra')
def sumarLetras(palabra1, palabra2):
a = len(palabra1)
b = len(palabra2)
sumadeletras = a + b
r... |
# encoding = utf-8
import string
class Solution:
def convertToTitle(self, Input):
"""
Given a positive integer, return its corresponding column title as appear
in an Excel sheet
:param Input:int
:return:str
"""
if n < 0:
return ''
... |
# encoding = utf-8
class Solution:
def climbStairs(self, n):
"""
Each time you can either climb 1 or 2 steps. In how many distinct ways to the top
:param n: int
:return: int
"""
if n == 1:
return 1
if n == 2:
return 2
... |
# encoding = utf-8
class Solution:
def removeDuplicates(self, nums):
"""
Remove the duplicates in-place such that each element appear only once and return
the new length
:param nums: List[int]
:return: int
"""
i = 1
while i < len(nums):
... |
"""
Physics, chemistry, and some math constants.
Package:
RoadNarrows elemenpy package.
File:
constants.py
Link:
https://github.com/roadnarrows-robotics/
Copyright:
(c) 2019. RoadNarrows LLC
http://www.roadnarrows.com
All Rights Reserved
License:
MIT
"""
import math
from elemenpy.core.format import... |
from typing import Callable, List
"""
Class for a Chromosome in the Genetic Algorithm
"""
class Chromosome:
"""
Structure to hold the genes of an individual and its corresponding fitness
"""
def __init__(self, genes: List[int]):
self.genes = genes
self.fitness = 0
def mutate(sel... |
"""
Team: Nicholas DeGroote, Lynn Pickering, Vita Borovyk, and Owen Traubert
To run this code:
requirements: numpy, matplotlib
At the bottom of the code, after the " if __name__ == "__main__": " statement
- Change the parameters you desire to change such as size of board
- Change the policy that you want to run
- ch... |
from pandas import to_numeric
def replace_all_slashes(df, column_name):
func = lambda str: str.replace("/", "_")
df[column_name] = df[column_name].map(func)
return df
def convert_col_to_percent(df, column_name):
if df[column_name].dtype == "O": # Object column
# The column may contain '-' a... |
'''
if the name is less than 3 char,
its a short name!
if the name is more than 50 chars,
its a long name!
otherwise
Damnnnn, you've got a nice name.
'''
name = str(input('Enter your Name: '))
if len(name)<3:
print(f'its a short name!')
elif len(name)>50:
print(f'its a long name!')
else:
print(f'Damnnnn! ... |
def max_of_3_num(*num):
print('dupa')
if len(num)!=3:
print("You should put only 3 numbers.")
else:
print(max(num))
for i in num:
print(i)
max_of_3_num(1,2,3,4) |
number1 = int( input() )
number2 = int( input() )
number3 = int( input() )
largest = -1e10
if number1 > number2 and number1 > number3:
largest = number1
elif number2 > number1 and number2 > number3:
largest = number2
else:
largest = number3
print(largest)
|
import unittest
from funcs import is_palindromic, find_palindromic
class test_is_palindromic(unittest.TestCase):
def test_if_00_is_palindromic(self):
self.assertTrue(is_palindromic(33))
def test_if_002300_is_palindromic(self):
self.assertTrue(is_palindromic(5655565))
def test_if_99999_i... |
def find_multiples(k, n):
"""
returns iterator of all multiples of k in n, up to n
not ordered
"""
seen = set()
for item in (l for i in k for l in range(i, n, i)):
if item not in seen:
seen.add(item)
yield(item)
|
'''
Created on Feb 16, 2018
@author: ckont
'''
class Car:
"Class documentation and stuff goes here"
"it can be printed using ClassName.__doc__"
# instance vars, default values
color = "null"
value = 0
miles = 0
used = False
# methods all need the have self as a parameter
... |
'''
Created on Feb 16, 2018
@author: ckont
'''
print(10+10) #prints 20
print ("10+10") #prints 10+10 as a string
print(-5+10*20) #follows PEMDAS ==> 195
#comments are with hashes
print("10 + 10 is:", 10+10) #use commas to print multiple stuff
#print("10 + 10 is:" + 10+10) doesnt work live Java
#print(3 4) gives an... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 16 00:38:39 2018
@author: tushar
"""
import re
for _ in range(int(input())):
m = re.findall(r'(?<!^)#[0-9a-f]{3,6}', input().strip(), flags = re.I)
if m:
print('\n'.join(m)) |
import calendar
m,d,y = input("input").split()
print(calendar.day_name[calendar.weekday(int(y),int(m),int(d))].upper()) |
from random import randint
num = int(input("Digite um número de 0 a 5: "))
n1 = randint(0, 5)
if num == n1:
print("Você ganhou. Parabéns!!!")
else:
print("Você perdeu!!!") |
n1 = int(input('\033[0;33mDigite o primeiro termo da P.A: '))
n2 = int(input('Digite a razão da P.A: \033[m'))
print("\n")
for n in range(1, 13):
for p in range(0, 1):
pa = n1 + (n - 1) * n2
print("\033[0;31mO {}º termo da P.A é {}\033[m.".format(n, pa))
|
'''
for valores in range(1, 5):
t = (int(input(f"Digite o {valores}º número: ")))
tu = [t]
print(tu)
'''
|
"""
n1 = int(input("Digite o primeiro termo da P.A: "))
n2 = int(input("Digite a Razão da P.A: "))
c = 0
while c < 10:
c += 1
pa = n1 + (c - 1) * n2
print(f"{c}º termo é {pa}") """
print("Gerador de PA v2.0")
print("=-=" * 15)
n1 = int(input("Primeiro termo: "))
n2 = int(input("Razão da PA: "))
t = n1
c =... |
# Object inheritance
class user:
def __init__(self, fname, lname):
self.__fname = fname
self.__lname = lname
def get_full_name(self):
return self.__fname + " " + self.__lname
def user_login(self):
print("Welcome " + self.__fname)
def user_work(self):
print(self... |
# String formatting
animal = "Lion"
#1. Format string in usual/general method
print("Animal is " + animal)
#2. Format string in usual/old method
print("Animal is %s" %animal)
#3. Format string using 'format' method
print("Animal is {}".format(animal))
#4. Format string using f-strings( f / F )
print(f'Animal is {a... |
# String formatting
name = "John"
print("Hello %s" %name)
age = 26
print("You are %d years old" %age)
print("Hello %s, You are %d years old" %(name, age))
user = ["David", 21, "IT"]
print("Hello %s, You are %d years old and you are in the %s dept." %(user[0], user[1], user[2]))
|
import random;
rand_num=random.randint(0,2);
if(rand_num==0):
ai_hit="rock";
elif(rand_num==1):
ai_hit="paper";
else:
ai_hit="scissor";
player1_hit=input("player choose your hit\n").lower();
if(player1_hit==ai_hit):
print("This is a tie");
elif(player1_hit=="rock"):
if(ai_hit=="paper"):
print("ai choose pap... |
import matplotlib.pyplot as plt
import numpy as np
import math
# 导入数据集
def loadDataSet(fileName, splitChar=','):
dataSet = []
with open(fileName) as fr: # 读取完文件数据后自动关闭文件
for line in fr.readlines():
curline = line.strip().split(splitChar)
fltline = list(map(float, curline)) # ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
2017 MCPC Rehearsal at UCSY
Problem-B: Find A Word
'''
import sys
class TestCase():
pass
def parse_tc(tc):
'''
Input: Test Case
Update: tc.num: number of query tc.query: word to be found
Return: None
'''
tc.num = int(s... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
2017 MCPC at UCSY
Problem-D: Car showroom
'''
import sys
class TestCase():
pass
def parse_tc(tc):
'''
Input: Test Case
Update:
Return: None
'''
tc.size = int(sys.stdin.readline())
tc.n = int(sys.stdin.readline())
... |
word1 = input()
word2 = input()
if word1[::-1] == word2:
print("YES")
else:
print("NO")
|
#to store each value with it's corresponding result for later purposes.
fib_recorder = dict()
#Initial fib values
fib_recorder[1] = 1
fib_recorder[2] = 1
#Dynamic Programming is used here to memoize the N values for optimizing the function.
#Some function calls will be free which means it will have O(1) because it... |
import string
word = input()
vowels = {"a", "o", "y", "e", "u", "i"}
result = ""
for char in word:
if char.lower() in vowels:
continue
result += "." + char.lower()
print(result)
|
class Student(object):
"""类"""
name = 'Student'
def __init__(self, name, score):
# 这是属性
# 访问限制
self.__name = name
self.score = score
def _print_score(self):
print('%s: %s' % (self.__name, self.score))
def get_grade(self):
if self.score >= 90:
... |
import os,os.path
def traverse(pathname):
for item in os.listdir(pathname):
fullitem=os.path.join(pathname,item)
#print(fullitem)
if os.path.isdir(fullitem):
traverse(fullitem)
else :
print(fullitem)
traverse("C:\JAVA")
|
print("What do you want to get at the store? Hit enter when you're done.")
list = []
while True:
a = input()
if a == "":
break
list += [a]
print("Okay, here's your list:")
for x in range(len(list)):
print(str(x+1) + ". " + list[x])
print("Do you want to remove anything? \ny or n")
def g... |
# Write a function to check if a linked list is a palindrome
from utils import LinkedList
# List visual: [r, a, c, e, c, a, r]
a_palindrome = LinkedList()
a_palindrome.add_to_tail("r")
a_palindrome.add_to_tail("a")
a_palindrome.add_to_tail("c")
a_palindrome.add_to_tail("e")
a_palindrome.add_to_tail("c")
a_palindrome.... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def get_value(self):
return self.value
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_to_tail(self, value):
new_node = Node(value)
if se... |
# Implement a function to check if a binary tree is a binary search tree
from utils import Node
def validate_bst(bst):
return validate_helper(bst)
def validate_helper(node, min=None, max=None):
if not node: # Check to see if the node exists
return True
# Make sure the node value is within bounds... |
# Determine if a string has all unique characters
# Solution implemented with a dictionary
def is_unique_with_dict(str):
frequency = {}
for char in str:
if frequency.get(char):
return False
frequency[char] = 1
return True
# Solution implemented with a list
def is_unique(str):
chars = [... |
import sys
def fizzbuzz():
for i in range (0, 101):
if i % 3 is 0:
sys.stdout.write("fizz")
if i%5 is 0:
sys.stdout.write("buzz")
sys.stdout.write("\n")
if i%5 is not 0 and i%3 is not 0:
sys.stdout.write(str(i))
fizzbuzz()
|
class Person:
def __init__(self,name, email):
self.name = name
self.email = email
def __repr__(self):
return repr((self.name,self.email))
class Student(Person):
def __init__(self, name, email, college, cls):
super().__init__(name,email)
self.college = college
... |
import traceback
# Import the necessary package to process data in JSON format
print('yes')
try:
import json
except ImportError:
import simplejson as json
# We use the file saved from last step as example
tweets_filename = '/home/vinay/fetched_tweets.json'
tweets_file = open(tweets_filename, "r")
tweets_text =... |
from turtle import Turtle, Screen
import random as r
screen = Screen()
screen.setup(500, 400)
colors = ['green', 'yellow', 'orange', 'red', 'purple', 'blue']
user_bet = screen.textinput(title='Make your bet', prompt="Which turtle will win the race? Enter a color: "
... |
n=int(input("Enter n value"))
i=1
flag=0
while(i<=n):
if(n%i==0):
flag=flag+1
print("factor is",i)
i=i+1
if(flag==2):
print("It is a prime number")
else:
print("It is not a prime number")
|
i=int(input("Enter i value"))
while(i>=1):
print(i)
i=i-1
'''
output
Enter i value20
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1'''
|
zadati_string=input("Unesi neki string: ")
print(zadati_string)
string_lista=zadati_string.split(" ") #od stringa, niza reci, napravi listu
print(string_lista) #reci izmedju kojih je stajao razmak
dict={} #pravimo prazan dict
for rec in string_lista: ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import timeit
def P012():
import math
def divisors(n):
l=2
r=int(math.sqrt(n))+1
for i in range(2,r):
if n%i==0:
l+=2
if i*i==n:
l-=1
return l
n=10
while ... |
#!/usr/bin/env python
# *-* coding:UTF-8 *-*
def checkio(expression):
stack=[]
match={u')':u'(',u']':u'[',u'}':u'{'}
for i in expression:
if i in "([{":
stack.append(i)
elif i in ")}]":
if len(stack)==0:
return False
if stack.pop()!=match[... |
#!/usr/bin/env python
from datetime import datetime
print datetime.now()
seq=[i*9*10**(i-1) for i in range(10)]
seq[0]=0
def DigitN(n):
global seq
acu=0
i=0
while n>acu+seq[i]:
acu+=seq[i]
i+=1
margin = n-acu
cnt = (margin+i-1)/i
num = 10**(i-1)+cnt-1
... |
#!/usr/bin/env python
from datetime import datetime
print datetime.now()
MAX=0
N=0
for a in range(1,100):
for b in range(1,100):
n=a**b
l=sum(map(int,list(str(n))))
if MAX<l:
MAX=l
print MAX
print datetime.now() |
#-*- coding:UTF-8 -*-
'''
使用coursera-dl下载coursera课程资源后, 减少目录层级
'''
import sys
import os
def FlatDir(destdir):
os.chdir(destdir) ## 课程目录
for week in sorted(os.listdir(".")):
#print(week)
os.chdir(week) # 每周目录
i=1
for clazz in sorted(os.listdir(".")):
#pr... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def clock_angle(time):
h,m=time.split(":")
h,m=int(h),int(m)
if h>12:
h=h-12
ha=(h*60+m)/(12*60.0)*360
ma=m/60.0*360
ang=abs(ma-ha)
if ang>180:
ang=360-ang
ang=int(ang*10)
return ang//10 if ang%10==0 else ang/10.0
if __name__ == "__main__":
print clock_angle... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
from datetime import datetime
print datetime.now()
factor=[1]*10
for i in range(1,10):
factor[i]=i*factor[i-1]
def factorial(n):
return sum(map(lambda x:factor[x],map(int,str(n))))
LIMIT=20000
step={}
for i in range(1, LIMIT+1):
cnt=set()
... |
# -*- coding: utf-8 -*-
__author__ = 'xavier'
class Equip(object):
"""
Classe que representa un dels equips d'estirar a corda.
Conté la llista dels jugadors que en formen part
"""
def __init__(self, equip):
self.equip = equip
self.jugadors = []
def getnom(self):
"""
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 09:02:16 2019
#bulletPointAdder.py -Adds Wikipedia bullet points to the start of each line of text
@author: janicelove
"""
import pyperclip #installation issues: https://stackoverflow.com/questions/41247045/how-to-install-pyperclip-to-anaconda
te... |
import os
import csv
election_csv = os.path.join("Resources/election_data.csv")
poll = {}
total_votes = 0
candidates = []
number_votes = []
vote_percent = []
winner_list = []
with open(election_csv, newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
#The ... |
#4. Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
#Правильное ре... |
#Задание №1
ten = 10
ball = int(input("Сколько в спортзале мячей? "))
name = input("Как тебя зовут? ")
print(type(ball))
if ball > 4 or ball==0:
print("%s пришел в спорзал , насчитал %d мячей."%(name,ball))
elif ball ==1:
print("%s пришел в спорзал , насчитал %d мяч."%(name,ball))
else:
print("%s пришел в ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.