text stringlengths 37 1.41M |
|---|
assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste memory appending actions that don't actually change any values
if values[box] == value:
... |
"""Hangouts emoticon to emoji converter."""
def replace_emoticons(string):
"""Replace emoticon words in string with corresponding emoji."""
return _replace_words(HANGOUTS_EMOTICONS_TO_EMOJI, string)
def _replace_words(replacements, string):
"""Replace words with corresponding values in replacements dict... |
# 딕셔너리, 키와 값을 쌍으로 가지는 자료형
# 관련된 정보를 연관 시키며 뮤테이블 객체
my_dict = {}
my_dict[1] = 'a'
my_dict['b'] = 2
my_dict['c'] = 'd'
my_dict['kk'] = 'seed'
my_dict
del my_dict['kk']
my_dict[1] = 'aaaa'
## dict.values()
# 특정 객체만 사용할 수 있는 함수
# 딕셔너리에서 값만 뽑아서 돌려줌
my_dict.values()
for d in my_dict.values():
print(d)
# keys와 dic... |
n = int(input())
for i in range(n):
print(i+1, end="")
# another solution
ans =''
for i in range(n):
ans += str(i+1)
print(ans) |
names_grades = [] # first we initial an empty list
# getting the first input which is the number of students to loop over
for _ in range(int(input())):
name = input() # inputting the name
score = float(input()) # inputting the score
# appending the current score to the empty list
names_grades.... |
def diagonalDifference(arr):
length = len(arr) # finding the length of the list
first = 0 # note that the 2 dimensions are equal
second = 0 # initial start with zero for both diagonals
for i in range(length):
first += arr[i][i]
second += arr[i][length - i - 1]
... |
"""Neural Network in Numpy"""
import numpy as np
class Activation:
def __init__(self):
self.activation_functions = [
"sigmoid",
"relu"
]
def relu(self, z):
return np.maximum(0, z)
def sigmoid(self, z):
return 1 / np.add(1, np.exp(-z))
def relu... |
def solution(n, jinsu):
a = ''
while n :
n, b = divmod(n, jinsu)
a += str(b)
return a[::-1]
n = 125
#십진수
ss = 3
#변환진수
print(solution(n, ss))
|
"""
File processing functions for managed files.
readFile - Read a file
writeFile - Write a file
safeGetState - Get the recovery state for a file
safeRecover - Initiate recovery for a file
safeReadFile - Read with recovery support
safeWriteFile - Write with recovery support
"""
from os import unlink, rename
from os.pa... |
import math
import datetime
def firstrun():
return "success"
def radius(C):
return C / (2 * math.pi)
def getlist(list):
size = len(list) - 1
first = "first"
last = "last"
result = "First:{0} Last:{1}".format(list[0],list[size])
return result
def getdate(date1,date2):
return (date1 ... |
# 1. We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each).
# Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without
# any loops.
def make_bric... |
string = input("Enter string:")
l = list(string.split())
l1 = l[::-1]
print(" ".join(l1))
|
import random
import os
ready_word = [] # Array with characters entered by the user, characters will be written only those that have not yet been named by the user and that are found in the hidden word
word = [] # Array with characters of the hidden word, this array will lose the character if the user entered it.
hist... |
def traverse(root):
output = ''
queue = [root]
visited = []
while len(queue) > 0:
# pop the next item in the queue
curr = queue.pop(0)
# add all unvisited neighbors to the queue
for neighbor in curr.neighbors:
if neighbor not in visited and neighbor not in ... |
def _preorderHelper(node):
output = ''
output += str(node.value) + ' '
if node.left != None:
output += _preorderHelper(node.left)
if node.right != None:
output += _preorderHelper(node.right)
return output
def preorder(node):
return _preorderHelper(node).strip()
def _inorder... |
class Library:
def __init__(self, list, name):
self.booksList = list
self.name = name
self.lendDict = {}
def displayBooks(self):
print(f"Books present in library:{self.name}")
for book in self.booksList:
print(book)
def lendBook(self, user, ... |
from unittest import TestCase
from validator import Validator
class TestValidator(TestCase):
def tests_invalid_id(self):
"""
Tests invalid ID
"""
test_data = {0: {"1D": "A123", "Gender": "F", "Age": "23", "Sales": "789", "BMI": "Normal", "Salary": "200",
... |
class Countdown(object):
def __init__(self, step):
self.step = step
def next(self):
if self.step == 0:
raise StopIteration
self.step -= 1
return self.step
def __iter__(self):
"""Returns iterator"""
return self
def countdown_example():
for e... |
money = int(input())
limit, percent, years = 700000, 1.071, 0
while money <= limit:
years += 1
money *= percent
# print(money)
print(years)
|
hello= "This again? come up with something else"
number= 56
num2= 67.3
print(hello)
print("hello")
print(num1, num2)
print(num1 + num2)
|
import numpy as np
from random import randint, random
import matplotlib.pyplot as mpl
from math import exp
# Problem 5, Triangle
"""
Consider a triangle and a point chosen within the triangle according to the uniform probability law. Let X be the distance from the point to the base of the triangle. Given the he... |
class HashEntry:
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return str(self.key) + ": " + str(self.value)
class HashMap:
def __init__(self, size=100):
self.TABLE_SIZE = size
# https://www.programiz.com/python-... |
#/usr/bin/python3
#
# Project 0 is a set of small functions to warm up with python3 and discrete math.
# [[[[1#]]]]
#[[[[0#]]]]
# I *John Robertson* have written all of this project myself, without any
# unauthorized assistance, and have followed the academic honor code.
#[[[[1#]]]]
import re
### M... |
import PuzzleHunt
def factorial(number):
x = 1
while number >= 1:
x *= number
number -= 1
return(x)
#print(factorial(12))
#When you're ready, uncomment the code below to test:
PuzzleHunt.test_factorial(factorial) |
def reverse_caesar_shift(message, shift):
secret = ""
message = message.upper()
for letter in message:
if letter == ' ':
secret += letter
else:
secret += chr((ord(letter) - ord('A') - shift) % 26 + ord('A'))
print(secret) |
def c_to_f(degC):
degF = (degC * 9/5) + 32
return degF
degC = float(input("Gimme a temperature in celsius: "))
if degC > -273.15:
print(c_to_f(degC))
else:
print("yous a foo")
|
if __name__ == "__main__":
list_ = [4, -1, 10, -1, 3, 3, -1, 8, 6, 9]
# предположим, что первый элемент в нашем списке минимальный
min_value_index = 0 # TODO чему равен индекс предполагаемого минимального элемента?
min_value = list_[min_value_index]
for i in range(len(list_)): # TODO как перебра... |
if __name__ == "__main__":
num1 = 12345
print(list(str(num1)))
# Конструкция для разбития числа на цифры
digits_list = [int(d) for d in str(num1)]
print(digits_list)
join_num = "".join([str(d) for d in digits_list])
print(int(join_num))
|
wind = int(input())
if 1 <= wind <= 4:
print("Слабый")
elif 5 <= wind <= 10:
print("Умеренный")
elif 11 <= wind <= 18:
print("Сильный")
else:
print("Ураганный")
|
list_ = list(range(9, -1, -1)) # TODO используйте отрицательный шаг, чтобы числа шли в обратном порядке
print(list_)
|
A = 5
B = 7
if A % 2 != 0 and B % 3 !=0: # ToDo напишите сюда условие проверки нечетности чисел А и B
print("'Числа А и B нечетные'")
|
if __name__ == "__main__":
rus_alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
#help(enumerate)
for index, value in enumerate(rus_alphabet, start=1): # TODO как за один раз получать пару индекс-значение?
print(index, value) # TODO как тогда должен выглядеть индекс?
|
tuple_ = (8, 9, -5, -3, 1, -10, 8, -10, -5, 0, 5, -4, 0, 10, -8, 1, 6, -6, 6, -9)
print(sum(tuple_))
print(len(tuple_))
print(sum(tuple_) / len(tuple_))
print(min(tuple_))
print(max(tuple_))
# TODO Каждое из значений печатать на отдельной строке
|
def get_sqrt(n, m):
return [x ** 2 for x in range(n, m+1) if x % 2 == 1]
if __name__ == "__main__":
print(get_sqrt(5, 13))
|
import pandas as pd
import numpy as np
from collections import defaultdict
df = pd.read_csv('data/survey_results_public.csv')
schema = pd.read_csv('data/survey_results_schema.csv')
def get_description(column_name, schema=schema):
'''
INPUT - schema - pandas dataframe with the schema of the developers survey
... |
if __name__ == "__main__":
a = 234.345
b = 45.698
print(f'{a:.6f} - {b:.6f}')
print(f'{a:.0f} - {b:.0f}')
print(f'{a:.1f} - {b:.1f}')
print(f'{a:.2f} - {b:.2f}')
print(f'{a:.3f} - {b:.3f}')
print(f'{a:.6e} - {b:.6e}')
print(f'{a:.6E} - {b:.6E}')
print(f'{a:.3f} - {b:.3f}')
p... |
if __name__ == '__main__':
while True:
try:
n, d = map(int, input().split())
mostrou = False
for i in range(d):
entrada = input().split()
data = entrada[0]
ocorre = list(map(int, entrada[1:]))
if ocorre.count... |
if __name__ == '__main__':
i = int (input())
for j in range(i):
veiculo = input()
resposta = ''
modelo_maior = 'ZZZ-9999'
modelo_menor = 'AAA-0000'
if len(veiculo) != 8:
resposta = 'FAILURE'
else:
for k in range(len(veiculo)):
... |
def check_movement(l, c):
global arena, n, m, f
if l >= n or l < 0 or c >= m or c < 0:
return False
elif arena[l][c] == "#":
return False
elif arena[line][column] == "*":
arena[line][column] = '.'
f += 1
return True
if __name__ == '__main__':
turn_right = {
... |
if __name__ == "__main__":
m = int(input())
a = int(input())
b = int(input())
c = m - (a + b)
maior = a if a > b else b
maior = c if c > maior else maior
print(maior) |
if __name__ == '__main__':
while True:
try:
n = int(input())
m, l = map(int, input().split())
marcos = []
leo = []
for i in range(m):
carta = list(map(int, input().split()))
marcos.append(carta)
for i in ... |
if __name__ == '__main__':
n = int(input())
for _ in range(n):
valores = input()
a = int(valores[0])
b = int(valores[2])
sinal = valores[1]
if a == b:
print(a * b)
else:
if sinal.islower():
print(a + b)
else:
... |
if __name__ == '__main__':
print("-"*39)
print("| decimal | octal | Hexadecimal |")
print("-"*39)
for i in range(8):
print(f"| {i} | {i} | {i} |")
for i in range(8, 10):
octal = i + 2
print(f"| {i} | {octal} | {i} |")
... |
def testa_triangulo(a, b, c):
if abs(b - c) >= a or a >= b + c:
return False
if abs(a - c) >= b or b >= a + c:
return False
if abs(b - a) >= c or c >= a + b:
return False
return True
if __name__ == '__main__':
lista = list(map(int, input().split()))
lista.sort()
tes... |
# -*- coding: utf-8 -*-
if __name__ == '__main__':
PI = 3.14159
raio = float(input())
volume = (4/3) * PI * (raio ** 3)
print(f"VOLUME = {volume:.3f}")
|
if __name__ == '__main__':
repete = int (input())
texto = ''
for i in range(repete):
texto += 'Ho'
if i == repete - 1:
texto += '!'
else:
texto += ' '
print(texto)
|
if __name__ == '__main__':
while True:
frase = input()
if frase == "*":
break
frase = frase.lower()
palavras = frase.split()
i = palavras[0][0]
correct = True
for p in palavras:
if p[0] != i:
correct = False
... |
if __name__ == '__main__':
c = int(input())
for i in range(c):
hora, minuto, caso = map(int, input().split())
if hora < 10:
horario = f'0{hora}'
else:
horario = str(hora)
if minuto < 10:
minutos = f'0{minuto}'
else:
minutos ... |
#!/usr/bin/env python3
from pwn import *
# Before creating the script:
# The program gives you the address of a buffer that currently holds the value '9447',
# as well as another buffer than we can input a format string into. So we want to use
# this to alter the value stored in the buffer such that it passes a call ... |
from __future__ import absolute_import
import unittest
"""
Write a method to replace all spaces in a string with '%20'.
2017-01-15 Michael Palarya
"""
def urlify1(s, length):
"""
pythonic solution
"""
return "%20".join(s.split())
def urlify2(s, length):
"""
simple solution by creating a ne... |
from abc import ABC, abstractmethod
from typing import Tuple
import gym
import numpy as np
from gym import spaces, logger
class Player(ABC):
""" Class used for evaluating the game """
def __init__(self, env, name='Player'):
self.name = name
self.env = env
@abstractmethod
def get_nex... |
#!/bin/usr/python
# -*- coding: utf-8 -*-
import unittest
import funciones_bd
class TestStringMethods(unittest.TestCase):
def test_existe_ciudades(self):
""" Test que comprueba si hay ciudades disponibles. """
total = funciones_bd.cuentaCiudades()
self.assertNotEqual(total, 0)
def t... |
#!/usr/bin/env python
input = "1321131112"
from itertools import groupby
def look_and_say(input_string, num_iterations):
for i in xrange(num_iterations):
input_string = ''.join([str(len(list(g))) + str(k) for k, g in groupby(input_string)])
return input_string
print len(look_and_say(input, 50))
|
def is_int(data):
if type(data) == int:
print("este numero es int ", end="")
#return True
elif type(data) == float:
print("este numero es float", end="")
#return False
else:
print("este un string")
return "no es int ni float ni string"
print(is_int(5))... |
def main():
import random
random_num = random.randint(1, 3)
if random_num == 1:
answer = "Influenza"
elif random_num == 2:
answer = "Epilepsy"
else:
answer = "Chicken Pox"
print("What topic? {}".format(answer))
main()
|
class Multiply():
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
z = x * y
return z
def backprop(self, dz):
dx = dz * self.y
dy = dz * self.x
return dx, dy
class Add():
def __init__(self):
self.x = None
self.y = None
... |
#https://www.codechef.com/AUG19B/problems/DSTAPLS
test = int(input())
while test:
n, k = input().split()
n = int(n)
k = int(k)
ans = ""
ans = "NO" if n%(k*k) == 0 else "YES";
print(ans)
test -= 1
|
import math
def fuel_required(mass):
floor = mass / 3
return math.floor(floor) - 2
def fuel_required_recursive(mass):
floor = mass / 3
fuel = math.floor(floor) - 2
if fuel <= 0:
return 0
return fuel + fuel_required_recursive(fuel)
if __name__ == '__main__':
part_1 = 0
part_... |
#!/usr/bin/python3
"""This executable tests the neural network on all symbols
specified in training_set.json and prints the percentage of
correct NN's answers"""
import os
import json
import ocr.settings
import ocr.basic_nn.tools
REPETITIONS = 5
def correct_fraction():
"""A function which prints and returns th... |
status = True
while status:
answer = input("Say something: ")
if answer == "I love you aunty, I have to go now":
status = False
print("ok. Goodbye.")
elif answer == answer.lower():
print("WHAT? SPEAK UP!")
elif answer == answer.upper():
print("YOU ARE VERY RUDE!")
el... |
# -*- coding: utf-8 -*-
"""
Get the cartesian indices of input 1-D arrays
Similar to the Julia CartesianIndices
https://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays
"""
import numpy as np
def cartesian(*arrays, order='F'):
"""
-i- arrays : list of array-l... |
# coding: utf-8
# In[11]:
import pandas as pd
#poke=pd.read_csv('D:\Data projects\pandas\pokemon_data.csv')
#print(poke.head(10))
#print(poke.tail(10))
#poke_excel=pd.read_excel('D:\Data projects\pandas\pokemon_data.xlsx')
poke_txt=pd.read_csv('D:\Data projects\pandas\pokemon_data.txt', delimiter='\t')
# In[13]... |
class ProductParser:
"""
This class contains methods that will analyse products that API has returned
"""
@staticmethod
def separate_brands(brands):
"""
If more than 1 brand, separate each brand and returns the first one
"""
if "," in brands:
brands_list ... |
# Buzzer or LED intensifies as object appraoches
import RPi.GPIO as GPIO
from time import sleep
import datetime
import math
# Define the pins we'll use
LED = 32
BUZZER = 33
DISTTRIGGER = 10
DISTECHO = 8
# Declare variables used in getting the distance from the sensor
# how long the soundwave will be sent for
triggerP... |
class Board():
def __init__(self):
self.sideLength = 16;
self.boundaries = [[[0 for i in range(4)] for i in range(self.sideLength)] for i in range(self.sideLength)]
self.mouseLocation = [0,0]
#boundaries[x][y][direction]
for i in range(16):
# mark outside boundar... |
list1=[1,2,3,4,5,6,7,8]
list2=["a","b","c"."d","e"]
for each in list1:
list2.append((each))
print(list2)
|
# Create a decorator that makes a function run with a delay of n sec (n should be the decorator parameter).
# Create also a couple of simple functions to test the decorator and decorate them accordingly.
# Hint 1: use the "extended" decorator-writing pattern:
# def decorator(arg1, arg2, ...):
# def real_decorator(f... |
#prg to remove stopwords
noise_list = [ "is", "a", " this",".","of","in","an","the","as","but","was",";",":","were","am","are","I","at","on","under","over","it"]
def remove_noise(input_text):
words=input_text.split()
noise_free_words=[word for word in words if word not in noise_list]
noise_free_text = " "... |
# Une classe c'est un plan
# Un objet c'est une voiture faites à partir de ce plan
class Plan(): # 0
pass # 1 {}
# 0
class Vehicule(object):
speed = 0
def drive(self):
pass
def get_speed(self):
return self.speed
vec = Vehicule()
vec.drive() # drive(vec)
class Car(Vehicule):
... |
from tkinter import*
from tkinter import font
def btnClick(numbers):
global operator
operator=operator + str(numbers)
text_Input.set(operator)
#def pangkat():
#global operator
#operator = operator + str(numbers**2)
#text_Input.set(operator)
def btnClearDisplay():
global oper... |
board = []
turn = 0
for i in range(3):
z = ["X", "X", "X"]
board.append(z)
def print_board(board):
for b in board:
print (" ".join(b))
print_board(board)
#Player 0 & 1:
def show_board(player):
exception = True
while exception:
try:
type_row = int(input("***P... |
votosegunsuedad=int(input("determine la edad: "))
#proceso
if votosegunsuedad >=18:
print ("si podra votar para las eleciones: ")
else:
print ("no podra votar para las elecciones: ")
|
#!/usr/bin/env python3
"""Sort clipboard using subprocess module."""
import subprocess
def get_clipboard():
"""Get the clipboard from the pbpaste command."""
paste = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
paste.wait()
data = paste.stdout.read()
return data.decode()
def set_clip... |
#!/usr/bin/env python3
"""Two Sums.
Given an array of integers, return indices of the two
numbers such that they add up to a specific target.
You may assume that each input would have exactly
one solution, and you may not use the same element twice.
https://leetcode.com/problems/two-sum/description/
"""
def two_s... |
#!/usr/bin/env python3
"""Dictonary Utils.
Dictionary Utilities.
"""
from functools import reduce
from operator import mul, add, sub
def create_power_dict(length=1):
return {x: x**x for x in range(1, length+1)}
def operate(func, *dicts):
"""Apply func to values of *dicts and return the result."""
res... |
#!/usr/bin/env python3
"""Time Zone - Resolve what time is it?
Find out what time of a given location.
"""
import os
import pytz
from datetime import datetime
from timezonefinder import TimezoneFinder
from pygeocoder import Geocoder
from collections import namedtuple
TimeZoneResult = namedtuple('TimeZoneResult', ['... |
#!/usr/bin/env python3
"""Wrapper for textwrap module.
Working with the textwrap module and creating a wrapper that includes
all functionality while keeping the original text.
"""
from textwrap import TextWrapper, dedent, indent
GLOBAL_LEN = 72
class MyTextWrapper:
"""My wrapper for the textwrap.TextWrapper c... |
#!/usr/bin/env python3
"""Demo of aiohttp package."""
import aiohttp
import asyncio
async def fetch(session, url):
"""Fetch the url."""
async with session.get(url) as response:
return await response.text(encoding='utf-8')
async def task(url):
"""Async task function."""
print(f'{url} star... |
#!/usr/bin/env python3
"""Digital Mistakes kata.
Correct the mistakes of the character recognition software.
Share this kata:
Character recognition software is widely used to digitize printed texts.
Thus the texts can be edited, searched and stored on a computer.
When documents (especially pretty old ones... |
#!/usr/bin/env python3
"""Find all files matching a pattern."""
import fnmatch
from pathlib import Path
PATTERN = '*.py'
HOME_DIR = Path.home()
SEARCH_DRIVE = HOME_DIR
matches = 0
def search(path, pattern):
"""Search path with pattern.
Print the files found in the directory first,
then search any subd... |
#!/usr/bin/env python3
"""Reckon - simple substitution cipher."""
import os
from base64 import b64decode, b64encode
from string import ascii_letters, punctuation, digits
from hashlib import sha512
chars = tuple(ch for ch in (*ascii_letters, *punctuation, *digits, ' ',))
def hash_() -> str:
"""Create has from ... |
#!/usr/bin/env python3
"""SQLite3 database creation."""
import sys
import sqlite3
from contextlib import contextmanager
@contextmanager
def create_db(name='db'):
"""Create database and yield cursor using contextmanager."""
try:
conn = sqlite3.connect(f'{name}.db')
cursor = conn.cursor()
... |
#!/usr/bin/env python3
"""What next?
Script that chooses a random action from a set of actions and suggests
an action to the user.
"""
import random
class WhatNextAction:
"""What Next Action Class."""
def __init__(self, *args, **kwargs):
"""Create a list of common actions and create a random acti... |
#!/usr/bin/env python3
"""Leap Year tester.
Given a year, determine if the it's a leap year.
"""
import sys
from datetime import date
def leap_year(year):
"""Determine if a year is a leap year."""
try:
d = date(year, 2, 29)
except ValueError:
return f"{year} is not a leap year."
retu... |
#!/usr/bin/env python3
"""Python Http server ("Hello, World!").
Fun with sockets and multiprocessing.
source: https://www.youtube.com/watch?v=MRToT6vVfQE
"""
import socket
import multiprocessing
def handle(connection, client_address):
"""Handle the connection."""
print('handling', client_address)
conn... |
class ASList:
"""
Array-set List: A wrapper of list and set.
by HermesPasser
"""
def __init__(self, values=[], unique=False):
self._is_unique = unique
self._list = set() if unique else []
self.update(values)
def __str__(self):
return str(self._list)
def __len__(self):
return len(self._list)
d... |
#crtDirs moudel
import os
def creatinDirs():
print("* * * CREATING FOLDERS IF NOT EXISTS. * * *\n")
resultDirs = ["result/", "source/", "result/XXLarge/", "result/XLarge/", "result/Large/", "result/Normal/", "result/Small/"]
for k in resultDirs:
if os.path.exists(k) == True:
print(... |
def ProblemFourA(m):
p=list(m)
q=list(m)
x=len(p)-1
i=0
while i<len(p):
p[i]=q[x-i]
i+=1
s=''.join(p)
print(s)
def InsertionSort(l):
for i in range(1,len(l)):
val = l[i]
target = i
while target>0 and l[target-1]>val:
... |
"""
Moduł służący do operacji na plikach.
"""
import functions
class Files:
"""Klasa zawierająca metody do operacji na plikach"""
def __init__(self):
Files.filesConnectionList = []
Files.filesConnectionWeight = []
FilesConnectionList = []
FilesConnectionWeight = []
@classmethod... |
import sqlite3
# make_entry(cursor, temperature, light_level, pressure, humidity, date = None)
# cursor - SQLite3 cursor object
# temperature - temperature reading as float
# light_level - light reading as float
# pressure - pressure reading as float
# humidity - humidity reading as flo... |
import numpy as np
from LinearOptimization.linear_program import LinearProgram
def create_tableau(lp: LinearProgram):
"""
Create simplex tableau from normalized linear program.
"""
# get dimensions and construct A_base
m, n = lp.constraints.shape
# cut out base values from constraint matrix A... |
import csv
import sqlite3
conn = sqlite3.connect('/home/iwk/src/worlddata-python-example/data/import/world-gdp.db')
c = conn.cursor()
with open("/home/iwk/src/worlddata-python-example/data/import/data.countries.csv", 'r', encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
... |
def app():
import streamlit as st
import zipfile
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.impute import KNNImputer
import numpy as np
from sklearn.preprocessing import LabelEncoder
uploaded_file = st.file_uploader('Upload file' , type = "csv")
sh... |
import re
""" La forma utilizando la in-built function eval con try-excep
'la foma pythonista' pero sin expresiones regulares
"""
class MyArray2():
def __init__(self, entrada):
self.entrada = entrada
def operation(self):
print(self._valid())
def _valid(self):
try:
... |
class complex :
def __init__(self, Re, Im):
self.__Re = Re
self.__Im = Im
def __add__(self, obj):
return complex(self.__Re+obj.__Re, self.__Im+obj.__Im)
def __sub__(self, obj):
return complex(self.__Re-obj.__Re, self.__Im-obj.__Im)
def __mul__(self, obj):
retu... |
"""Python file equivalent to Continuum-supplied demo notebook '1 - Diagonal Plot.ipynb'"""
import numpy as np
from bokeh.plotting import figure, output_notebook, output_file, show
#output_notebook()
# # First, the simple example from Bokeh's Getting Started documentation:
# x = [1, 2, 3, 4, 5]
# y = [6, 7, 2, 4, 5]
#
... |
"""
列表的基本使用
一、列表(list类型)
1、在python是用中括号表示(和其他语言中的数组看起来差不多)
2、例子:[11,22,33,‘python’]
3、列表中可以存储任何类型的数据
4、空字符串 s1=‘’ <class 'str'>
5、空列表 li = [] <class 'list'>
6、列表和字符串(后续会讲的元组,有一个公共操作):切片和索引取值
"""
li = [11, 1.3, True, '788', [11, 22]]
print(li)
s1 = ''
li = []
print(type(s1), type(li))
'''
二、索引(下标)
1、列表里的每个数... |
a = 3
b = 4
c = a + b
c = 5
print(c)
list1 = [{1: 18510929499}, {2: 13212314321}]
list1 = [{"id": 1, "mobile": 18510929499}, {"id": 2, "mobile": 13212314321}]
for a in range(len(list1)):
print(list1[a]['mobile'])
|
"""
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
"""
def game():
my_hp = 1000
my_power = 200
your_hp = 1000
your_power = 199
round = 0
while True:
my_hp=my_hp-... |
from typing import List
class Text:
"""
PygameのINPUT、EDITINGイベントで使うクラス
カーソル操作や文字列処理に使う
"""
def __init__(self) -> None:
self.text = ["|"] # 入力されたテキストを格納していく変数
self.editing: List[str] = [] # 全角の文字編集中(変換前)の文字を格納するための変数
self.is_editing = False # 編集中文字列の有無(全角入力時に... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.