text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
# coding: utf-8
# ### Tuples
# - t1 parenthesis() li square brackets[]
# - difference between list and tuples
# - list are mutable - can be changed / modified
# - used to access modify,add,delete data
# - tuples are immutable - vcannot be changed
# - used to access data only... |
# Import Counter
from collections import Counter
# Collect the count of each generation
gen_counts = Counter(generations)
# Improve for loop by moving one calculation above the loop
total_count = len(generations)
for gen,count in gen_counts.items():
gen_percent = round(count / total_count * 100, 2)
print('ge... |
# Collect the count of primary types
type_count = Counter(primary_types)
print(type_count, '\n')
# Collect the count of generations
gen_count = Counter(generations)
print(gen_count, '\n')
# Use list comprehension to get each Pokémon's starting letter
starting_letters = [name[0] for name in names]
# Collect the count... |
import random
def selectFromFile(path):
with open(path) as f:
dataList = list(f)
if dataList[0].find(":") != -1: # if there is a colon in the first line of the file
weightedDict = dictionaryCreator(dataList) # assume it is a raffle dictionary
return weightedSample(weightedDict)
el... |
"""
用for循环实现1~100求和
Version: 0.1
Author: 骆昊
Date: 2018-03-01
"""
sum = 0
for x in range(1, 101):
sum += x
print(sum)
'''
a = 2020
print(a)
b = int(input('b = '))
print(a+b)
'''
for x in range(11):
print(x)
|
for _ in range(10):
total = int(input())
difference = int(input())
klaudia = (total + difference) // 2
natalia = klaudia - difference
print(klaudia)
print(natalia)
|
while True:
n = int(input())
if n == 0:
break
pi = 3.1415926536
print("{0:.2f}".format(n*n/(2*pi)))
|
import itertools
from collections import Counter
def count_totals(s, n):
"""
Given the number of sides (s), and number of dice (n),
count the totals for all possible dice comibnations, and return a dictionary
mapping the total to the number of occurrences.
"""
return Counter(sum(r) for r in
... |
import urllib2
import re
from binaryTree import tree
#this is the binary search tree that will index the words that need to be ignored while indexing the search strings
stopWordsTree = tree()
#this is the binary search tree that will index the search strings
searchStringsTree = tree()
print 'Starting Indexing'
#ope... |
a = int(input('Введіть число: '))
b = int(input('Введіть число: '))
print(a+b)
print(a-b)
print(a/b)
print(a*b)
print()
print(abs(a+b))
print()
|
'''
Text based single deck blackjack game
One player vs an automated dealer
For 1 player, shuffle deck after 5 hands
Blackjack pays 3:2
Win pays 1:1
Dealer is dealt two cards, one face up and one face down
Player is dealt two cards face up
Dealer hits on 16 or less and soft 17; stands on hard 17 or greater
Ties go to t... |
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import csv
# Function will scrape the data for each teams allowed yard per game
def get_teams_OYG(team1, team2):
opp_ypg_url = 'https://www.teamrankings.com/nfl/stat/opponent-yards-per-game'
opp_ypg_data = urlopen(opp_ypg_url)
opp_ypg... |
from room import Room
from character import Enemy
from item import Item
backpack = []
kitchen = Room('Kitchen')
kitchen.set_description('a place to cook food')
dining_hall = Room('Dining Hall')
dining_hall.set_description('a place where people eat')
ball_room = Room('Ballroom')
ball_room.set_description('a place whe... |
print("请输入一个数:")
a = input()
b = pow(eval(a), 3)
print("{0:-^20}".format(b))
|
# 备注的使用
# coding=utf-8
# !@Author : YaoLei
# TempConvert.py
# 温度转换实例
TempStr = input('请输入带有符号的温度值,如82F或18C:')
if TempStr[-1] in ['F', 'f']:
C = (eval(TempStr[0:-1])-32)/1.8
print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
F = 1.8*eval(TempStr[0:-1])+32
print("转换后的温度是{:.2f}F".format(F)... |
# 学习文件的打开
# 文件操作的步骤:打开-操作-关闭
def read_txt1(): # 遍历全文本,方法一
fo = open('文件操作.测试文本', 'r', encoding='UTF-8') # 文件路径需要为反斜杠\或//,如'd:\45\3.tet',
# 'r' 只读 'w' 覆盖写模式 'x' 创建写模式 'a'追加写模式 't' 文件以文本文件打开,'b' 文件以二进制打开
# '+' 与r/w/x/a一同使用,增加同时读写功能
txt = fo.read() # 读人全部内容,一次读入,全文处理
fo.close() # 文件的关闭
return print(t... |
abc = {'A' : 'Z', 'a' : 'z', 'B' : 'Y', 'b' : 'y', 'C' : 'X', 'c' : 'x', 'D' : 'W', 'd' : 'w', 'E' : 'V', 'e' : 'v',
'F' : 'U', 'f' : 'u', 'G' : 'T', 'g' : 't', 'H' : 'S', 'h' : 's', 'I' : 'R', 'i' : 'r', 'J' : 'Q', 'j' : 'q',
'K' : 'P', 'k' : 'p', 'L' : 'O', 'l' : 'o', 'M' : 'N', 'm' : 'n', 'N' : 'M', ... |
def calc(val):
if (val % 2 == 0):
val = val**2
else:
val = 1/val*1000
return val
print(calc(22), type(calc(22)))
#print(calc("x")) |
# Importing modules
import os, csv
# Assigning a variable to the file getting read
path = os.path.join("Resources", "election_data.csv")
#Defining variables/lists
total_votes = 0
votes = []
candidate = 0
candidates = []
vote_percentage = []
winner = 0
# Opening the variable storing the file
with open(path) as csvf... |
from abc import abstractmethod
from typing import List, Dict
import pandas as pd
class AbstractDataSource:
@abstractmethod
def read_data(self, *args, **kwargs) -> List[Dict]:
"""
:return: list of dicts with the same keys
"""
pass
class CSV(AbstractDataSource):
def __init... |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return []
queue = deque()
queue.append(root)... |
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
n = len(board)
m = len(board[0])
x, y = click[0], click[1]
directions = [-1, 0, 1]
def dfs(x, y):
if board[x][y] == "M":
board[x][y] = "X"
... |
#!/usr/bin/python
'''
takes contents of delimited file and transposes columns and rows
outputs to txt file
'''
import re
def detect_delimiter(row):
pattern = re.compile(r'[a-zA-Z0-9"\']')
return pattern.sub('', row)[0]
def transpose(i, o=None, d=','):
f = open (i, 'r')
file_contents = f.readlines ()
... |
# 小飞机
# 来源:https://www.nowcoder.com/practice/5cd9598f28f74521805d2069ce4a108a?tpId=107&tqId=33282&rp=1&ru=%2Fta%2Fbeginner-programmers&qru=%2Fta%2Fbeginner-programmers%2Fquestion-ranking
# 描述:按格式输出*的飞机
# 矩阵:6*12
for i in range(6):
for j in range(12):
if i==0 or i==1:
if j==5 or j==6:
... |
import random
print("HELLO AND WELCOME TO THE UNBIASED DICE :")
print("DO YOU WISH TO ROLL THE DICE?[y/n]")
b = input()
if b == 'y':
a = random.randint(1,6)
print("YOU GOT A ",a)
if b == 'n':
print("OKAY THEN ......")
|
print('hello world')
print(3+1)
# 将我们的数据输出到文件当中
# a表示如果有文件就追加,如果没有文件就新建文件
fp = open('D:/helloPython.txt', 'a+')
print('hahahaha', file=fp) #换行输出
# 关闭文件
#fp.close()
# 不进行换行操作的输出
print('hello','world','python')
print('hello','world','python',file=fp)
fp.close()
#ret = input('请输入数据')
#print(ret)
'''
money = 10... |
# given a list of random numbers, chose a series of numbers from this list, making the sum largest
# every twos numbers that we chose from original list are not adjacent.
import numpy as np
def max_sum(arr, i):
if i == 0:
return arr[0]
elif i == 1:
return max(arr[0], arr[1])
else:
... |
# coding: utf-8
# from bottom to top, every point has two base point
# 1. select the larger one and plus it as the max sum for current point.
def dp_max_sum(triangle):
result = triangle
for x in range(len(triangle)-2, -1, -1):
for y in range(0, len(triangle[x])):
# get two children point a... |
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open('../practical5/task5.txt', 'w', encoding='utf-8') as f:
numbers = input('введите числа через пробел: ')
f.write(numbers +... |
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
# имя, фамилия, год рождения, город проживания, email, телефон.
# Функция должна принимать параметры как именованные аргументы.
# Реализовать вывод данных о пользователе одной строкой.
data = {
'name': 'имя',
'surname':... |
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
print('3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn')
x = str(input('Введите число "X": '))
x = int(x) + int(x + x) + int(x + x + x)
print(f'x + xx + xxx = {x... |
#-*- coding:utf-8 -*-
#定制类
class Student(object):
def __init__(self,name):
self.name=name
def __str__(self):
return 'Student object (name:%s)' % self.name
__repr__=__str__
print(Student('Michael'))
class Fib(object):
def __init__(self):
self.a,self.b=0,1
def __iter__(self):
return self
def ... |
from polygon import Polygon
class Rectangle(Polygon):
def __init__(self, side1, side2):
self.side1 = side1
self.side2 = side2
def draw(self):
print("Rectangle with width and height")
def getAria(self):
return self.side1 * self.side2
|
# ##########for문을 이용해서 구구단 출력하기 ###############
# for i in range(2,10): #2~9까지의 범위만큼 i가 반복합니다.
# for j in range(2,10): #i가 2일때 j는 2,3,4,5,6,7,8,9 i가 3일때 j는 2,3,4,5,6,7,8,9 이런식으로 반복합니다.
# print(i,"X",j,"=",i*j) #,로 구분해서 for문이 돌때마다 변하는 i와 j그리고 그 곱하기 기호와 = 기호로 이어줍니다.
# ##########한번만 답할수있는 구구단 게임 ########... |
import copy
import random
from typing import List
# -------------------------------------
State = List[List[str]]
class TicTacToeGame(object):
smarter = True
# If smarter is True, the computer will do some extra thinking - it'll be harder for the user.
triplets = [[(0, 0), (0, 1), (0, 2)], # Row 1
... |
from sense_hat import SenseHat
import time
from math import cos, sin, radians, degrees, sqrt, atan2
"""
Sense HAT Sensors Display !
Select Temperature, Pressure, or Humidity with the Joystick
to visualize the current sensor values on the LED.
Note: Requires sense_hat 2.2.0 or later
"""
sense = SenseH... |
from robots import Robot
class Fleet:
def __init__(self):
self.robots = []
# stores robot objects
def create_fleet(self):
for i in range(3):
name = "Robot" + str(i + 1)
self.robots.append(Robot(name)) |
# --- class ---
import calendar
from tkinter import *
class TkinterCalendar(calendar.Calendar):
def formatmonth(self, master, year, month):
dates = self.monthdatescalendar(year, month)
frame = Frame(master)
self.labels = []
for i,j in enumerate(["MON", "TUE", "WED", "THU", "FRI",... |
class Ordenamiento():
def __init__(self):
pass
# Retorna la Lista Invertida
@staticmethod
def insertsort(lista):
for i in range(1,len(lista)):
pos = i
while pos > 0 and lista[pos-1] > lista[i]:
pos -= 1
lista = lista[:pos] + [lista[i]] ... |
"""
program: average_scores.py
Author: Ondrea
Last date modfied: 06/07/20
The purpose of this program is to read in one person's names,
first and last, their age and three scores out of 100.
The program wants to take the three scores and find the average,
storing into a variable.
"""
def average(score1, ... |
# Read an integer:
a = int(input())
next = True
if a%100 == 0:
next = False
if a < 1000:
amnt = 10
else:
amnt = 100
while a > amnt:
a = int(a/10)
if next == True:
print (a+1)
else:
print(a)
|
class stack():
def __init__(self):
self.q1 = []
self.q2 = []
return
def push(self, x):
if len(self.q1) == 0:
self.q1.append(x)
else:
self.q2.append(x)
while len(self.q1) >0:
self.q2.insert(0, self.q1.pop())
self.q1 = self.q2.copy()
self.q2 = []
... |
def height_rows(student_heights):
arr = [[student_heights[0]]]
row = 0
for x in student_heights:
if arr[row][-1] >= x:
arr[row].append(x)
else:
arr.append([x])
return (len(arr))
test1 = [5, 4, 8, 1] #2
test2 = [8, 6, 9,12, 14, 5] #4
print(height_rows(test1))
print(height_rows(tes... |
'''
Given a string that may contain a letter f. Print the index of the first
and last occurrence of f. If the letter f occurs only once, then output
its index once. If the letter f does not occur, print -1.
'''
s = input()
ind1 = ind2 = -1
for x in range(len(s)):
if s[x] == 'f':
if ind1 == -1:
ind1 = x
... |
def flip(arr, k):
for i in range(k//2):
arr[i], arr[k-i-1] = arr[k-i-1], arr[i]
print (k)
print(arr)
return k
def is_sorted(arr):
for x in range(len(arr)-1):
if arr[x] > arr[x+1]:
return False
return True
def pancake_sort(nums):
k_vals = []
unsorted = len(nums)
while(unsorted > 0):
m... |
def first_missing_positive_integer(integers):
integers.sort()
count = 1
for y in integers:
if y == count:
count += 1
return count |
# Read an integer:
a = int(input())
b = int(input())
c = int(input())
# Print a value:
a *= c
b *= c
if b >= 100:
a += b//100
b%= 100
print(str(a) + " " + str(b))
|
# Read the numbers like this:
students = int(input())
apples = int(input())
# Print the result with print()
print(apples // students)
print(apples % students)
# Example of division, integer division and remainder:
"""
print(63 / 5)
print(63 // 5)
print(63 % 5)
""" |
def binarySearch(nums, find_num, start, stop):
if start > stop:
return -1
else:
mid = start+((stop-start)//2)
print(mid)
if nums[mid] == find_num:
return mid
elif find_num < nums[mid]:
return binarySearch(nums, find_num, start, mid-1)
else:
return binarySearch(nums, find_n... |
# Given two integers A and B (A ≤ B). Print all numbers from A to B inclusively.
a = int(input())
b = int(input())
s = ""
for x in range(a, b+1):
s += str(x) + " "
print (s) |
def nlp_calculator(statement):
statement = statement.split()
a = word_to_num([statement[1]])
b = word_to_num([statement[-1]])
nums_ans = translator[statement[0]](a,b)
return num_to_word(nums_ans)
def word_to_num(words):
words = "".join(words)
if words in word_dict:
return word_dict[words]
words =... |
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def print_bfs(self):
if not self.root:
return
queue = [self.root]
while len(queue) > 0:
current_node = queue.pop(0)
print(cur... |
import time
# ԂvNX
class ProcessingTimer(object):
def __init__(self, label = "processing time"):
self.start_time = 0 # Jn
self._label = label
def __enter__(self):
self.start_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
print( '{} : {:.3f} [s]'.format... |
import threading
import Queue
class IndexQueue:
"Thread-safe dictionary-like (used for register file reading)."
def __init__(self):
self.data = {}
self.data_lock = threading.Lock()
def put(self, key, value):
with self.data_lock:
if not key in self.data:
... |
import time
from binary_search_tree import BSTNode
start_time = time.time()
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = [] # Return the list of ... |
"""
pessoa e o modulo onde esta criada a classe Pessoa.
Pessoa maisculo e a classe q estou herdando.
Quando eu faço uma herança eu herdei os metodos da classe em questao, neste exemplo agora eu tenho
os metodos andar e chorar da clase Pessoa e mais o metodo bicicleta q fiz na classe BB.
"""
# Realizando a importaçao d... |
class CalculoReal(object):
def __init__(self,cotacao,valorReal):
self.valorReal = valorReal
self.cotacao = cotacao
if self.cotacao <= 0:
raise ("Cotacao Invalida")
print("chegou aqui...")
def converter(self):
print (self.valorReal / self.cotacao)
if ... |
"""
This is our main python file for Trump as a Movie for January monthly Hack
"""
import requests
movie = input("Enter movie name: ")
movie_title_bit = movie.replace(' ', '+')
r = requests.get("http://www.omdbapi.com/?t="+movie_title_bit+"&y=&plot=short&r=json")
data = r.json()
movie_rating = float(data["imdbRati... |
#Modify the constructor for the fraction class so that it checks to make sure that the numerator and denominator are both integers. If either is not an integer the constructor should raise an exception.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueErro... |
from os import walk
def create_dict(folder):
f, dict_here = [], []
for (dirpath, dirnames, filenames) in walk(folder):
f.extend(filenames)
break
for i in range(len(f)):
dictl='music/{}/{}'.format(folder,f[i])
dict_here.append(dictl)
with open("{}.txt".format(folder),"w") as f:
for i in range... |
import matplotlib.pyplot as plt
import numpy as np
from ReadingData import *
'''
Creates bar graphs for first and second questions using matplotlib
'''
#format long labels by splitting words onto new lines
def format_labels(dict):
for key in dict:
if ' ' in key:
new_key = '\n'.join(key.split('... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading the file
data=pd.read_csv(path)
#Code starts here
# Step 1
#Reading the file
#Creating a new variable to store the value counts
loan_status= data['Loan_Status'].value_counts()
#Plotting bar p... |
num = int(input("Enter number: "))
STR = input("Enter string: ")
|
def Perfect():
a = int(input("Enter a number: "))
sum = 0
for x in range(1,a):
if(a % x == 0):
sum += x
if(sum == a):
print("The number is perfect")
else:
print("The number is imperfect")
menu()
def Armstrong():
a = int(input("Enter a numbe... |
from itertools import combinations
def is_sigma_algebra(Omega, E):
# check if Omega is in E
if Omega not in E:
return False
# check if E is closed under complement
for item in E:
if Omega - item not in E:
return False
# check if E is closed under union
for i in range... |
# Functions are defined with the keyword def.
def add(a, b):
"""This method adds two numbers"""
# The above string is called as docstring that can be used
# to demonstrate how the use the function and what it does.
return a + b
print add(2, 3)
# Python functions can return multiple values.
def get_de... |
# While loops are as easy as they are powerful.
all_numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
length = len(all_numbers) # len() function lets you find the length of a data structure
i = 0
while i < length:
print all_numbers[i]
i += 1 # Compound increment operator
... |
import numpy as np
from math import *
from Common.state import Point
import matplotlib.pyplot as plt
#from help_functions import *
class Agent(object):
def __init__(self, in_index, start_pos, goal_pos, in_poi, radius, start_vel = np.zeros(2)):
self.pos = start_pos.xy
self.goal = goal_pos
... |
'''
Exercicio para descobrir o tamanho de nome do usuario usando strings e len() para calcular o tamanho
'''
nome = str(input("\nOlá.\nPor favor, digite seu nome:\n"))
if(len(nome) <= 5):
print(f"Nome curto, ein {nome}?")
elif(len(nome) > 6 and len(nome) <= 8):
print(f"Nome na média, {nome}")
else:
print(f... |
"""
Given an image represented by an NxN matrix, where each pixel in the image is
4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
"""
def swap(matrix, row1, col1, row2, col2):
temp = matrix[row1][col1]
matrix[row1][col1] = matrix[row2][col2]
matrix[row2][col2] = temp
# ... |
"""Module de gestion des arbres de la briandais. BriandaisTree est la classe
associee, et des fonctions de gestion existe afin de manipuler l'arbre de maniere
non POO."""
import string
import os
EXEMPLE = "A quel genial professeur de dactylographie sommes-nous redevables de \
la superbe phrase ci-dessous, un modele d... |
# Арифметические операторы
# http://pythonicway.com/python-operators
# Сложение
print(2 + 3) # 5
# Вычитание
print(2 - 3) # -1
print(-5 - 3) # -8
# Умножение
print(2 * 3) # 6
# Деление
print(6 / 3) # 2.0 (FLOAT)
print(3 / 2) # 1.5 (FLOAT)
# Деление по модулю (получение остатка от деления)
print(6 % 2) # 6 -... |
# Синтаксис языка Python
print('Hello world!!!')
# Написание кода в одну строку
print('Hello world!')
print('Hello world!!!')
# Написание нескольких функций в одну строку
print('Hello'); print('world!!')
'''
Пример
многострочного
комментария
'''
""""
Еще
один
пример
многострочного
комментария
"""
|
#commenting functions
def get_sum(a, b): # push Ctrl + Q
"""
Return sum a and b.
:param a: First operand
:type a: int
:param b: Second operand
:type b: int
:return: Return sum a + b type int
"""
return a + b
print(get_sum(1, 2))
#области видимости
a = 5 #global
def f():... |
print "---Part I---"
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
def names():
for dicts in students:
print dicts['first_name'] +... |
a=int(input())
if(a<0):
print("Invalid Value!")
elif(a<=50):
print("cost = {:.2f}".format(a*0.53))
else:
print("cost = {:.2f}".format(50*0.53+0.58*(a-50))) |
# create a random letter cypher for a string
import random
def make_dash(string):
out_string = ''
for char in string:
if char != ' ':
out_string += '-'
else:
out_string += char
return out_string
def make_new_key():
new_alpha = []
alphabet = list('abcdefghijk... |
# write a function (is_even(n)) that returns true or false depending on whether
# a number is even or not
# now write a function (filter_it) that takes a function and a list and returns
# a new list of numbers that are even.
def is_even(n):
if n % 2 == 0:
return True
'''
def filter_it(func, numlist):
... |
# '''
# In pure functional programming:
#
# 1. everything is a function
# 2. functions are "pure" and have no side effects
# 3. data structures are immutable
# 4. state is preserved inside a function
# 5. recursion is used instead of loops/iteration
#
# Advantages:
#
# 1. Absence of side effects makes your programs mor... |
# Given two text files containing numbers, return a list of the numbers
# that they share. (Use happy.txt and primes.txt)
# This requires: reading a file, converting from strings to integers
# and some list manipulation
a_file = open('happy.txt', encoding='utf-8')
a_string = a_file.read()
a_file.close()
b_file = op... |
# Given a list of ints, write a function find the highest_product you can get from three of the integers.
# The input list will always have at least three integers.
def product_of_three(alist):
#sort the list to put the highest integers at the end
alist.sort()
#set a total for product
total = 1
... |
import random
CELLS = [(0, 0), (0, 1), (0, 2),
(1, 0), (1, 1), (1, 2),
(2, 0), (2, 1), (2, 2)]
def get_locations():
monster = random.choice(CELLS)
door = random.choice(CELLS)
player = random.choice(CELLS)
if monster == door or door == start or start == monster:
return get_lo... |
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-fr... |
# Given two text files containing numbers, return a list of the numbers
# that they share. (Use happy.txt and primes.txt)
# This requires: reading a file, converting from strings to integers
# and some list manipulation
a_file = open('happy.txt', encoding='utf-8')
a_string = a_file.read()
a_file.close()
|
# write a function (mult) that takes two numbers and returns the result
# of multiplying those two numbers together
def mult(num1, num2):
return num1 * num2
# now write a function(apply_it) that takes three arguments: a function,
# and two arguments and returns the result of calling the function with
# the two ar... |
'''
In pure functional programming:
1. everything is a function
2. functions are "pure" and have no side effects
3. data structures are immutable
4. state is preserved inside a function
5. recursion is used instead of loops/iteration
Advantages:
1. Absence of side effects makes your programs more robust
2. Programs ... |
import random
def picker(list):
list_out = []
list_in = list[:]
while list:
pick = random.choice(list)
list_out.append(pick)
index = list.index(pick)
list.pop(index)
print(dict(zip(list_in, list_out)))
list = ['a', 'b', 'c', 'd', 'e']
print(picker(list)) |
# write a function (is_even(n)) that returns true or false depending on whether
# a number is even or not
def is_even(n):
if n % 2 == 0:
return True
else:
return False
# now write a function (filter_it) that takes a function and a list and returns
# a new list of numbers that are even.
liszt =... |
from tkinter import *
from random import randrange as rnd, choice
import time
root = Tk()
root.geometry('800x600')
root.title("Catch the ball")
canvas = Canvas(root, bg="White")
canvas.pack(fill=BOTH,expand=1)
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'magenta']
def new_ball():
"""
Creates a ball ... |
# Take input from user
number = int (input("Enter a number to check"))
#Now check
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a prime number')
# Print the reason for not being prime
print('Because', i, 'times', number//i, 'is', numb... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 03 23:04:41 2017
@author: User
"""
#!/usr/bin/python
def nextMove(posr, posc, board):
n = len(board[0])
dirt = []
for i in range(n):
for j in range(n):
if board[i][j] == 'd':
dirt.append([abs(posr-i)+abs(posc-j),i,j])
u... |
from typing import Optional
class Node:
"""
Each Node holds a reference to its previous node
as well as its next_node node in the List.
"""
def __init__(self, value, prev=None, next=None):
self.prev = prev
self.value = value
self.next = next
class DoublyLinkedList:
"... |
'''
Author@ Elijah_mikaelson
Given an array of integers,
return a new array such that each element at index i of the new array is the product of all
the numbers in the original array except the one at i
**Without using division**
'''
def Solution(arr,n):
for i in range(n):
|
# 변수가 가리키는 메모리의 주소 확인
a = [1, 2, 3]
print(id(a)) # 2130600743432
#region 리스트를 복사
# 1. 얉은 복사
b = a # 참조에 의한 복사(주소값 복사)
print(id(b)) # 2130600743432
print(a is b) # True
a[1] = 4
print(a, b) # [1, 4, 3] [1, 4, 3]
# 2. 깊은 복사
a = [1, 2, 3]
b = a[:]
a[1] = 4
print(a, b) # [1, 4, 3] [1, 2, 3]
f... |
# 딕셔너리 쌍 추가하기
a = {1: 'a'}
a[2] = 'b'
print(a) # {1: 'a', 2: 'b'}
a['name'] = 'pey'
print(a) # {1: 'a', 2: 'b', 'name': 'pey'}
a[3] = [1,2,3]
print(a) # {1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]}
# 딕셔너리 요소 삭제하기
del a[1]
print(a) # {2: 'b', 'name': 'pey', 3: [1, 2, 3]}
# 딕셔너리에서 Key 사용해... |
import numpy as np
import os
class Activation(object):
def __init__(self):
self.state = None
def __call__(self, x):
return self.forward(x)
def forward(self, x):
raise NotImplemented
def derivative(self):
raise NotImplemented
class Identity(Activation):
def __init__(self):
super(Identity, self).__... |
# The elevator will first process UP requests where request floor is greater than current floor and
# then process Down requests where request floor is lower than current floor.
# https://tedweishiwang.github.io/journal/object-oriented-design-elevator.html
from enum import Enum
from heapq import heappush, heappop
... |
import tensorflow as tf
import numpy as np
trX = np.linspace(-1, 1, 101)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 # create a y value which is approximately linear but with some random noise
X = tf.placeholder("float") # create symbolic variables
Y = tf.placeholder("float")
def model(X, w):
return tf.m... |
# Program divides the first number by the second number
a = int (input("Enter first number: "))
b = int (input("Enter second number: "))
answer = a // b
remainder = a % b
print(a, "divided by", b, "is", answer, "with a remainder of", remainder)
print("{} divided by {} is {} with a remainder of {}" .format (a, b, a... |
import matplotlib.pyplot as plt
import numpy as np
# The np.linspace() function in Python returns evenly spaced numbers over
# the specified interval which in this case is 40 numbers in range 0-4.
# plt.plot is plotting the variables, included are colour and labels
# title and x and y labels along with a legend and s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.