text stringlengths 37 1.41M |
|---|
"""
To modify a value in a ditionary, givethe dictionary name,
followed by the key in square brackets and then the new value
you want associated with that key placed after the equal to sign( = ).
"""
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The a... |
"""
Getting the computer to make a simple decision based on temperature readings
Objectives:
To understand simple, two-way, and multi-way decision programming patterns.
To understand the concept of Boolean expressions and the bool data type.
"""
# a program to convert celsius to fahrenheit
def main():
cel... |
# now, for the json.load() function
# this program uses json.load() to read back the list into memory
import json
filename = 'numbers.json' # we make sure to read from the same file we wrote to
with open(filename) as f_obj: # we open it in read mode
numbers = json.load(f_obj)
print(numbers)
# the jso... |
"""
A simple program that takes the user's input, and adds it to a list.
"""
cities = []
def main():
# def instructions():
# print("\n\tType in any city name I should visit, and I'll add it to a list.")
# print("\tTo quit, type <done>")
# instructions()
prompt = "\n\tType in any city name I s... |
# Python 2.7
# Example from Python Crash Course
# Here's another example of nesting a list inside of a dictionary
# looking at our previous example of a dicitonary of similar objects
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 16 17:42:04 2021
@author: mohammadtaher
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 21:40:59 2019
@author: Faradars-pc2
"""
def searchforvowels(w:str):
''' find vowels in word '''
#w = input('Yek kalame benevis: ')
v = set('aeiou')
'''found = v... |
def get_string(string):
substring = input("Get characters of string starting from n characters and m length (max is %d): " % len(string))
substring = substring.split(" ")
n = int(substring[0])
m = int(substring[1])
print('From %d to %d: %s' % (n, m + n, string[n:m + n + 1]))
print('\nFro... |
print('In Python, 0 to the power of 0 is: %d' % 0**0)
print('However, not everyone agrees that 0^0 is 1.')
|
# Goal: Record number of bikes available every minute for an hour in NYC
# This will allow us to see which station is most active during that hour
# Activity = total number taken out OR returned
import requests # requests is a URL handler to allow downloading from internet
from pandas.io.json import json_normalize
i... |
import sys
sample_input = ['2',
'5',
'5 6 8 4 3',
'3',
'8 9 7']
def solve():
pass
def write_output(t, result):
print ('Case #%s: %s' % (t, result))
sys.stdout.flush()
def run():
#We collect the first input line consisting of a single i... |
A = int(input())
B = int(input())
maxim = A
if maxim < B:
maxim = B
print(maxim)
|
a = int(input())
b = int(input())
c = int(input())
typ = ''
if b > a:
(b, a) = (a, b)
if c > a:
(c, a) = (a, c)
if a + b > c > 0 and a + c > b > 0 and b + c > a > 0:
if a**2 < b**2 + c**2:
typ = 'acute'
elif a**2 == b**2 + c**2:
typ = 'rectangular'
elif a**2 > b**2 + c**2:
ty... |
hour1 = int(input())
minut1 = int(input())
sec1 = int(input())
hour2 = int(input())
minut2 = int(input())
sec2 = int(input())
print((hour2*3600 + minut2*60 + sec2) - (hour1*3600 + minut1*60 + sec1))
|
import math # импортируется библиотека math
print(int(2.5)) # округляет в сторону нуля (отбрасывет дробную часть)
print(round(2.5)) # округляет до ближайшего целого, если дробная часть равна 0.5, то к ближайшему чётному
# перед каждым вызовом функции из библиотеки нужно писать слово ''math.'', а затем имя функц... |
from datetime import datetime
def expand_tweet(status):
'''Given a tweepy Status object, expands the text of the tweet
If the status object represents a retweet, then this
function sets "full_tweet" to the full text of the
retweeted tweet (i.e. the part after the "RT @handle:")
If the s... |
# exo 1
#
# def display_message():
# print("im a message")
# display_message()
# exo 2
#
# def favorite_book(title):
# if(title == "Alice in Wonderland"):
# print("One of my favorite books is Alice in Wonderland")
# favorite_book("Alice in Wonderland")
# exo 3
#
# def describe_city(name_of_city = "par... |
import math
class Circle():
def __init__(self, radius ):
self.radius = radius
def area(self):
x = 2*(math.pi)*self.radius
return x
def make_circle(self):
print(" **** ")
print(" * * ")
print(" **** ")
def __add__(self, other):
if isi... |
def maximum_number(*args):
max_num = args[0]
for i in args:
if i > max_num:
max_num = i
return max_num
print(maximum_number(-10,-4,-7,-10,-30)) |
# python_list_categ
l = ["haha", "poc", "Poc", "POC", "haHA", "hei","hey", "HahA", "poc", "Hei"]
d = {}
for cuv in l:
cuv.lower()
if cuv.lower() in d.keys():
d[cuv.lower()] += 1
else:
d[cuv.lower()] = 1
for cuv in d:
print ("Cuvantul {} apare de {} ori".format(cuv, d[cuv])) |
# python_substr_introductiv
s = input("Your string is ")
# a
for i in range(0, len(s)):
print (s[i:] + s[:i])
# b
print ("\n")
for i in range(0, len(s)):
print (s[-i:] + s[:-i])
# c
print ("\n")
for i in range(1, len(s)//2 + 1):
print (s[:i] + '|' + s[-i:]) |
'''
Program that calculates and list all the even, odd, and square numbers
between two given whole numbers including negatives.
'''
import math
def main():
x_value = int(input("Enter a value for x: "))
y_value = int(input("Enter a value for y: "))
print()
print("Even numbers between", x_value, "and",... |
# Sebastian Raschka, 2016
"""
source: http://adventofcode.com/2016/day/2
DESCRIPTION
--- Day 2: Bathroom Security ---
You arrive at Easter Bunny Headquarters under cover of darkness.
However, you left in such a rush that you forgot to use the bathroom!
Fancy office buildings like this one usually have keypad locks ... |
# 아무 것도 입력하지 않고 엔터만 입력하면 입력이 종료
# 여러 문장을 입력받아 대문자로 변환해 출력하는 프로그램을 작성
count = 1
while count <4 :
str_ = input()
if not str_:
break
print(">> {}".format(str_.upper()))
count =count +1 |
# #인 부분은 1 공백인 부분은 0
# # 이 하나라도 있으면 무조건 포함
# 공백은 둘다 만족
# 원래의 비밀지도를 해독하기
def bin(num):
result = ''
arr = ['0', '1']
while num > 0:
result = arr[num % 2] + result
num = num // 2
return result
def solution(n, arr1, arr2):
secret_map = []
for decimal1, decimal2 in zip(arr1, arr2)... |
# 1부터 20사이의 숫자 중 3의 배수가 아니거나
# 5의 배수가 아닌 숫자들의 제곱 값으로 구성된 리스트 객체를 출력하는 프로그램을 작성
list = []
for num in range(1,21):
if num % 3 !=0 or num % 5!=0 :
num = num ** 2
list.append(num)
print(list) |
from datetime import datetime
def calculate(name, age) :
year = 100- age + datetime.today().year
print(name+"(은)는"+ str(year) +"년에 100세가 될 것입니다.")
name = input()
age = int(input())
calculate(name, age) |
# 임의의 url 주소를 입력받아 protocol, host, 나머지(path, querystring, ...)로 구분하는 프로그램을 작성
url = input()
url_1 = url.split('://')[0]
url_2 = url.split('://')[1].split('/')[0]
url_3 = url.split('://')[1].split('/')[1]
print("protocol: "+url_1)
print("host: "+url_2)
print("others: "+url_3) |
# 100~300 사이의 숫자에서 각각의 자리 숫자가 짝수인 숫자를 찾아서 콤마(,)로 구분
arr =[]
for i in range (100,301) :
if (i //100)%2 ==0 and ((i%100)//10)%2 ==0 and (i%10)%2==0:
arr.append(i)
for i in range(len(arr)-1) :
print(arr[i],end=',')
print(arr[-1]) |
arr = "()[{}[]"
# arr2 = "((())))("
# check1 = []
# check2 = []
# check3 = []
# isTrue = "False"
# for i in arr2:
# if i == "(":
# check1.append(i)
# elif check1 and i == ")":
# check1.pop()
# elif i == "[":
# check2.append(i)
# elif check2 and i=="]":
# check2.pop()
# ... |
#7
class Restaurant():
def __init__ (self,restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
return "{} serves wonderful {}." .format(self.restaurant_name, self.cuisine_type)
def open_restaurant(self... |
# 소수인지를 판단하는 프로그램
def prime(num) :
for div in range(2,num) :
if num % div == 0:
print("소수가 아닙니다.")
break
elif div == num -1:
print("소수입니다.")
else:
continue
number = int(input())
prime(number) |
# dynamic programming --> 값들을 "저장"해두고 필요할 때 꺼내 쓴다.
# 피보나치 수열 정리 ★★★★
# 경우의 수 많은 경우 ---> dp 무조건 100% 활용하기
# bottom up 을
def solution(n):
answer = [0, 1] # F(0)=0, F(1)=1
for i in range(2, n + 1): # F(n) = (F(n-1) + F(n-2)) % 1234567
answer.append((answer[i - 1] + answer[i - 2]) % 1234567)
return a... |
import sys
alpha = str(input())
if alpha.isupper() :
print(alpha + "는 대문자 입니다.")
else :
print(alpha + "는 소문자 입니다.") |
from collections import deque
import sys
dx = [1,-1,0,0]
dy = [0,0,-1,1]
def iswall(x,y):
if x<0 or y<0 :
return False
if x >= n or y >= m :
return False
if matrix[x][y] == 0 : # 방문한 경우
return False
return True # 그 외의 경우
def bfs(x,y):
queue = deque()
print(queue)
q... |
#'abcdef' 문자열의 각각의 문자를 키로 하고 0~5 사이의 정수를 값으로 하는 딕셔너리 객체를 생성하고,
# 이 딕셔너리 객체의 키와 값 정보를 출력하는 프로그램을 작성
data = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5}
for key in data:
print(key + ": " +str(data.get(key))) |
# 덧셈하여 타겟을 만들 수 있는 배열의 두 숫자 인덱스를 리턴하라
# enumerate를 활용하여 부르트 포스 알고리즘
nums = [2,7,11,15]
target = 9
sum =[]
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if target == nums[j] + nums[i]:
sum.append(i)
sum.append(j)
print(sum)
dict={}
for index,value in enumerate(nums):
... |
l=[]
l0=[]
for i in range(2):
l1=[]
l0.append(l1)
for i in range(3):
l2=[]
l1.append(l2)
for i in range(4):
l2.append(0)
print(l0) |
from sys import maxsize
__author__ = "Grzegorz Holak"
# I decided to make first name and last name without default value, as rest can be blank
# only these 2 I decided to must have in each contact, so I changed order of parameters in method to make
# it easier. After all we could test more possibilities, fill some pa... |
# 6. Write a Python program to find the three elements that sum to zero from a set (array) of n real numbers.
class Triples:
def find_triplets(self, arr):
result = []
list_set = set(arr)
len_list = len(list_set)
for i in range(len_list - 1):
for j in range(i + 1, len_li... |
# 4. Write a Python class to get all possible unique subsets from a set of distinct integers. -
class SubSets:
@staticmethod
def subsets(arr):
result = []
for i in range(2 ** len(arr)):
subs = [arr[j] for j in range(len(arr)) if not i & (2**j)]
result.append(subs)
... |
from sys import argv
script, filename = argv
#open a text file
txt = open(filename)
print "Here's your file %r:" % filename
#Display the content
print txt.read()
print "Type the filename again:"
#Prompt the user to re enter the filename
file_again = raw_input("> ")
#open it again
txt_again = open(file_again)
#read i... |
# NOTE: This is a directional graph
# Need more logic for a unidirectional graph - need to copy edges into both graphs
import random
class GenerateGraphDict():
def __init__(self, verticies, max_edges=False):
self.verticies = verticies
if max_edges is False:
self.max_edges = verticies... |
# Verilen sayıyı kendi basamakları ile çarp: 29 2 * 9 = 18, 1 * 8 = 8
# Eğer çıkan sonuç tek basamaksa direk döndür
def persistence(n):
counter = 0
mylist = []
while len(str(n)) != 1: # n'in uzunluğu 1 olunca dur
for i in str(n): # Bütün haneleri bir listeye koy
... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
sentences = ["I love my dog",
"I love my cat",
"You Love my Dog!"]
tokenizer=Tokenizer(num_words=100)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
pr... |
# this file is code for the rod problem
# problem statement:
# given a length n, rod, we could cut the rod in any we like. Obviously, it should in int size, and we also get the price of each size rods. Our goal is to compute the max revenue we could get by cutting the rod.
# author: Jianbin hong
# Date: 15/11/2013
i... |
#Warren Green
#006314031
#takes user input
x = int(input("enter a number:"))
i = x
print("list of divisors")
# This loop calculates the divisors of whatever number is chosen
while i>0:
if x%i ==0:
print (i)
i -=1
else:
i -=1 |
#!/usr/bin/env python3
"""
This module should introduce you to basic plotting routines
using matplotlib.
We will be plotting quadratic equations since we already
have a module to calculate them.
"""
# Matplotlib is a module with routines to
# plot data and display them on the screen or save them to files.
# The prima... |
#!/usr/bin/env python3
"""
This script is intended to demonstrate the following built in data
structures in python:
dictionaries
This script acts better as a series of commands to enter
into the interactive python interpreter
See https://docs.python.org/3.4/library/stdtypes.html
"""
# To import just 1 class or... |
"""Homework. Advanced level
The Guessing Game
Write a program that generates a random number between
1 and 10 and lets the user guess what number was
generated.
The result should be sent back to the user via a print
statement."""
import random
user_input = input("What number am I thinking of? From 1 to 10 only: ")
... |
'''
преобразователь ПП в бинарный вид
прописать в правилах, что новая каждая команда на новой строчке и заканчивается запятой
'''
def hex2bin(str, form=16):
"""
Переводчик hex, oct str в bin str
"""
a = int(str, form)
return format(a, '0>16b')
def to_binary_pp(filename):
temp = {}
with op... |
class BySubjectGradeBook(object):
def __init__(self):
self._grades = {}
def add_student(self, name):
self._grades[name] = {}
def report_grade(self, name, subject, grade):
by_subject = self._grades[name]
grade_list = by_subject.setdefault(subject, [])
grade_list.appe... |
import pandas as pd
'''
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
'''
a = [1, 7, 2]
myvar1 = pd.Series(a)
print(myvar1)
# Labels
print(myvar1[0])
# Create labels
a = [1, 7, 2]
myvar2 = pd.Series(a, index=["x", "y", "z"])
print(myvar2)
print(myvar2["y"])... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 24 08:02:02 2015
@author: Jared J. Thompson
"""
import psycopg2
from psycopg2.extras import DictCursor
def connect_to_db(name, user, host, password ):
try:
conn = psycopg2.connect(database=name, user=user, \
host=host, password=password)
c... |
from tkinter import *
def readdata():
print("Clicked ReadData: You typed:", textval.get())
def removedata():
print("Clicked RemoveData")
win1 = Tk()
win1.title("Read from Textbox using a Button")
win1.geometry("200x200+100+600")
# Button class is used to add a button to the window
# use command property o... |
import pandas as pd
aus_weather = pd.DataFrame({
'city': ['Brissie', 'Sydney', 'Canberra'],
'temp': [55, 32, 16],
'wind': [66,50,80]
})
print(aus_weather)
us_weather = pd.DataFrame({
'city': ['Boston', 'Califonia', 'Dallas'],
'temp': [20, 33, 46],
'wind': [90,32,36]
})
print(us_weather)
# ... |
import pandas as pd
# PIVOT
df1 = pd.read_csv('files/city-weather.csv')
print(df1)
df2 = df1.pivot(index='Date', columns='City')
print(df2) # Displays full pivot table
df2 = df1.pivot(index='Date', columns='City', values=['Forecast', 'Wind'])
print(df2) # Displays full pivot table
# PIVOT TABLE
df3 = pd.read_csv... |
import pandas as pd
import numpy as np
df1 = pd.read_csv('files/replace.csv')
print('DF1:\n', df1)
# Replace using a list of values in the entire DF
df2 = df1.replace([-9999, -8888], np.NaN)
print('DF2:\n', df2)
# Replace using a list of values in a dictionary
df3 = df1.replace({
'temparature': [-9999, -8888],
... |
class Person:
def __init__(self, name, age):
print("Hello there, {}".format(name))
self.name = name
self.age = age
def __str__(self):
return "Name: {}\nAge:{}".format(self.name, self.age)
class Teacher(Person):
def __init__(self, name, age, sub):
Person.__init__(se... |
# Exponentials
num = int(input("Please enter a number: "))
exp = int(input("Please enter an exponent: "))
total = 1
for i in range(1,exp+1):
total = total * num
print("The result is: ", total)
'''
Output:
---------------
Please enter a number: 2
Please enter an exponent: 3
The result is: 8
''' |
# Continue statement demo
i = 1
while i < 10:
i = i + 1
if i < 8:
continue
print(i*10)
'''
Output:
-----------
5
6
7
8
9
10
''' |
from tkinter import *
win1 = Tk() # object of class Tk
win1.title("My First PyGUI Window") # Adds title to the window
win1.geometry("400x400+100+600")
lab1 = Label(win1, text='Your Name:', fg='Navy', bg='Teal')
# lab1.pack() # Places the element in the center of the window
# lab1.place(x=0, y=0) # places the eleme... |
def str_len(str1):
if isinstance(str1, int): # You can also use type(str1) == int
print('Integer is not supported')
elif type(str1) == float:
print('Floating point values are also not support at this stage')
else:
return len(str1)
str_len(233.5)
# ---------------------------------... |
class Playing_card:
def __init__(self, card_num, card_suit):
self.rank = card_num
self.suit = card_suit
@property
def color(self):
if self.suit.lower() == "hearts" or self.suit.lower() == "diamonds":
return "red"
else:
return "black"
card_1 = Playi... |
# (1) Scoop class -- each instance is one scoop of ice cream
#
# s1 = Scoop('chocolate')
# s2 = Scoop('vanilla')
# s3 = Scoop('coffee')
#
# print(s1.flavor) # chocolate
#
# for one_scoop in [s1, s2, s3]:
# print(one_scoop.flavor) # chocolate, vanilla, coffee
#
# (2) Person class -- name, e-mail address, and phone... |
import math
if __name__ == "__main__":
value = float(input())
mean = float(input())
stdev = float(input())
mid = float(input())
z = float(input())
ci_value = z * (stdev / math.sqrt(value))
print(round(mean - ci_value, 2))
print(round(mean + ci_value, 2)) |
def cat_and_mouse(cat_x, cat_y, mouse_z):
distanceA = abs(cat_x - mouse_z)
distanceB = abs(cat_y - mouse_z)
if distanceA > distanceB:
return 'Cat B'
elif distanceA == distanceB:
return 'Mouse C'
else:
return 'Cat A'
if __name__ == '__main__':
q = int(input())
for _... |
import math
def cumulative_distribution(mu, sigma, x):
"""
In a certain plant, the time taken to assemble a car is a random variable, X,
having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours.
What is the probability that a car can be assembled at this plant in:
... |
from scipy import stats
def find_mean_median_mode(n, _array):
"""
Print lines of output in the following order:
* Print the mean on a new line, to a scale of 1 decimal place (i.e., 12.3, 7.0).
* Print the median on a new line, to a scale of 1 decimal place (i.e., 12.3, 7.0).
* Print t... |
#!/bin/python3
import sys
def lowestTriangle(base, area):
height = int(round(area*2/base))
new_area = int(round(height*base/2))
if new_area >= area:
return height
else:
return height + 1
base, area = input().strip().split(' ')
base, area = [int(base), int(area)]
height = lowestTriangle... |
def picking_numbers(arr):
"""
Given an array of integers, find and print the maximum number of integers you can select from the
array such that the absolute difference between any two of the chosen integers is less than or equal to 1.
:param arr: an array of integers
:return: an integer that repres... |
def summingSeries(n):
"""
For each test case, print the required answer in a line.
:param n: a single integer
:return: answer % modulo
"""
modulo = 1000000007
answer = n * n % modulo
return answer
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n ... |
def sum_digits(num):
r = 0
while num:
r, num = r + num % 10, num // 10
return r
if __name__ == '__main__':
n = int(input())
divisors = []
for i in range(1, n + 1):
if n % i == 0:
divisors.append(i)
print(max(divisors, key=sum_digits))
|
def climbing_leaderboard(leaderboard, alice_scores):
rankings = createRankings(leaderboard)
i = len(leaderboard) - 1
for score in alice_scores:
flag = True
while flag:
if i == -1:
print(1)
flag = False
elif score < leaderboard[i]:
... |
print("===== program pembagian ======")
def pembagian(a,b):
return a/b
try:
penyebut = int(input("masukan angka penyebut :"))
pembilang = int(input("masukan angka pembilang :"))
print ( pembagian ( penyebut, pembilang ) )
except ValueError: # cara menangkap keywordl error
print("input yang anda msu... |
# # membuat proram menampilkan bilangan prima
array = []
def bilangan_prima():
for i in range(1,36):
if i < 36:
array.append(i)
print(array)
bilangan_prima()
array2 = []
user = int(input("masukan batas deretan bilangan :"))
for a in range(2,user):
mod = 1
print(a)
for b in... |
# operasi logika
# NOT,OR ,AND ,XOR
# NOT (kebalikan dari nilai oeprasi logika)
print("=====NOT=====")
a = True
d = False
print("operasi a =", a, "operasi d =", d)
hasil = not a
print("NOT a =", hasil)
hasil = not d
print("NOT d =", hasil)
# OR (jika salah satu bernilai true maka hasil akan true)
print("====OR====")... |
tahun = int(input("masukan tahun :"))
if tahun % 4 == 0:
if tahun % 100 == 0:
if tahun % 400 == 0:
print("tahun ini kabisat")
else:
print("tahun ini bukan kabisat")
else:
print("tahun ini kabisat 1")
else:
print("sudah pasti bukan tahun kabisat")
... |
# program menentukan bilangan genap ganjil
angka = int(input("mencari angka ganjil genap!!\nmasukan angka: "))
for i in range(1,angka+1):
if i % 2 == 0 :
print(i,"= bilangan genap")
else:
print(i," = bilangan ganjil") |
# +++++++++3--------------10++++++++++++
# masukan angka kurang dari 3 atau lebih besar dari 10
inputUser = float(input(" masukan angka\n kurang dari 3\n atau\n lebih dari 10 :"))
kurangDari = inputUser < 3
lebihBesarDari = inputUser > 10
print("angka yang anda masukan \n kurang dari 3 :",kurangDari,"\n atau \n lebih b... |
import pickle
'''
The pickle module allows us to serialize and de-serialize Python objects. In other words, it can transform an object into a tech stream before saving it into a file. The reverse is also possible and referred to as de-serializing.
Here we can create a constructor that sets the initial state of an ori... |
#
# Example file for working with functions
#
# define a basic function
def func1():
print("I am a function")
# function that takes arguments
def func2(arg1, arg2):
print(arg1, " ", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(nu... |
secret = "swordfish"
pw = " "
count = 0
auth = False
max_attempt = 5
while pw != secret:
count+=1
if count>max_attempt: break # it will break all the way out of the loop skip the else block
if count == 3 :continue # It just goes up at line 7 and checks the condition so instead of 5 trials only 4 trials
... |
#!/usr/bin/env python3
""" Three philosophers, thinking and eating sushi """
'''
Now that we've figured out how to avoid a deadlock between our two philosophers using chopsticks we can return to our routine of eating and philosophizing. I'm ready for another piece of sushi so I'll pick up the first chopstick, then the ... |
#!/usr/bin/env python3
""" Generators are the best way to iterate through large or complex data sets, especially when performance and memory are of concern.
The generator function returns a generator object and that generator object will yield the values. Now, you may have heard that generators yield rather than return... |
import platform
def main():
message()
x = 'Hello World "{1:<09}" "{0:>09}"'.format(8,9)
y = 10
a = 42
b = 73
r = f'I am f string ====> {y} {a}'
print(r)
def message():
print("This is python version {}" .format(platform.python_version()));print("I am {}".format(x));print("Just Checking %d" % y)
print(f"heh... |
pos = -1
def search(list,n):
i=0
for i in range(6):
i<len(list)
if list[i]==n:
globals()['pos']=i
return True
i=i+1;
return False
list=[5,9,122,90,45,6]
n=6
if search(list,n):
print("found at",pos)
else:
print("not found")
|
# -*- coding: UTF-8 -*-
# 通常一个切片操作要提供三个参数 [start_index: stop_index: step]
# start_index是切片的起始位置
# stop_index是切片的结束位置(不包括)
# step可以不提供,默认值是1,步长值不能为0,不然会报错ValueError。
# 取一个list或者tuple的部分元素
L = ['Michael','Sarah','Tracy','Bob','Jack']
# 取 L的 前三个元素
# 法一 笨方法: L[0] L[1] l[2]
# 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环
# 取 L 的前... |
# Program to guess a number from 1 to 9 and tell whether the number is too close, too far or exact.
# Give the user option to exit when he types "exit" and also show how many guesses he made at the end.
import random
import sys
a = random.randint(1, 9)
stop = False
count = 0
while stop == False:
count += 1
us... |
""" Convolutional Neural Network.
Build and train a convolutional neural network with TensorFlow.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
This example is using TensorFlow layers API, see 'convolutional_network_raw'
example for a raw implementation with varia... |
from cs50 import get_int
from cs50 import get_float
def main():
money = get_money()
cents = round(money * 100)
coins = 0
while cents >= 25:
cents = cents - 25
coins = coins + 1
while cents >= 10:
cents = cents - 10
coins = coins + 1
while cents >= 5:
... |
# NR法 関数の解を求める
import numpy as np
def f(x):
return x**2-2*np.sin(x)
def divf(x):
return 2*x-2*np.cos(x)
# 初期値
x = [1]
# 相対誤差
z = ["-"]
# 許容誤差
ips = 10**(-4)
xi = x[0]
zi = ips + 1
i = 0
print("初期値: " + str(xi))
print("許容誤差: " + str(ips))
print("")
while zi > ips:
print(str(i + 1) + "周目")
xi = x[i]... |
#!/usr/bin/env python
from hashlib import md5
from itertools import count
key, h5, h6 = input(), 0, 0
for i in count(1):
h = md5(f"{key}{i}".encode()).hexdigest()
# The nested conditions speed up evaluation
if h.startswith("00000"):
if not h5:
h5 = i
if h6:
... |
import unittest
from python_example_project.number_class import Number
unittest.main(argv=['first-arg-is-ignored'], exit=False)
class test_number(unittest.TestCase):
def test_float(self):
n = Number(2.)
self.assertEqual(n.square(), 4.)
self.assertEqual(n.cube(), 8.)
def test_int(se... |
# Import modules to use
from words import words
import random
from colorama import Fore,Style
# 1. Welcome
print("Welcome to the game hangman in Python")
# 2. Function to get word
def get_valid_word(words):
word = random.choice(words)
# Choose a good word
while '-' in word or ' ' in word: # While - or ' '
... |
numero_de_convidados = input('Quantas pessoas vao pra festa? ')
lisa_de_convidados = []
i = 1
while i <= int(numero_de_convidados):
nome_de_convidado = input('Coloque o nome do convidado ' + str(i)+ ': ')
lisa_de_convidados.append(nome_de_convidado)
i += 1
print('Serao chamados ' + numero_de_convidados , '... |
from random import uniform
# Animal names and IDs
species = {
'Monkey': 0,
'Giraffe': 1,
'Elephant': 2
}
class Animal:
""" Parent animal object """
def __init__(self):
self.health = 100.00
self.is_dead = False
self.name = type(self).__name__
def tick(self):
""" Method called every hour of simulation ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 08 18:09:13 2015
@author: Stephane
"""
"""This is a small script to demonstrate using Tk to show PIL Image objects.
The advantage of this over using Image.show() is that it will reuse the
same window, so you can show multiple images with... |
#return just the even items
my_array = [1,2,3,4,5,6]
def is_even(num) :
return num % 2 == 0
result = filter(is_even, my_array)
for item in result :
print(item) |
file = open('test.txt').read().strip('\n')
test = file.splitlines()
def solution(down, right, area):
count = 0
x = 0
y = 0
while True:
y = y + down
if y >= len(area):
break
x = (x + right) % len(area[y])
if area[y][x] == "#":
count = count + 1
... |
from fantasy import positions, relevant_stats
import pandas as pd
import numpy as np
def last_n_weeks(df, stub, career_game, n):
"""
Given the player's data stored in df, find the stats for the player's last n games
prior to career_game if they exist. Wrapping to previous year if necessary. If n > game
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.