text stringlengths 37 1.41M |
|---|
imiona = ['Artur', 'Barbara', 'Czesław']
print(imiona)
indeks = int(input('Proszę podać indeks imienia do skasowania: '))
indeks_min = -1 * len(imiona)
indeks_max = len(imiona) -1
if indeks_min <= indeks <= indeks_max :
print('Kasowane imię to:', imiona.pop(indeks))
else:
print('Nie ma elementu o takim ind... |
while True:
wyraz = input('Wpisz dowolny wyraz: ')
if ' ' in wyraz:
print('Wpisano spację')
continue
ile_znakow = len(wyraz)
komunikat = 'Wyraz "{}" ma {} znaków.\n' \
'Wyraz ten zaczyna się na literę "{}"'.format(wyraz, ile_znakow, wyraz[0])
print(komunikat)
|
import numpy
import streamlit as sl
"""# Transportation Problem"""
@sl.cache
def random_problem(size: int):
"""Random Transportation Problem to solve"""
a = numpy.random.rand(size)
a /= a.sum()
b = numpy.random.rand(size)
b /= b.sum()
c = numpy.random.rand(size, size)
c /= c.sum()
ret... |
#!/usr/bin/env python3
"""
Laszlo Szathmary, 2014 (jabba.laci@gmail.com)
Print just the name of the current directory.
For instance, if you are in "/home/students/solo",
then this script will print just "solo".
The output is also copied to the clipboard.
Usage: here
Last update: 2017-01-08 (yyyy-mm-dd)
"""
import... |
# List of Pies
pies = ["Pecan", "Apple Crisp","Bean", "Bannoffee","Black Bun", "Blueberry", "Buko","Burek", "Tamale","Steak"]
greeting = ("Welcome to the House of Pies! Here are our pies: --------------------------------------------------------------------- \n(1) Pecan, (2) Apple Crisp, (3) Bean, (4) Banoffee, (5)... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
class Solution(object):
def merge_sort(self, nums):
if len(nums)<2:#當nums於2時
return nums#回傳nums
else:
left=nums[:len(nums)//2] #左邊數值
right=nums[len(nums)//2:]#右側數值
return merge(mergeSort(left), mergeSor... |
myFile = open("spam2.txt")
total = 0
count = 0
average = 0
for line in myFile:
if line.find("From ") >= 0:
startEmail = line.find(" ")
endEmail = line.find(" ", startEmail + 1)
fromEmail = line[startEmail:endEmail]
if line.find("To") >= 0:
startEmail = line.find(" ")
... |
import random
#随机数
secrect=random.randint(1,10)
#自定义函数 用于返回最大值
def getMaxVal(val1,val2):
if(val1>=val2):
return val1
else:
return val2
print('-------------测试程序---------------')
maxtimes=8
nowtime=0
while nowtime<8:
temp=input("请输入数字:")
guess=int(temp)
if guess==secrect:
print("大叔大... |
import numpy as np
import matplotlib.pyplot as plt
#read the data
data = np.genfromtxt('kc_house_data.csv',delimiter=",") # read the data
data =np.delete(data,0,axis=0)
X = data[:, 19].reshape(-1,1) # -1 tells numpy to figure out the dimension by itself
ones = np.ones([X.shape[0], 1]) # create a array containing onl... |
from math import floor
num = float(input("Digite um numero: "))
inte = floor(num)
print("O numero {} tem a parte inteira {}".format(num, inte))
|
# Python program showing
# use of __call__() method
class MyDecorator:
def __init__(self, function):
print("__init__")
self.function = function
@staticmethod
def __call__(self):
print("__call__")
# We can add some code
# before function call
self.function... |
# @cache(times=3)
# def some_function():
# pass
# Would give out cached value up to times number only. Example:
import functools
from typing import Callable
def cache(times: int) -> Callable:
def cache_decorator(func: Callable) -> Callable:
"""
Accepts a functions
Returns cashed func... |
"""
Write a function that accepts another function as an argument. Then it
should return such a function, so the every call to initial one
should be cached.
def func(a, b):
return (a ** b) ** 2
cache_func = cache(func)
some = 100, 200
val_1 = cache_func(*some)
val_2 = cache_func(*some)
assert val_1 is val_2
"""
imp... |
"""
Написать декоратор instances_counter, который применяется к любому классу
и добавляет ему 2 метода:
get_created_instances - возвращает количество созданых экземпляров класса
reset_instances_counter - сбросить счетчик экземпляров,
возвращает значение до сброса
Имя декоратора и методов не менять
Ниже пример использов... |
#Accept a file name from user and print extension of that.
a=input("enter the filename")
s=a.split(".")
j="."
print(j+s[-1])
|
import csv
with open("file.txt","r")as f:
reader=csv.reader(f)
for row in reader:
print(row) |
#Fibonacci series of N terms .
n=int(input("enter the number"))
coun=1
n1=0
n2=1
sum=0
print("fibanacci series:\n",end='')
while(coun<=n):
print(sum,end="\n")
coun+=1
n1=n2
n2=sum
sum=n1+n2
|
#Display first and last color.
ls=[]
print("enter the colors")
b=input("").split(",")
ls.append(b)
print(b[0])
print(b[-1]) |
people = 50
cars = 30
trucks = 30
# if there are more cars than people, print the line below
if cars > people:
print(">>>> first if:", cars, people) # DEBUGGING
print("We should take the cars.")
# if there are not more cars than people but less, print the line below
elif cars < people:
print(">... |
from sys import exit
# Make the start of the game
def start():
print("You wake up half naked on the ground.")
print("Around you are massive trees surrounded by magical blue mist.")
print("Far down the hill in front, you see a little village filled with blue skinned people.")
print("You see a... |
#!/usr/bin/env python3
from vehicle import vehicle
from abc import ABC,abstractmethod
class bike(vehicle):
def __init__(self,name,color,wheel):
super().__init__(name,color,wheel)
def wheelie(length):
for i in range(0,length):
print("WEEE!")
def makeSound():
print("BRRRI... |
# ###### 1 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# sm1 = int(input("enter marks of first subject :"))
# sm2 = int(input("enter marks of Second subject :"))
# sm3 = int(input("enter marks of third subject :"))
# sm4 = int(input("enter marks of forth subject :"))
# sm5 = int(input("enter marks of fivfth subje... |
"""CPU functionality."""
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.ram = [0] * 256
self.register = [0] * 8
self.pc = 0
self.sp = 7
self.halt = False
self.fl = 0b00000000
self.LDI = 0b1000001... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def fiat_shamir():
#Inicialización
p=int(raw_input("\033[36m" +"Introduce el número primo secreto P: "+'\033[0;m'))
q=int(raw_input("\033[36m" +"Introduce el número primo secreto Q: "+'\033[0;m'))
N=p*q
print "\033[35m" +"N="+str(N) +'\033[0;m'
#Ide... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from random import sample
from exponenciacion_rapida import *
def test_lehman_peralta(p):
#comprobación de los primos pequeños:
primos=[2,3,5,7,11]
print "\033[35m" +"Test de Lehman-Peralta para " + str(p) + ": "+'\033[0;m'
print "\033[35m" +"1.... |
from datetime import datetime
def fib(n):
if (n <= 2):
return 1
else:
return fib(n - 1) + fib(n - 2)
def run(n):
start_time = datetime.now()
res = fib(n)
print("Calculating fib(%d) = %d took %s seconds" % (n, res, datetime.now() - start_time))
if __name__ == '__main__':
run... |
def get_all_powers_of_two(x):
res = []
power_of_two = 1
while power_of_two <= x:
if power_of_two & x != 0:
res.append(power_of_two)
power_of_two = power_of_two << 1
return res
def run_tests():
assert get_all_powers_of_two(330) == [2, 8, 64, 256]
assert get_all_power... |
# Related blog post - https://algoritmim.co.il/2019/11/23/senate-evacuation/
import string
def remove_senators(senators_counter, senators_to_evict):
for senator in senators_to_evict:
senators_counter[senator] -= 1
if senators_counter[senator] == 0:
senators_counter.pop(senator)
def fo... |
def fibsum(N):
if N == 0:
return 0
previous = 0
current = 1
while current <= N:
tmp = current
current = current + previous
previous = tmp
########## here current >= A
count = 0
remain = N
while remain >= previous:
count += 1
remain -= pr... |
COLORS = ["red", "blue", "green", "purple", "orange", "yellow"]
COLORS_DICT = {color[0]: color for color in COLORS}
CODE_LENGTH = 2
TOTAL_ROUNDS = 12
USER_INPUT_PROMPT = "Please enter your next guess. (r=red b=blue g=green p=purple o=orange y=yellow\n"
USER_SCORE = "Bul: {}, Pgia: {}\n"
USER_WON = "You Win!"
USER_LOST... |
import math
# find sum of an array/list. Diffculty: Easy
def sum(A):
if not A:
return 0
if len(A)==1:
return A[0]
if len(A)>1:
return A[0]+sum(A[1:])
# print(sum([1,2,3]))
# find Minimum of an array. Diffculty: Easy
def basicMin(A, currMin):
if not A:
return currMin
... |
class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
left, right = 0, len(A)-1
while left<=right:
if A[left]>target:
return left
elif A[right]<target:
... |
# Definition for a point
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution:
# @param points, a list of Points
# @return an integer
def maxPoints(self, points):
maxNum=0
for i in range(len(points)):
map, same, ... |
"""This module contains examples of stream_func where f_type
is 'element' and stream_func has a list of multiple input streams,
a single output stream, and the operation is stateless. These
examples must have a LIST of input streams and not a single
input stream.
The functions on static Python data structures are of t... |
"""This module contains examples of stream_func where f_type
is 'element' and stream_func has a list of multiple input streams,
a single output stream, and the operation is stateless. These
examples must have a LIST of input streams and not a single
input stream.
The functions on static Python data structures are of t... |
"""This module contains examples of stream_func where f_type
is 'element' and stream_func has a single input stream, a
single output stream, and the operation is stateless.
The functions on static Python data structures are of the form:
element -> element
"""
if __name__ == '__main__':
if __package__ is None:... |
"""This module contains examples of stream_func where f_type
is 'element' and stream_func has a single input stream, a
single output stream, and the operation is stateless.
The functions on static Python data structures are of the form:
element -> element
"""
if __name__ == '__main__':
if __package__ is None:... |
#!/usr/bin/python3
print("different functions of cat command")
print("""1) for show the content of file :
2) for cat file1 > file2 :
3) for cat file1 >> file2 :
4) for display $ at the end of every line {cat -E}: """)
ch=int(input("enter your choice"))
if ch == 1:
first=input("enter file name")
con=open(first,"r")
p... |
## all funciton will take a list of integers as input
def rsum(ints):
if len(ints) == 1:
return ints[0]
else:
return ints[0] + rsum(ints[1:])
def rmax(list):
if len(list) == 1:
return list[0]
else:
m = rmax(list[1:])
return m if m > list[0] else list[0]
def se... |
# Functions for reading tables and databases
import glob
from database import *
# a table is a dict of {str:list of str}.
# The keys are column names and the values are the values
# in the column, from top row to bottom row.
# A database is a dict of {str:table},
# where the keys are table names and values... |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Funcion de lectura de archivos de Tablero
#
# @param num = numero de archivo a leer
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
listaIndices = []
def read_file(Board, num):
... |
import unittest
# this version does not keep the order
def deduplicate_v1(duplicated_list):
return list(set(duplicated_list))
# my first approach for keeping the order. Complexity O(n ^ 2)
def deduplicate_v2(duplicated_list):
result = list()
for element in duplicated_list:
if element not in result... |
#assignment
#assume that i have a list, inside a list we have show how many times a number exist in a list.
name=['aman', 'preet', 'aman', 'preet', 'deep', 'aman', 'deep', 'deep', 'deep', 'aman', 'aman']
print(name)
print(type(name))
#to print aman
print("the name aman is founded in a given list",name.co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# transform string to datetime
import datetime
string = '2017/09/26 11:39:00'
d = '2017-09-26'
str2datetime = datetime.datetime.strptime(string, '%Y/%m/%d %H:%M:%S').date()
str2date1 = datetime.datetime.strptime(d, '%Y-%m-%d')
str2date2 = datetime.datetime.strptime(d, '... |
"""
Movie Class
Creates a movie object with a youtube trailer, poster art and title
"""
class Movie(object):
def __init__(self, title, poster_image_url, trailer_youtube_url):
"""
Movie constructor
Parameters
----------
title : string
title of the movie
... |
import random
import charSet as cs
class Word_Based_Password:
def __init__(self):
self.password = "PROMPT: Select options!"
def randomize_case(self, letter):
if letter == " ":
letter = ""
elif letter != " ":
randomChoice = random.choice('abc')
if... |
class Value_Action():
# GET VALUE
def get_value(self, value, whereFrom):
value = whereFrom.get()
return value
# +/- BUTTON METHODS
def increment(self, value, place):
value = self.get_value(value, place)
value = int(value)
value += 1
value = str(value)
... |
#add 5 6 and 7 to the Tuple
my_tuple = (1,2,3)
my_tuple = my_tuple[:3] + (5,6,7)
print(my_tuple)
|
import pandas as pd
from sklearn import preprocessing
import numpy as np
history_days = 30 # Predict a month into future
def csv_to_dataset(csv_file_path):
file_data = pd.read_csv(csv_file_path)
file_data = file_data.iloc[::-1] # Reverse order, most recent values last, want to be predicting into future, not past
... |
'''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
... |
import csv
# Write file.
with open('file.csv', 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=';')
csv_writer.writerow(['titile1', 'titile2', 'titile3', 'titile4', 'titile5'])
csv_writer.writerow(['column1', 'column2', 'column3', 'column4', 'column5'])
# Read file.
with open... |
"""
A text based clone of 2048
Made by Chendi
"""
import random
import utils
import enum
import collections
# because typos
CURRENT_GAME = "current game"
class Cell:
"""represents a cell in a board"""
def __init__(self, value=0):
self.length = 1
self.value = value
self.has_merged = F... |
nama = []
TL = []
nama = [item for item in input("Nama : ").split()]
TL = [item for item in input("Tempat Tanggal Lahir : ").split()]
jumlahKataNama = len(nama) - 1
jumlahkataTL = len(TL) -1
sisa_nama = ""
for i in range(0,jumlahKataNama):
sisa_nama = sisa_nama + nama[i] + " "
tanggal = ""
for i in range(jumlahkat... |
import psycopg2
def connect_conn():
"""Establish connection to database and return connection object."""
db = 'bgpuyxgj'
user = 'bgpuyxgj'
password = 'password' # Don't commit!
host = 'raja.db.elephantsql.com'
conn = psycopg2.connect(dbname=db, user=user,
password... |
# Q5:. A cryptarithmetic puzzle
def Q5():
def isPZCZ(n):
"""Predicate to check that n, the input number,
has the format PZCZ, i.e. the 2nd and 4th digits are equal.
n: input number, assumed to be 4 digits
Returns True if n has the format PZCZ, False otherwise."""
# convert to... |
graph={
1:[2,3],
2:[1,4,5,7],
3:[1,5,9],
4:[2,6],
5:[2,3,7,8],
6:[4],
7:[5,2],
8:[5],
9:[3],
}
def DFS(graph, root):
visited = []
stack = [root]
while stack:
n = stack.pop()
for i in graph[n]:
if i not in visited:
stack.append(i)
i... |
#Given an array of integers, find the first missing positive integer
#in linear time and constant space. In other words,
#find the lowest positive integer that does not exist in the array.
#The array can contain duplicates and negative numbers as well.
#For example, the input [3, 4, -1, 1] should give 2. The inp... |
##-----------------------------------------------------------------
##Real Python examples
##To check Using SMTP_SSL()
'''
import smtplib,ssl
smtp_server='smtp.gmail.com'
port=465
sender='--Enter your email address--'
password=input('Enter your password and press enter : ')
context=ssl.create_defau... |
from Tkinter import*
root =Tk()
frame1=Frame(root, width = 500, height = 400)
frame1.pack()
Label(frame1,text="Validador de Cedula", fg="Red", font=("Arial",18)).place(x=135,y=30)
def is_valid_date(action, char, text):
# Solo chequear cuando se añade un carácter.
if action != "1":
return True
re... |
#coding=utf-8
class Solution:
def quick_sort(self, lists, left, right):
# 快速排序
if left >= right:
return lists
key = lists[left]
low = left
high = right
print "before One iteration key:",key,lists
while left < right:
while left < ... |
#!/usr/bin/env python3
"""Program to get internet IP info."""
import json
import requests
import argparse
def getipinfo(website):
"""Get ip info from website."""
inforequest = requests.get(website)
infobyte = inforequest.content
return json.loads(infobyte)
def printinfo(ipinfo):
"""Print out t... |
#This is a basic script for practicing the syntax for different loops in python
import sys
class TestClass:
i = 1
def __init__(self):
self.i = 10000
def set_i(self, j):
print(j)
temp = self.i
self.i = j
print(temp)
return(temp)
if (len(sys.argv) < 2):
... |
# Uses python3
import random
def lcm_naive(a, b):
for l in range(1, a*b + 1):
if l % a == 0 and l % b == 0:
return l
return a*b
def gcd(a, b):
if b == 0:
return a
rem = a % b
return gcd(b, rem)
def lcm_fast(a, b):
return int((a * b) / gcd(a, b))
def test_solutio... |
def binary_tree_depth_order(tree: BinaryTreeNode) -> List[List[int]]:
from collections import deque
traversal = list()
if tree is None:
return traversal
queue = deque()
queue.append(tree)
while queue:
curr_level, queueSize = list(), len(queue)
for i in range(queueSize):
... |
def multiply(num1, num2):
result = [0] * (len(num1) + len(num2))
sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1
num1[0], num2[0] = abs(num1[0]), abs(num2[0])
for i in reversed(range(len(num2))):
for j in reversed(range(len(num1))):
result[i + j + 1] += num1[j] * num2[i]
for i... |
def is_valid_sudoku(partial_assignment):
#check 9 3x3 subgrids
for rOffset in range(0, 7, 3):
for cOffset in range(0, 7, 3):
appeared = [False] * 9
for r in range(3):
for c in range(3):
num = partial_assignment[r + rOffset][c + cOffset]
... |
def snake_string(s):
lst = []
for i in range(1, len(s), 4):
lst.append(s[i])
for i in range(0, len(s), 2):
lst.append(s[i])
for i in range(3, len(s), 4):
lst.append(s[i])
return ''.join(lst)
print(snake_string("Hello World!"))
|
import os
import random
from hangman_art import logo,stages
from hangman_words import word_list
print(logo)
chosen_word= random.choice(word_list)
display = []
lives = 6
found = False
for _ in chosen_word:
display.append("-")
print(display)
while "".join(display) != chosen_word and lives >= 0:
guess= input(... |
import numpy as np
# Create array manually
a = np.array([0, 2, 4, 6])
# Get dimension of array
print(a.ndim) #should print 1
#####
# Get shape of array
print(a.shape) #should print (4,) meaning 4 dimensions on 0th axis
# Get length of array
print(len(a)) #should print 4
# Create multidimesional arrays manually
b =... |
import argparse
argument_pass = argparse.ArgumentParser()
argument_pass.add_argument("-n", "--name", required=True, help="name of the user is required!")
# -n is the shorthand for --name where either may be used in the cmd line
# help string would give additional info in ther terminal when executed with the --help f... |
year = input('Введите год\n')
if year.isdigit():
if int(year[-2:]) % 4 == 0:
print('Год високосный')
else:
print('Год не високосный')
else:
print('Введите год ЦИФРАМИ') |
import vectorlength
import lineslope
import degrees
import vector
import calculator
import squareroot
# if function.
def t_if():
if choice == "calculator":
calculator.cal()
elif choice == "square root":
squareroot.sqr()
elif choice == "vector length":
vectorlength.length_vector()
elif choice == ... |
print("Enter n and m:")
try:
string_n, m = input().split()
if string_n.isdigit() and m.isdigit():
sum, quantity = 0, int(m)
if len(string_n) > quantity:
for digit in list(string_n[:len(string_n) - int(quantity) - 1:-1]):
sum += int(digit)
print("The sum of... |
students = [
{
"name": "Mark",
"age": 15
},
{
"name": "Emily",
"age": 14
},
{
"name": "Joseph",
"age": 15
}
]
def add_student(name, age=15):
new_student = {
"name": name,
"age": age
}
students.append(new_student)
pri... |
#!/usr/bin/python
"""
Multiprocessing variant of sudoku1.py. Launches one process per option on the
first '0' found.
Lots of potential optimizations available from here.
by Jason Price
"""
from __future__ import print_function
import multiprocessing
import random
import sys
# import time
# 06090010030820000000900... |
#!/usr/bin/env python
# this script will turn the Passive Buzzer on and then off
import RPi.GPIO as GPIO
import time
# breadboard setup
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# assign pin number for Passive Buzzer; pin 32 = GPIO 12
buzz_pin = 32
# set Passive Buaaer pin's mode as output
GPIO.setup(buzz_pi... |
import math
def BSA(bWeight, bHeight):
return math.exp(
0.425*math.log(float(bWeight))
+0.725*math.log(float(bHeight))
+math.log(71.84))/10000
def DailyDose(bWeight, bHeight, fDose):
BSA_value=BSA(bWeight,bHeight)
if (fDose in set(["y","Y"])):
return 150*BSA_value
else... |
import os
import csv
num_votes = 0
results = {}
with open('election_data.csv') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader, None)
for row in csvreader:
if not row[2] in results:
results[row[2]] = 1
else:
results[row[2]] += 1
print("... |
nums = [0,1,2,2,3,0,4,2]
val = 2
# count method returns the number of elements with the specified value
while nums.count(val): # will loop through nums while val is in nums
nums.remove(val) # removes val from nums while val is in nums (while loop, see above)
print(nums)
|
def min_max_difference(numbers_array):
min=numbers_array[0]
max=numbers_array[0]
difference=0
for num in numbers_array:
if num<min:
min=num
if num>max:
max=num
difference = max-min
return difference
|
# scoping
x = 1
class A():
x = 3
class B:
print x
class C:
x = 5
class B:
def f(self):
print x
C.B().f()
class D:
x = 7
class E:
class F:
print x
class G:
def f(self):
x = 9
class H:
print x
G().f()
class I... |
#!/bin/python
name=["o2","yangqi"]
name.append("++");
name.sort()
for n in name:
print n
name[2]="fff"
name.append('aa')
for n in name:
print n
|
print('Digite a expressão - Por exemplo 2 + 2 ou 2 * 2')
result = str(input('Expressão: '))
print('Resultado: ', eval(result))
|
# -*- coding:utf-8 -*-
# ジェネレータ
# 処理の途中で値を返し、必要に応じて処理を再開できる
def sample_generator():
print("call 1")
yield "1st step"
print("call 2")
yield "2nd step"
print("call 3")
yield "3rd step"
# ジェネレータオブジェクトを作成
gen_func = sample_generator()
text = gen_func.__next__() # yieldまで実行
print(te... |
# -*- coding: utf-8 -*-
# map関数
# lambda式と組み合わせるとさらに簡略化が可能
from __future__ import print_function
# 引数の値を2倍にする関数
def calc_double(val):
return val * 2
x = 3
y = calc_double(x)
print(x, y)
data1 = [x for x in range(1, 100, 11)]
# calc_doubleでdata1の全ての要素を2倍にする
# data2はmapオブジェクトが格納されるため、appendなどできない
data2 = map(calc_... |
# -*- coding: utf-8 -*-
# ファイル入出力
# open("ファイルパス", "モード")
f = open("sample.txt", "r") # ファイルを開く
text = f.read() # ファイル読み込み
print(text)
f.close() # ファイルを閉じる
f = open("sample2.txt", "w")
f.write("sample text 2")
f.close()
# ファイルの読み書き
f = open("sample.txt", "r+")
text = f.read(... |
# -*- coding:utf-8 -*-
# Pythonのif-elif-else
# Pythonではスコープをインデント(タブ)で表す
if(10 > 5):
# 条件が真であれば実行
print("10は5より大きい")
print()
num1 = 8
if(num1 >= 10):
print(str(num1) + "は10以上")
else:
print(str(num1) + "は10より小さい")
print()
# `else if`ではなく`elif`を使う
# 論理和(||)は`or`演算子を使う
# 論理積(&&)は`and... |
def anumeric(st):
word = st.split()
l = []
for i in word:
if not i.isalpha() and not i.isnumeric() and i.isalnum():
l.append(i)
return l
print(anumeric("prokash this2 value is5 alphanumaric and 123 &h12")) |
import numpy as np
import matplotlib.pyplot as plt
from DeZero import Variable
import DeZero.functions as F
def main():
# dataset
np.random.seed(0)
x = np.random.rand(100, 1)
y = np.sin(2 * np.pi * x) + np.random.rand(100, 1)
# initialization of weights
I, H, O = 1, 10, 1
W1... |
# goal: receive a large peice of text via email from Bart and decrypt it here and send it back to him unencrypted
import other_millers
from math import gcd as bltin_gcd
class RSA:
def toBase10(self, n, alphabet):
a = 0
for c in n:
pos = alphabet.find(c)
a *= len(alphabet)
... |
username = input("Input username: ")
user_list= { "Quang Nguyen":{ "Name": "Nguyen Nhat Quang"
, "Age":"21", "Gender":"Male", "Interest":"Football",
},
"Thu Nguyen":{"Name": "Nguyen Thi Thu"
, "Age":"37", "Gender":"Female", "Interest":"Play",
},
"Quy Nguyen": { "Name": "Dinh Quy"
, "Age":"20", "Gender":"Male", "Interes... |
import os
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# returns a compiled model
# identical to the previous one
model = tf.keras.models.load_model('image_classification_fine.h5')
"""As the model trains, the los... |
from math import *
from numpy import *
# from chapter05.paintUtils import *
def loadDataSet():
dataMat = []
labelMat = []
fr = open("C:\\Users\\Mypc\\Desktop\\machinelearninginaction\\Ch05\\testSet.txt", )
arrayOLines = fr.readlines()
for line in arrayOLines:
lineArr = line.strip().split()
... |
'''Obliczanie wartość bezwzględnej danej liczby jest najprostszym przykładem
użycia algorytmu z decyzją. Dla danej liczby x wartość bezwzględna |x| wynosi:
x jeżeli x ≥ 0,
-x w przeciwnym wypadku.
'''
from decimal import Decimal
while True:
print('wpisz liczbę:')
x=int(Decimal(input()))
if x>=0:
... |
# generating sudoku grid filled with numbers
def showgrid():
print("grid")
for l in grid:
print(l)
def clear(num,x,y):
print("clear")
modx = int(x/3)
mody = int(y/3)
for a in range(len(grid)):
moda = int(a/3)
for b in range(len(grid[a])):
if grid[a][b] == ... |
# level 2 solving strategies
# functions here:
# from level2 import Naked_Multiple,Hidden_Multiple,Lines_2,NT,NT_chains,Y_Wing,
def Naked_Multiple(unit):
found = False
for mult in range(3,8):
done = []
for cell in range(len(unit)):
if type(unit[cell]) == str:
if len... |
import random
class die:
"""Class for die objects.
attributes:
sides (int) : Number of sides the dice has (default is 6)
methods:
change_sides(new_side) : changes the number of sides
roll_die() : returns a random integer from 1 to number of sides
... |
import random
def addition(n):
somme = 0
for i in range(1, n+1):
somme = somme + i
print(somme)
#addition(3)
#addition(8)
########################################################
def fibo():
n2 = 0
n1 = 1
suite = [0]
for i in range(1, 20):
somme = n1 + n2
n2 = n1
... |
#classes is collection of methods and variables#Multiple object
#Inheritance..existing the existing method for child class
#Operator overloading..
class Account1: #class variable (b_name) and instance variable (uname) - we use it with an instance; class function and instance function
#instance object and class... |
class Normal:
def __init__(self, x=0, y=0, z=0):
try:
(self.x, self.y, self.z) = x
except TypeError:
self.x = x
self.y = y
self.z = z
def __mul__(self, norm):
return (self.x * norm.x) + (self.y * norm.y) + (self.z * norm.z)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.