text stringlengths 37 1.41M |
|---|
import re
import string
from CCG_new import constants
from CCG_new import util_classes
import pdb
import copy
from nltk.ccg import chart, lexicon
def _find_quoted_phrases(explanation):
"""
Checks for the existence of a quoted phrase within an explanation
Three types of quotes are accepted
... |
def header():
print("********************************")
print("*** Dice Rolling Simulator ***")
print("*** By Nathan Stanford Sr ***")
print("********************************\n")
# Set the default values of the Dice
Dice1Start = 1
Dice1End = 6
EndGame = 'n'
import random
header()
while EndGame ... |
# inheritance: 상속
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self, to_name):
print("안녕! " + to_name + " 나는 " + self.name)
def introduce(self):
print("내 이름은 " + self.name + " 그리고 나는 " + str(self.age) + "살이야.")
class Polic... |
from socket import *
import sys
import urllib.request
#The socket module forms the basis of all network communication
#Firstline specifies the address of the server. it can be an IP or servername.
#e.g. "128.138.32.126" or "yourserver.eng.uci.edu"
#second line shows which port your server will be working on(usually ... |
# Create a function that generates a file where all letters of English alphabet are listed by "n" on each line.
# Solution
import string
def letters_on_line(n):
with open("alphabet.txt", "w") as f:
alphabet = string.ascii_lowercase
letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabe... |
# Create a function that calculates acceleration given
# Initial velocity v1, final velocity v2, start time t1, and end time t2. The formula for acceleration is:
# a = (v2-v1)/(t2-t1)
# Solution (Python 2.6)
def accel_calc(v1, v2, t1, t2):
return float(v2 - v1) / float(t2 - t1)
print(accel_calc(0, 10, 0, 20))
|
"""
Functions used to reformat the data from graphql queries into the more useful data
"""
# noinspection SpellCheckingInspection
def get_event_ids_and_names(tournament: dict, videogame_id: int) -> list:
"""
Returns more the names of the events for a given tournament and game id
"""
event_names = []
... |
'''
Created on 2019. 4. 8.
@author: user
'''
'''
<커피전문점에 필요한 함수>
1. 총 커피값: 인원 * 커피값
2. 총 지불금액: 인원 * 커피값이 15000원 초과시 할인 2000원 (할인여부 판단)
'''
def coffeeSum(person,price):
sum = person * price
return sum # return 받는 대상: main 함수
def coffeeSale(sum):
if sum > 15000:
print("당신이 지불할 커피 ... |
'''
Created on 2019. 5. 1.
@author: user
'''
class Money:
name = '';
age = 0
give = 10000
def __init__(self, name, age):
self.name = name
self.age = age
Money.give = Money.give - 1000
def play(self):
print(self.name + "이(가) 놀고 있어요.")
... |
'''
a = 100
b = a
print(a,b)
print()
a = b = 200
print(a,b)
def sum(x, y): # x, y => 매개변수
return x + y
a = sum(200,100)
print(a)
print("반환 받은 값>>", a)
'''
def sum2():
x = int(input(">>"))
y = int(input(">>"))
return x + y
def sum3():
x = int(input(">>"))
... |
# -*- coding:utf-8 -*-
from tkinter import *
class MyApp:
def __init__(self,parent):
self.myparent=parent
#--- mainframe 생성 ---
self.mainframe=Frame(self.myparent)
self.mainframe.pack()
#--- button1 생성 ---
self.button1=B... |
# 기본
list = [1,5,8,2,3,9,7]
print(min(list))
print(max(list))
# 정렬한 후 최소값 최대값
list.sort()
print(list)
print(min(list))
print(max(list))
# 리스트에서 최소값 찾아서 프린트
list = [2,5,8,1,3,9,7]
print(list.index(min(list)))
# 찾고 싶은 값의 위치 찾기
print(list.index(8))
|
'''
Created on 2019. 4. 9.
@author: user
'''
'''
두 수를 입력받아 각각 처리해서 리턴하는
add, minus, mul, div 함수 만들기!!
'''
def add(x,y):
return x + y
def minus(x,y):
return x - y
def mul(x,y):
return x * y
def div(x,y):
return x / y
|
'''
Created on 2019. 4. 9.
@author: user
'''
import webbrowser
from tkinter import *
window = Tk()
window.title("DdP Program")
window.geometry("300x100")
def onClick(x):
webbrowser.open(x,new=1)
label = Label(text="some text")
label.pack()
labelOne = Label(text="A little bit more text")
... |
# basic output: monitor
print("Hi....")
print('Hi....')
# basic input: keyboard
name = input("your name: ")
year = input("your birth year: ")
print("your input name is", name)
print("your input year is", year)
# This is result
age = 2019 - int(year) + 1
print("your age is", age) |
# 소지금액 입력
def money():
global total
total = int(input("소지금액을 입력하세요>> "))
print("현재 소지금액은 %d원입니다." % total)
return total
# 1000원
def mf_1000():
mo_1000 = total / 1000
global re_1000
re_1000 = total % 1000
print("# 1000원 지폐는 %d개입니다." % mo_1000)
return re_1000
... |
print("###### 영화관 좌석 예매 프로그램2 #####")
# 초기좌석
seat = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
print("-----------------------------------------")
count = 0
while True:
# 좌석번호와 예매여부 출력
print("", end="\t")
for i in range(0,len(seat)):
print("%d열" % (i+1), end =... |
'''
Created on 2019. 5. 1.
@author: user
'''
class Employee:
name = ''
gender = ''
age = ''
agesum = 0
empcnt = 0
ageavg = 0
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
Employee.agesum = Em... |
'''
Created on 2019. 5. 1.
@author: user
'''
### 관리자 계정 관리 ###
class Member:
id = '';
pw = '';
grade = '';
mileage = '';
def __init__(self, id, pw, grade, mileage):
self.id = id
self.pw = pw
self.grade = grade
self.mileage = int(mileage)
if ... |
def main():
number_list = input().split()
even_list = [int(x) for x in number_list if int(x)%2 == 0]
odd_list = [int(x) for x in number_list if int(x)%2 != 0]
even_list.sort()
odd_list.sort()
if len(even_list) >= len(odd_list):
print([x for x in list_mix(even_list, odd_list)])
def lis... |
primeiro=int(input('Insira o primeiro termo da PA: '))
razão=int(input('Insira a razão da PA: '))
i=0
total=0
escolha=10
while escolha != 0:
total+=escolha
while i < total:
print(primeiro,end=' → ')
primeiro += razão
i += 1
print('PAUSA')
escolha=int(input('Quantos termos você q... |
n=0
quantos=0
soma=0
while n != 999:
n=int(input('Digite um número [999 para parar]: '))
if n != 999:
quantos+=1
soma+=n
print(f'Foram digitado {quantos} números e a soma entre eles é {soma}.')
|
pessoas={'nome':'Lucas','sexo':'M','idade':19}
print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.')
print('-'*30)
#laços com key value e items
for key in pessoas.keys():
print(key)
for values in pessoas.values():
print(values)
for key,value in pessoas.items():
print(f'{key} = {value}')
#apagar
del p... |
dados={'Nome':str(input('Nome do Jogador: ')).strip()}
partidas=int(input('Quantas partidas ele jogou: '))
gols=[]
total=0
for c in range(1,partidas+1):
marcados=int(input(f'Quantos gols na partida {c}: '))
gols.append(marcados)
total+=marcados
dados['Gols']=gols
dados['Total']=total
print('-'*30)
print(dad... |
import random
import time
sorteio=[]
jogos=[]
num=total=0
print('-'*40)
print(f'{"JOGA NA MEGA SENA":^40}')
print('-'*40)
escolha=int(input('Quantos jogos você quer que eu sorteie? '))
print()
print('-='*3,f' SORTEANDO {escolha} JOGOS ','=-'*3)
print()
while total < escolha:
cont=0
while True:
num=ran... |
nome=opção=maisbarato=''
preço=total=maisdemil=cont=maisbaratopreço=0
print('-'*25)
print(' LOJA')
print('-'*25)
while True:
nome=str(input('Nome do produto: ')).strip()
preço=float(input('Preço: R$'))
if cont==0:
maisbarato=nome
maisbaratopreço=preço
if preço < maisbaratopreç... |
lista=[]
for cont in range(1,6):
n=int(input('Digite um valor: '))
if cont == 1 or n > lista[-1]:
lista.append(n)
print('Adicionado ao final da lista...')
else:
pos=0
while pos < len(lista):
if n <= lista[pos]:
lista.insert(pos,n)
... |
#!/usr/bin/python3
"""
this is a comment
"""
spam = "That is Alice's cat."
# print "asdasd \n"
# print "aaa:",spam
# print "a",spam[3]
# print spam.upper()
# print spam[3:]
linein = raw_input()
print "a",linein
# print "a",linein.lower()
# print('How are you?')
# feeling = raw_input()
# if feeling.lower() == 'great':
... |
fname = input("Enter file name: ") #input file
fh = open(fname)
lst = list() #empty list
for line in fh: #split per words
line = line.rstrip()
line = line.split()
for nline in line: #check if words exist in lst, if not then append
if nline in lst:
continue
... |
# Quiz 1: Iterative Parsing
# Goal: iterative parsing xml file to find top-level tags and their count
# Output: dictionary including tag name as key, and tag count as value.
import xml.etree.ElementTree as ET
import pprint
from Collections import Counter
def count_tags(filename):
taglist=[]
tagdict={}
for event, e... |
# https://leetcode.com/problems/maximum-subarray/
class Solution:
# dynamic programming solution that adds to the max subarray if the
# maximum subarray at the previous array index is greater than zero.
def maxSubArray(self, nums: list[int]) -> int:
res = []
res.append(nums[0])
maxn... |
def handle_command(command_components):
if components[0] == 'insert':
numbers.insert(int(components[1]),int(components[2]))
elif components[0] == 'print':
print(numbers)
elif components[0] == 'remove':
numbers.remove(int(components[1]))
elif components[0] == 'append':
nu... |
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import solve
# Specify datapoints for the problem
xi = np.array([-1., 1., 2.])
yi = np.array([0., 4., 3.])
# Define the linear system to be solved
A = np.array([np.ones(3), xi, xi ** 2])
A = A.T
b = yi
# Solve the linear system
c = solve(A, b)
pri... |
"""
Your job is to write a function which increments a string, to create a new string.
If the string already ends with a number, the number should be incremented by 1.
If the string does not end with a number the number 1 should be appended to the new string.
"""
import re
def increment_string(string):
digits =... |
from hashmap_tree_intersection.tree import Tree, Node
from hashmap_tree_intersection.hashtable import Hashtable
def hashmap_tree_intersections(tree1,tree2):
dupes = []
hashtable = Hashtable(100)
if not tree1.root or not tree2.root:
return []
def looping(node):
nonlocal hashtable
... |
open = ["[","{","("]
close = ["]","}",")"]
def multi_bracket_validation(input):
brackets = []
for i in input:
if i in open:
brackets.append(i)
elif i in close:
pos = close.index(i)
if ((len(brackets) > 0) and
(open[pos] == brackets[len(bracket... |
def for_task2_increase_list(A,B):
N = B
for i in range(A, B-0+1):
print(i, end=" ")
if A > 0 and B > 0:
print("\nN - number", N)
def for_task2_down_list(A,B):
if A > B :
print("A shoud be less than B")
N = B
for i in range(A-1, B, A-1):
print(i, end=" ")
|
def task_ar_Odd_list():
import random
numbers = []
for i in range(10):
numbers.append(int(random.random() * 10))
print(numbers)
even = 0
print("Odd numbers in range:")
for i in numbers:
if i < 0:
break
if i % 2 == 0:
even += 1
else:
... |
int_val = 4
str_val = 'PythonIsBest'
flt_val = 24.56
# print(hash(4))
# print(hash(str_val))
# print(hash(flt_val))
print("The integer hash value is : " + str(hash(4)))
print("The string hash value is : "... |
from enum import Enum
class countries(Enum):
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
for country in countries:
print(country.name + " = " + str(country.value)) |
# -*- coding: utf-8 -*-
"""
Write a test program that prompts the user to enter a phone number as a string.
The input number may contain letters. The program translates a letter
(uppercase or lowercase) to a digit and leaves all other characters intact.
@author: Neha Bais
MET CS-521 A3
"""
# mapping key's... |
"""
Input : Prompts user to enter file name and string to be removed
Output : Removes the string from all occurences in the file.
"""
import os.path
inp_file = input ("Enter a file name :")
str_to_remove = input ("Enter the string to be removed: ")
file_path = r'E:\Neha\Spring 2020\CS521 Python\Source_Fi... |
# -*- coding: utf-8 -*-
"""
Use Class with private data fields
Write a test
program that prompts the user to enter a, b, c, d, e, and f
and displays the result.
If is 0, report that “The equation has no solution.”
Test Input :
No Solution : 1.0,2.0,2.0,4.0,4.0,5.0
Valid roots : 9.0,4.0,3.0,-5.0,-6... |
"""
Created on Thu Apr 2 10:11:42 2020
@author: Neha Bais
MET CS-521 A3
prompts the user to enter three numbers and invokes the
function to display them in increasing order
"""
def displaySortedNumbers(num1, num2, num3):
'''
Sort numbers in increasing order
'''
numbers = [num1, num2,... |
"""
Write a recursive function that displays
a string reversely on the console
inp : abcd
out : dcba
@author: Neha Bais
MET CS-521 A3
"""
def main():
inp_str = input('Enter a string: ')
if len(inp_str) == 0:
print('You entered a null string')
else:
print("Reverse of string... |
# -*- coding: utf-8 -*-
"""
Neha Bais
Write a program to display the population for each of the next five years. Assume the
current population is 312032486 and one year has 365 days.
"""
total_time = 3600 * 24 * 365 #calculate total seconds in a year
birth = total_time // 7
death = total... |
"""
Neha Bais
MET CS-521 Spring'20
Assignment 10.3
reads some integers
between 1 and 100 and counts the occurrences of each.
"""
def num_dict(num) :
# Empty dictionary
num_dict = {}
# Count of numbers in list
for i in num :
if i in num_dict :
num_dict[i] += 1
... |
"""
Majority judgement is a voting system that aims to produce a ranking of all
candidates (from here-on 'submissions'). For a horrible wiki-hole on voting
theory, please see: https://en.wikipedia.org/wiki/Majority_judgment
This is designed to provide basic tools to play around with this voting system.
It has been se... |
import numpy as np
matrix = np.arange(0, 100).reshape(10, 10)
print(matrix[1, :]) # whole row 1
print(matrix[:, 1]) # whole col 1
print(matrix[1, 1:4]) # row 1 from col 1 to 4
print(matrix[1:4, 1]) # col 1 from row 1 to 4
new_matrix: np.ndarray = matrix[1, :]
print(new_matrix.reshape(5, 2))
|
"""Handle questions asked to player."""
import time
import asyncio
import discord
import colours as colour
# this variable and function let ask.py have access to the client
client = None
def init(client_):
"""Provide module with `client`."""
global client
client = client_
# stores a... |
def descending_order(num):
# Bust a move right here
#turn a number into a string
#split it into a list
#sort and reverse it
#.join characters into a string
#cast back to integar
num = 123456789
num = str(num)
num = [char for char in num]
num.reverse()
joined = ''.join(num)
# for number i... |
"""Create our first deque. Which can push and pull from the head or tail."""
class Node(object):
"""this creates a node object that will be used for our deque."""
def __init__(self, val, prev=None, next_node=None):
"""Constructor for the deque project."""
self.val = val
self.prev = pr... |
"""Create a Graph Data Structure."""
class Vertex:
"""Create the verticies within the graph."""
def __init__(self, node):
"""Initialize the verts."""
self.id = node
self.adjacent = {}
def add_neighbor(self, neighbor):
"""Identify verts that are neighbors."""
self.... |
"""Implementation of a priority que"""
class PriorityQueue(object):
"""Initialize of PriorityQueue class."""
def __init__(self):
"""Initialize Priorirty Queue"""
self.pq_dict = {}
def insert(self, data, priority=0):
"Add value to queue with data and optional"
if not is... |
# https://www.hackerearth.com/practice/python/getting-started/input-and-output/practice-problems/golf/jadoo-and-dna-transcription/
d={"G":"C","C":"G","T":"A","A":"U"}
c=input()
for x in c:
if x not in d:
print("Invalid Input")
exit()
for x in c:
if x in d:
print(d[x],end='')
... |
import asyncio
import time
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(0.01)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def print_time(x):
for _ in range(x):
... |
"""
Day 16 Advent of Code 2018
"""
import sys
def main(filename):
"""Parse the input file and output the results."""
with open(filename) as f:
parts = f.read().split("\n\n\n\n")
samples = list(filter(None, parts[0].split("\n")))
program = list(filter(None, parts[1].split("\n")))
operation... |
"""
Day 4 Advent of Code 2018
"""
import operator
import re
import sys
from collections import defaultdict, Counter
def main(filename):
"""Main function for counting sleeping guards."""
ordered = {}
with open(filename) as f:
for line in f:
match = re.match(r'\[([^\]]+)\] (.+)', line)
... |
"""
Day 11 Advent of Code 2018
"""
import sys
MIN_GRID_SIZE = 1
MAX_GRID_SIZE = 301
def main(filename):
"""Parse the input file and output the results."""
with open(filename) as f:
serial = int(f.readline().strip())
grid = create_grid(serial)
area = create_summed_area(grid)
coordinates, ... |
# TODO: Write docstring here
"""The Hype Machine program is designed to hype the individual user up. It requires the user to give their name."""
# TODO: Initialize __author__ variable here
__author__ = "730010632"
# TODO: Implement your program logic here
name: str = input("What is your name? ")
print("You entered: ")
... |
#!/usr/bin/python
str1='hello'
str2='he'
if str2 in str1:
print 'contain the str'
else:
print 'not contain'
|
import csv
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
# loads data from csv file
def load_data(file_name, input_variable1, input_variable2, input_variable3, output_variable):
data = []
data_names = []
with open(file_name) as csv_file:
csv_reader = csv.reade... |
from tkinter import *
keyboardKeys = \
[
['q','w','e','r','t','y','u','i','o','p'],
['a','s','d','f','g','h','j','k','l','<--'],
['z','x','c','v','b','n','m','.','_','Enter'],
]
class VirtualKeyboard:
text = ""
cursor = [0, 0]
def displayKeyboard(self, score=0):
sel... |
# 万物皆对象,python中的类,函数都说对象
# 类名()会做两件事:自动分配内存空间;自动调用初始化方法
# 1.__init__,__del__,__str__
class Dog():
role = 'Dog'
def __init__(self):
print("hello world")
def print_dog(self):
print("hello dog")
def __del__(self):
print("wo zou le ")
def __str__(self):
# 必须返回一个字符串,直接输... |
class Node:
def __init__(self,weight,ch="",code="",left=None,right=None):
self.ch =ch
self.weight = weight
self.code = code
self.left = left
self.right = right
class Huffman_tree:
def __init__(self,str="",root=None,char_dict={},node_list=[]):
self.str = str
... |
def sort(nums,begin,end):
if begin>=end:
return
i=begin
j=end
tmp=nums[i]
while i<j:
while i<j and nums[j]>tmp:
j=j-1
if i<j:
nums[i]=nums[j]
i=i+1
while i<j and nums[i]<=tmp:
i=i+1
if i<j:
nums[j]... |
# 网易笔试第一题 最大公约数
def get_max(a,b):
if a < b:
a, b = b, a
while a %b !=0:
tmp = a%b
a = b
b = tmp
return b
# 第二题:按位或
def is_True(a,b,num_list):
if not num_list:
return "NO"
if a == 1:
num_list.append(b)
else:
num = b
for i in num_l... |
# 广度优先遍历bfs:先访问完同一层的结点,然后才继续访问下一层结点,
# 它最有用的性质是可以遍历一次就生成中心结点到所遍历结点的最短路径,这一点在求无权图的最短路径时非常有用。
import queue
def bfs(graph, start):
q = queue.Queue()
visited = set()
q.put(start)
while not q.empty():
u = q.get() # Remove and return an item from the queue.
print("u: ", u)
for v in... |
#!/usr/bin/env/python3
# -*- coding: utf-8 -*-
"""
@Time : 2020/3/30 16:34
@Author : Chen Liu
@FileName: bai_du.py
@Software: PyCharm
"""
# 判断链表是否有环,如果有返回交点,
def is_exisit(root):
if not root:
return None
searched_list = []
while root:
searched_list.append(root)
root = root.ne... |
# Python program to create a simple GUI
# calculator using Tkinter
# import everything from tkinter module
import Tkinter as tk
import Calconfig as cf
import math as mt
from itertools import cycle as cy
# globally declare the expression variable
expression = ""
recall=[]
recl = cy(recall)
def recallfn(exp):
... |
from typing import List,Any
import math
import numpy as np
Vector = np.ndarray
def l2_len(v: Vector) -> float:
return math.sqrt(np.dot(v, v))
def dot(v1: Vector, v2: Vector) -> float:
assert v1.shape == v2.shape
return np.dot(v1, v2)
def add(v1: Vector, v2: Vector) -> Vector:
assert v1.shape == v2.... |
# Lists Bölümündeki HackerRank Çözümüm
#=========================================================================
N = int(input())
l=[]
for i in range(0,N):
inp=input()
if inp.startswith('insert'):
l.insert(int(inp.split()[1]),int(inp.split()[2]))
elif inp.startswith('print'):
print(l)
e... |
# задание 1
name = "Anna"
age = 28
number = 3.4
print(name)
print(age)
print(number)
name = input("What is your name?")
print("Nice to meet you," + name)
age = input ("How old are you?")
print("Great! You are" + age + "years old")
# задание 2
number = int(input("Введите число в секундах:"))
hours = str(number // 36... |
age=21
if age==21: #Notice the use of : , indendatioan and no braces
print("No beer for u")
name="Goku"
if name is "Avash": #notice the use of 'is'
print("Hey there Avash")
elif name is "Lucy": #notice the syntax of elseif
print("What up luce")
elif name is "Toto":
print("Tyau Tyau")
else:
print("N... |
numbersTaken=[7,9,12,18,21]
print("here are the numbers that are still availabe")
for n in range(1,30):
if n in numbersTaken:
continue #.. flow of control goes back to loop when if condition is met
print (n)
|
while True:
try:
number=int(input("Whats ur fave num")) #may be we gonnaa get error here
print(10/number)
break
except ValueError: #if we get value error from above code ...below code is run
print("Make sure enter a number")
except ZeroDivisionError:
print("Dont pick ... |
'''
Programa : Ciencia de Datos con Pthon
Modulo 02 : Estadística y Visualización de Datos con Python
Sesion 01 : Importación de Datasets
Fecha : 18/08/2019
Version : 1
Author : Jaime Gomez
'''
import numpy as np
# Basic Operations
print("------------------------------------")
# Arithmetic Operators
a_array = np.ara... |
'''
Programa : Ciencia de Datos con Pthon
Modulo 02 : Estadística y Visualización de Datos con Python
Sesion 01 : Fundamentos de Estadistica
Fecha : 01/09/2019
Version : 1
Author : Jaime Gomez
'''
import pandas as pd
import numpy as np
import scipy.stats as ss
# Media
print("---------------------------------")
NOMBRE_... |
# let's say we are interested in just product price, so we wanna sort the price
items = [
('product', 10),
('product1', 9),
('product2', 12)
]
# in older way we can do this.
prices = []
for item in items:
prices.append(item[1])
# print(prices)
# and also smart way we can do this
x = map(lambda item: i... |
import datetime
import pytz
# for time zone
dt = datetime.datetime(2020, 7, 12, 9, 30, 45, tzinfo=pytz.UTC)
# print(dt)
# to print list of the time zone name
for timezone in pytz.all_timezones:
# print(timezone)
pass
# dt_utc_now = datetime.datetime.now(tz=pytz.UTC)
# print(dt_utc_now)
#
# dt_dhaka = dt_utc... |
def alphanumeric(s):
letter_flag = False
number_flag = False
for i in s:
if i.isalpha():
letter_flag = True
if i.isdigit():
number_flag = True
# print('Number:'+ number_flag)
# print("Letter:"+ letter_flag)
return letter_flag and number_flag
def is_uid_... |
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
# print(arr.shape)
arr2 = np.array([1, 4, 6, 9], ndmin=5)
print(arr2)
print('Shape of Array', arr2.shape)
|
#to change the value of touple
thisToupel = ("apple", "banana", "cherry")
newList = list(thisToupel)
newList[1] = "mango"
backToTauple = tuple(newList)
print(backToTauple)
lenght = len(backToTauple)
print(lenght)
for item in backToTauple:
print(item)
oneItem = ('one',)
oneItem.__class_getitem__()
print(oneItem)
... |
items = [
('product', 10),
('product1', 9),
('product2', 12)
]
filtered = list(filter(lambda item: item[1] >= 10, items))
# print(filtered)
def filter_num(numbers):
if numbers > 4:
return numbers
num_list = [3, 6, 4, 20, 8, 1]
filter_numbers = list(filter(filter_num, num_list))
print(filter_... |
x = input('Value 1: ')
y = input('Value 2: ')
print(x + y)
|
airplane = 0
while airplane <= 3:
airplane += 2
print("*")
|
x = int(input('Value 1: '))
y = int(input('Value 2: '))
x = x // y
y = y // x
print(y)
|
#!/usr/bin/env python3
import bisect
#implementation of the Bentley Ottman Algorithm for detecting intersections in O(NLogN+k)
class Event:
p1 = (0,0) #point (y,x)
p2 = (0,0)
event_type = None #'start', 'end', and 'v' are accepted types
def __init__(self, p1, p2, event_type):
self... |
#!/usr/bin/env python
# coding: utf-8
# # Problem 1: Basics of Neural Networks
# * <b>Learning Objective:</b> In this problem, you are asked to implement a basic multi-layer fully connected neural network from scratch, including forward and backward passes of certain essential layers, to perform an image classificatio... |
'''import datetime
now = datetime.datetime.now()
if now.hour < 12 :
print("AM")
else :
print("PM")
month = int(input('월을 입력해주세요 : '))
if 3 <= month <=5 :
weather = '봄'
elif 6 <= month <=8 :
weather = '여름'
elif 9 <= month <=11 :
weather = '가을'
elif month == 12 or month <= 2 :
weather = '겨울'
pri... |
num = int(raw_input('Enter a positive integer:'))
pwr = 2
root = 1
ans= False
while pwr < 6:
while abs(root**pwr)<=abs(num):
if root**pwr == num:
print 'the root is', root
print 'the power is', pwr
ans = True
root += 1
pwr += 1
# root = 1
if ans != True:
pri... |
import datetime
class Person(object):
def __init__(self, name):
"""Create a person"""
self.name = name
try:
lastBlank = name.rindex(' ')
self.lastName = name[lastBlank+1:]
except:
self.lasrName = name
self.birthday = None
def getName... |
def f(x):
def g():
x = 'abc'
print 'x =', x
def h():
z = x
print 'z =', z
x = x + 1
print 'x =', x
h()
g()
print 'x =', x
return g
x = 3
z = f(x)
print 'x =', x
print 'z =', z
z()
|
import pandas as pd
index = 0
data = pd.read_csv("/Users/aditi/Downloads/Gala Donations.xlsx - sf.csv")
names = data["Opportunity Name"]
amounts = data["Amount"]
my_csv = pd.read_csv("/Users/aditi/Downloads/Spreadsheet2.xlsx - Sheet1.csv")
contacts = my_csv["Contacts"]
moneys = my_csv["Amount"]
for name in names:
... |
x = "There are %s types of people." %10
print x
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s" % (do_not, binary)
print y
print "I said: %r" %x
print "I also said: '%s'." %y
hilarious = False
joke_evalution = "Isn't that joke so funny?! %s"
print joke_evalution % hilarious |
#Можно ли собрать библиотеку из рецептов по разделам:
# закуски, 2-е, десерты.
# Потом создать функцию
которая будет выводить список и количество продуктов
при
# выборе 1,2,3 блюда на _____ персон.
В итоге вывести на печать список покупок.
with open('recipe.txt', encoding='utf-8') as document:
menu={}
for lin... |
def func(*args, **kwargs):
if "reverse" in kwargs:
return [word[::-1].title() for word in args]
return [word.title() for word in args]
print(func(*["hello", "world"]))
print(func(*["hello", "world"], reverse=True))
|
# Operators in Python
print("Operators in Python")
print(2 + 2)
print(2 * 2)
print(2 - 2 * 5)
print(4 / 2)
print(8 // 2)
print(2 ** 4)
print(round(22 / 7))
print(round(22 / 7, 2))
print(48 % 7)
# Precedence and Associativity
# ()
# ** R --> L
# *,/,//,% L --> R
# +, - L --> R
print("Precedence and Associativity")
pri... |
# Using list comprehension
even_number_less_than_10 = [i for i in range(1, 11) if i % 2 == 0]
print(even_number_less_than_10)
# Using Filter function
even_number_less_than_10 = list(filter(lambda a: a % 2 == 0, list(range(1, 11))))
print(even_number_less_than_10)
def func(number):
return str(number)
result = fil... |
# unordered collection of unique elements
s = {1, 2, 3, 1.2, 'a', 'b'}
print(s)
# can not store list or dictionary in set. since they are not un-hashable(so it can not remove duplicates)
# s = {[], {}}
# Adding items to set
s.add(11)
# Will throw exception if 11 is not found, use discard instead
s.remove(11)
# No e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.