text stringlengths 37 1.41M |
|---|
# ITP Week 4 Day 2 Exercise
#Today we will pull information from the Pokemon api, put it into a dictionary, and then put that info into a new Excel file. We will write the pseudocode as a group in class. Be sure to follow the pseudocode, break your problems down into smaller pieces, and consult the documentation whe... |
#Write your code below this line 👇
# [Interactive Coding Exercise] Printing
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print('what to print')")
# String Manipulation and Code Intelligence
print("Hello world!\nHello Aisha\nHello Princess")
# String concatenation
print... |
#!/usr/bin/env python3
from random import sample, randint
# return list of common elements between two random lists of up to 50 numbers between 1 and 50
print([ num for num in sample(range(50),randint(1,50)) if num in sample(range(50),randint(1,50)) ])
|
'''
Util functions
'''
from math import sqrt
def distance(p1, p2):
'''
Distance between the point p1 and p2
Points are in the form (x,y)
'''
return sqrt(((p2[0] - p1[0]) ** 2) + ((p2[1] - p1[1]) ** 2)) |
"""
Controls:
see README
"""
from pynput import keyboard
import datetime
class Keyboard_Controller:
"""
Class for enabling keyboard input for the drone
Attributes
----------
drone : drone.Drone
The drone to control
keydown : bool
True if a key is pressed down, False if no keys... |
import numpy
def cartesian_to_polar(u, v):
"""
Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis).
Mainly for wind U,V to wind speed,direction transformations.
"""
c = u + v*1j
r = numpy.abs(c)
theta = numpy.angle(c, deg=True)
# Convert... |
digits=[]
while True:
try:
digits_input = input('Please enter comma separated digits: ')
input_split_by_comma = digits_input.split(",")
for digit in input_split_by_comma:
digits.append(int(digit))
break
except ValueError:
print("There is something wrong with t... |
def list_function(number, lst):
average = sum(lst) / len(lst)
min_value = min(lst)
max_value = max(lst)
less_count = len([i for i in lst if i < number])
more_count = len([i for i in lst if i > number])
return average, min_value, max_value, less_count, more_count
# testing
print(list_function(5,... |
import string
# se define la funcion check_char
def check_char(userin):
# se define la lista de caracteres
amay = string.ascii_uppercase
azmay = list(amay)
amin = string.ascii_lowercase
azmin = list(amin)
aztotal = azmay+azmin
# los errores se llamaran utilizando asserts en ... |
print(bool(1))
print(bool(0))
print(bool(0.01))
print(bool((1,2)))
print(bool((0,0)))
print(bool('string'))
print(bool('0'))
print(bool(''))
print(bool([0,0]))
print(bool({0}))
print(bool({}))
x = True
y = False
print(int(x))
print(int(y))
print(int(x and y))
print(int(x or y))
print(int(x + y))
print... |
import random
ans = random.randrange(-100,100)
i = 1
while(True):
str1 = "第" + str(i) + "次猜測的數值: "
g = eval(input(str1))
if(g > ans):
print('答錯,數字太大')
elif(g < ans):
print('答錯,數字太小')
else:
print('恭喜猜對了!共猜了', i,'次。')
break;
i+=1 |
n = eval(input('計算A!:'))
sum = 1
for i in range(n):
sum *= i+1
print( n, '! = ', sum) |
def main():
#take an input
toParse = sequence()
print("Please type in your note sequence with notes separated by spaces:")
inputbuffer = input()
toParse.setNotes(inputbuffer.split(" "))
if not toParse.checkvalid():
print("your sequence is invalid!")
return 1
print("the sequen... |
#! /usr/bin/env python
# latlon_3.py - for use in Chapter 10 PCfB
# Read in each line of the example file, split it into
# separate components, and write certain output to a separate file
# Set the input file name
# (The program must be run from within the directory
# that contains this data file)
InFileName = 'Ma... |
from typing import List, Union
class Stack:
"""
Stack Implementation based of python list (array)
values are kept in as string to suite the implementation needs
methods:
pop:
pops out the last element of the stack and returns it
push:
pushes an element to the t... |
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self, value):
self.first = Node(value)
self.last = self.first
self.length = 1
def enqueue(self, value):
self.last.next = Node(value)
... |
#PROGRAM TO FIND POWER OF ANY NUMBER IN FORM OF X^Y WHERE X AND Y ARE USER INPUTS.
x=int(input("ENTER VALUE FOR X "))
y=int(input("ENTER VALUE FOR Y"))
z=x**y
print("THE VALUE OF X^Y:",z)
|
# This program print a table discount for 5 prices
for i in range(5):
original = 5 * i + 4.95
discounted = original * 0.6
total = original - discounted
print("Original price: ${} \t Discounted: ${} \t Total: ${}".format(round(original, 2),
... |
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
#Dictionary above was copied from the learning platform per the assignment instructions
# Expected Output
# [("Speros", "(555) 555-5555"), ("Michael", "(999) 999-9999"), ("Jay", "(777) 777-7777")]
def tuplfy(tiona): ... |
# variables (number, strings, booleans(i.e. True/False))
# if/else = control flow or basic if-else logic.
# functions, are reusable templates of code. Also somtimes called subroutines.
# for/while loops are loops/iterations of pieces of code.
# classes encapsolate variables (data) and functions
# variables in a cla... |
## define statements
# variables
# data type (numbers, strings, boolean)
a = 10.876543
b = 10
c = 5
d = 3
print('HellowWorld')
## if else statments
# == equal to
# != not equal to
#if a == b:
# print("a is equal to b")
#elif c > a:
# print('a is equal to c')
#if a == d:
# print("a is equal to d")
#else:
#... |
"""
HeadHunter DEVSchool
Задача : Точки
Автор решения : Чиркин М.В.
Дата : 01.10.2015
"""
import math
class Point:
"""
x - координата точки по оси OX
y - координата точки по оси OY
radius - радиус точки (расстояние до ближайшей точки)
neighbors - список соседей... |
class Node:
def __init__(self,value,n=None):
self.data=value
self.next_node=n
self.previous_node=None
def get_next(self):
return self.next_node
def get_previous(self):
return self.previous_node
def get_data(self):
return self.data
def set_next(self,val... |
def swap(arr, a, b):
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(arr, start, end):
pivotIndex = start
pivotValue = arr[end]
while start <= end:
if arr[start] < pivotValue:
swap(arr, start, pivotIndex)
pivotIndex += 1
start += 1
... |
"""
Perception of light.
"""
# pyright: reportMissingTypeStubs=false
from typing import Tuple
import cv2
from perception.image import ImageBGR
GAUSSIAN_RADIUS: int = 41
def locate_brightest(img: ImageBGR) -> Tuple[float, Tuple[int, int]]:
"""
Return the value and pixel coordinates of the brightest area i... |
#for i in range (0,151):
# print(i)
#for i in range (0,1000005,5):
# print(i)
#for i in range (1,50):
# if i%5 == 0 and i%10 == 0:
# print("Coding Dojo")
# elif i%5 == 0:
# print("coding")
# else:
# print(i)
#x= 0
#for i in range(1,500000,2):
# ... |
#!/usr/bin/env python
import turtle
def draw_triangle(some_turtle):
for i in range (3):
some_turtle.forward(100)
some_turtle.right(120)
def draw_art():
window = turtle.Screen()
window.bgcolor('red')
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("green")
brad.speed(120)
for i in range (1,360):
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9
@author: ashu
"""
#Made by Ashutosh Gupta 101703118
import numpy as np #importing necessary libraries
import pandas as pd
import sys
def remove_outliers(infile, outfile):
dataset = pd.read_csv(infile) #reading dataset
data = dataset.iloc[:,1:]... |
import binascii
def str_to_hexStr(string):
str_bin = string.encode('utf-8')
return binascii.hexlify(str_bin).decode('utf-8')
def hexStr_to_str(hex_str):
hex = hex_str.encode('utf-8')
str_bin = binascii.unhexlify(hex)
return str_bin.decode('utf-8')
str1 = 0x1d6152ee93dd4122beb14c307e1779224f7e21b8... |
from xlrd import open_workbook, xldate_as_tuple
from xlutils.display import cell_display
from datetime import datetime, date
import sys
# CSV separator
SEP_CHAR = '|'
def convert(wb_name, sheet_name, start_row):
text = ''
wb = open_workbook(wb_name)
for s in wb.sheets():
if s.name == sheet_na... |
def solution(n, arr1, arr2):
answer = []
for i in range(n):
str1 = bin(arr1[i] | arr2[i])[2:]
# str1 = str1[2:]
#str1 = '0'*(n-len(str1))+str1
str1 = str1.rjust(n,'0')
# print(str1)
temp = str1.replace('1','#').replace('0',' ')
answer.append(temp)
retu... |
parent = {}
rank = {}
def make_set(v):
parent[v] = v
rank[v] = 0
def findRoot(v):
if parent[v] != v:
parent[v] = findRoot(parent[v])
return parent[v]
def union(root1, root2):
if root1 != root2:
if rank[root1] > rank[root2]:
parent[root2] = root1
else:
... |
# 2020 카카오 인턴십1 키패드 누르기
# https://programmers.co.kr/learn/courses/30/lessons/67256?language=python3
def solution(numbers, hand):
left_hand = "*"
right_hand = "#"
left = ['1', '4', '7', '*']
right = ['3', '6', '9', '#']
mid = ['2', '5', '8', '0']
answer = ''
for number in numbers:
if... |
nums = [3,1,2,3]
answer=0
s1 = set(nums)
half = len(nums)//2
if len(s1)>=half:
answer = half
else:
answer = len(s1)
# def solution(ls):
# return min(len(ls)/2, len(set(ls))) |
# Ryan Lin , CSC 110, 10/1/19
# Task 1
base_hours = 40
ot_multiplier = 1.5
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: '))
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
... |
# Ryan Lin, CSC 110, 10/10/19, Prof Ali
#
# Assignment 1
x = 0
for x in range(1, 10, 2):
y = "*" * x
print('{:^10}'.format(y))
x += 1;
if x == 10:
for x in range(7, 0 , -2):
y = '*' * x
print('{:^10}'.format(y))
x -= - 1
####################################... |
# coding: utf-8
from __future__ import division
import re
def get_stat_eff(n ,m, t):
"""
This function will compute the :
- Worst;
- Best;
- Random.
Efficiencies according the input variables, as follow:
------------------------------------------------------
(1) n: # Nodes
(2) m: #... |
# game ideas...
# cave adventure game, the point of which is to find a way out, to the light..
print("""You awaken in a cave, the only light is that of the lattern nearby on
the cavern floor. You do not know how you got here, all you remember is falling
asleep in your bed. after a brief look around with the lattern i... |
from random import randint
from celle import Celle
class Spillebrett:
# The constructor will have four instance variables notably self._rader which
# initiates the rows, self._kolonner which initiates the columns,
# self._rutenett which is an empty list and self._generasjonsnummer
# which is set to zer... |
def posterior(prior, likelihood, observation):
"""Returns the posterior probability of the class variable being true, given
the observation, ie. it returns p(Class=true|observation). The argument
observation is a tuple of n booleans such that observation[i] is the
observed value (T/F) for the i... |
# Uses python3
import sys
def calc_fib(n):
fib_nums=[0,1]
while(n>len(fib_nums)-1):
i=len(fib_nums)
temp_fib=(fib_nums[i-1]+fib_nums[i-2])%10
fib_nums.append(temp_fib)
return fib_nums
def fibonacci_sum_naive(n):
if(n==0):
return 0
elif(n==1):
return 1
els... |
'''
Try Else Finally
Finally: Regardless of the exceptions, a code will always be executed
'''
try:
x = int(input('Put a number: '))
y = 10/x
except ZeroDivisionError:
print('Cannot divide by zero')
else:
print(y)
finally:
print('Codes were excuted')
|
def selection_sort(alist):
# 与抓牌类似,左手上先有一张牌alist[0],然后抓一张牌alist[1]与手上的牌比较,value代表每次抓取的牌
for i in range(1,len(alist)):
value = alist[i]# 右手摸到的牌
# while循环体套路
j = i-1
while j>=0:
# 与手上左边的牌比较,如果比左边的牌小就交换位置
if value<alist[j]:
alist[j+1] = alist[... |
array = ["Malcolm", "X"]
array[0] = "Tray"
print(array[0] + " " + array[1])
groceryArray = ["Eggs", "Milk", "Yogurt", "Kombucha", "Chicken", "Lettuce", "Carrots"]
listSlice = groceryArray[3:6] # ":" slices the array non-inclusive of last index
slice_up_to_three = groceryArray[:3] #inclusive w/o "0" or last index
s... |
s = 'bicycle'
s[::3] #'bye'
s[::-1] #'elcycib'
print(s[::-2]) # eccb'
print(id(s[::-2]))
print(id(s[::-1])) #id相同
print(type((s[::-2])))
list = [3,4,5,6,7,8]
a=list[::-1]
b=list[1:3]
print(id(a),id(b)) #id不同
|
import collections
info=("feipeixuan",27,"牛逼")
### 元组拆包
name,age,_ = info
print(name,age)
name,*others =info
print(others) #[27, '牛逼']
### 嵌套元组拆包
info = (222,(3,5))
c,(x,y) =info
print(x,y)
### 命名元祖
Card = collections.namedtuple('Card', ['rank', 'suit']) #
print(Card(2,3))
Person = collections.namedtuple('Person',... |
a=[2,3,4,5,6,78]
b=['22','333','444','888888']
a.sort(reverse=True) #[78, 6, 5, 4, 3, 2]
b.sort(key=len)
print(b)
c={"aaa":22222,"bb":3}
print(sorted(c.items(),key=lambda item:item[1])) # 按照value 排序
print(c.items()) |
# coding:utf-8
"""
@author: mcfee
@description:
@file: test_slice.py
@time: 2020/7/10 下午3:12
"""
a = [1, 2, 3, 4]
print(a[1:-1])
print(type(a[1:-1]))
class Person:
def __getitem__(self, item):
print("222")
return item
person = Person()
print(person[1:-1]) # slice(1, -1, None)
print(dir(slice))... |
from random import *
# random number b/w 1 and 100
comp_num = randint(1, 100)
# getting user input
while True: # # test (check format) and get user input again
try:
guess = int(input("Enter an integer input between 1-100 : "))
break
except ValueError:
print("Error! That wa... |
from abc import ABC, abstractmethod
from utils.state import State
### THIS FILE CONTAINS CODE CLASSES OF DEVELOPED STATE SCORERS
# values of the state variable can be found in state.py
class StateScorer(ABC):
"""This is a base class for a state scorer. All developed state
scorers developed should inherit from... |
#!/usr/bin/env python
# 2019-3-31
from .node import Node
class BinarySearchTree:
def __init__(self):
self.__root = None
self.__comparisons = 0
@property
def comparisons(self):
return self.__comparisons
def __str__(self):
if self.__root is not None:
self.__... |
#!/usr/bin/env python3
# 2019-4-16
'''
NOTICE: This is an implementation using the Hashmap from assignment 2.
I prefer the other but just in case alan prefers this, I added it.
'''
import re
from .HashTable import HashTable
class AdjacencyList:
def __init__(self, commands):
self.__commands = commands
... |
"""Main games module."""
import prompt
ROUNDS_COUNT = 3
def launch(game):
"""Launch games.
Args:
game: game module
Returns:
Return cli to player.
"""
print('Welcome to the Brain Games!')
player_name = prompt.string('May I have your name? ')
print('Hello, {0}!'.format(pl... |
"""
exibindo uma tela vazia.
a tela abre.
escutamos o click em algumas teclas
"""
import pygame
def exibe_janela_e_escuta_click_em_varios_botoes():
largura_da_JANELA = 400
altura_da_JANELA = 400
largura_altura_da_JANELA = (largura_da_JANELA, altura_da_JANELA)
pygame.display.set_mode(largura_altura... |
"""
exibindo uma tela vazia.
a tela abre.
escutamos o pressionamento da tecla X
para fechar a tela.
"""
import pygame
def exibe_janela_e_escuta_a_letra_x():
largura_da_JANELA = 400
altura_da_JANELA = 400
largura_altura_da_JANELA = (largura_da_JANELA, altura_da_JANELA)
pygame.display.set_mode(largu... |
import numpy
firstLine = [int(x) for x in input().split()]
rows = firstLine[0]
columns = firstLine[1]
matrix = []
for i in range(rows):
M = numpy.array([int(x) for x in input().split()])
matrix.append(M)
print(numpy.transpose(matrix))
print(numpy.array(matrix).flatten()) |
def divide(dividend: int, divisor: int) -> int:
answer = 0
if dividend < 0:
return divide(-dividend, divisor) * -1
if divisor < 0:
divisor *= -1
while dividend - divisor >= 0:
dividend -= divisor
answer += 1
return -answer
... |
import unittest
from knapsack import Knapsack
from dynamic_program import Coins
class Chal4Test(unittest.TestCase):
def test_knapsack_values(self):
bag = (
(10, 60),
(20, 100),
(30, 195),
(40, 120),
(50, 120),
(5, 120),
(6... |
from vertex import Vertex
class Graph:
""" Graph Class
A class demonstrating the essential facts and functionalities of graphs.
"""
def __init__(self, file_name=None):
"""Initialize a graph object with an empty dictionary."""
self.vertices = {}
self.num_vertices = 0... |
x = 1
while True:
if x%2==1 and x%3==2 and x%4==3 and x%5==4 and x%6==5 and x%7==0:
break
x += 1
print(f"sol: {x}")
|
class BinaryTree:
"""
A Binary Tree, i.e. arity 2.
=== Attributes ===
@param object data: data for this binary tree node
@param BinaryTree|None left: left child of this binary tree node
@param BinaryTree|None right: right child of this binary tree node
"""
def __init__(self, data, left... |
"""
Some functions for working with puzzles
"""
from puzzle import Puzzle
from collections import deque
import random
# set higher recursion limit
# which is needed in PuzzleNode.__str__
# uncomment the next two lines on a unix platform, say CDF
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1)... |
"""
The rider module contains the Rider class. It also contains
constants that represent the status of the rider.
=== Constants ===
@type WAITING: str
A constant used for the waiting rider status.
@type CANCELLED: str
A constant used for the cancelled rider status.
@type SATISFIED: str
A constant used for ... |
#Day 2 Lecture
a=2
print('id(2) =', id(2))
print('id(2) =', id(a))
a = a+1
print('id(a) =', id(a))
print('id(3) =', id(3))
b = 2
print('id(b) =', id(b))
print('id(2) =', id(2))
a = 5
a = 'Hello World!'
a = [1,2,3]
def printHello():
print("Hello")
a = printHello
a()
def outer_function():
b = 34
def inn... |
# when there is only one condition to check, then only if is fine
# when there are only two condition then, we will use if and else (e.g. even or odd)
# If all if conditions(if+elif) fails, it executes the else
# If first if condition fails it execute subsequent elif and exit
num = 11
if num == 10:
print('In if ... |
# File Writing
file_obj = open("my_file.txt", "w")
content = """
these are my file contents
this is line #2
this is line #3
bla bla bla
"""
file_obj.write(content)
file_obj.close()
# File Reading
file_obj = open("my_file.txt", "r")
my_data = file_obj.read()
print(f'file contents: {my_data}')
file_obj.close()
# anothe... |
# !/usr/bin/env python
# -*- encoding:utf-8 -*-
# __author__ = "Xeon"
# Email: Xeon@xeon.org.cn
""""""
'''
isinstance: 它判断的是,obj是否是此类,或者此类的子孙类,实例化出来的对象
'''
# class A: pass
# class B(A): pass
#
# obj = B()
#
# print(isinstance(obj, B)) # 返回 True
# print(isinstance(obj, A)) # 返回 True
'''
getattr() 获取属性 ***
hasattr(... |
#
# @lc app=leetcode id=75 lang=python3
#
# [75] Sort Colors
#
class Solution:
def sortColors(self, nums:[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zeros,ones=-1,-1
for index,num in enumerate(nums):
nums[index] = 2
if... |
#
# @lc app=leetcode id=2 lang=python3
#
# [2] Add Two Numbers
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l = l1
temp = 0
... |
#
# @lc app=leetcode id=10 lang=python3
#
# [10] Regular Expression Matching
#
class Solution:
def isMatch(self, text: str, pattern: str) -> bool:
lengthOfText,lengthOfPattern = len(text),len(pattern)
dp = [[False]* (lengthOfPattern + 1) for _ in range(lengthOfText+1)]
dp[-1][-1] =... |
#
# @lc app=leetcode id=81 lang=python3
#
# [81] Search in Rotated Sorted Array II
#
class Solution:
def search(self, nums, target):
if not nums:
return False
low = 0
high = len(nums) - 1
while low <= high:
while low < high and nums[low] == nums[high]:#这样的目的是为... |
import socket
# Create a socket object
s = socket.socket()
# Get the local machine name
host = socket.gethostname()
# Set the port number
port = 12345
# Connect to the server
s.connect((host, port))
while True :
# Send a message to the server
text=input("message to server:")
if text == "q" :
bre... |
import math
ninty_angle = 90
# Create a Parent class, which all the other classes can refer to
class ParentShape():
def __init__(self, base, side, theta):
'''(ParentShape, float, float, float) -> NoneType
REQ: base > 0, side > 0
REQ: 0 < theta < 180
Initialize all the vairables, a... |
# Global variables. Feel free to play around with these
# but please return them to their original values before you submit.
a0_weight = 5
a1_weight = 7
a2_weight = 8
term_tests_weight = 20
exam_weight = 45
exercises_weight = 10
quizzes_weight = 5
a0_max_mark = 25
a1_max_mark = 50
a2_max_mark = 100
term_tests_max_mark ... |
import socket
import sys
import requests
import re
def hosts(host):
""" Return next ip """
host[3] += 1
if host[3] == 256:
if host[2] == 256:
if host[1] == 256:
host[0] += 1
host[1] = 0
host[1] += 1
host[2] = 0
host[2] += ... |
import random
import sys
def instructions():
print("Welcome to PassGen!")
print("To use PassGen enter values for three arguments.")
print("Argument 1: Password Length (int)")
print("Argument 2: Include Numbers (0=N or 1=Y)")
print("Argument 3: Include Special Characters (0=N or 1=Y)")
return
#Take system argume... |
import threading
import _thread
import tkinter as tk
import sys
""" Shows a popup with the alarm time & a button to cancel the alarm """
class Popup(threading.Thread):
def __init__(self, alarmtime):
threading.Thread.__init__(self)
self.__alarmtime = alarmtime
self.daemon = Tru... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 13 23:04:48 2018
@author: Habibur Rahman
@email: habib[dot]rahman[at]uits[dot]edu[dot]bd
"""
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return {"isEndOfWord": False, "children": {}, "Vi... |
# In this Lession we create the constructor
class Employee:
def __init__(self, nickadiname, salary, hobby): # THIS IS CONSTRUCTOR
self.nickname = nickadiname
self.salary = salary
self.hobby = hobby
def details(self):
# CREATE A FUNCTION THAT
return f"Nickname is: {sel... |
# a= input("Enter a name ")
# if a.isnumeric():
# raise Exception("number are not allowed")
# print(f"Hello {a}")
a= input("Enter you name ")
try:
print(f"{b} iss allowed!")
except Exception as e:
if a =="singh":
raise ValueError(f"[{a}is blocked")
print()
# raise ValueError(f"[{a}is... |
def serch(sentence1, sentence2):
"""
This function match the senteces with the
entere query
"""
word1 = sentence1.strip().split(" ")
word2 = sentence2.strip().split(" ")
word_score = 0
for words1 in word1:
for words2 in word2:
if words1.lower() == words2.lower():
... |
def search_name():
word = []
Employee_number = int(input("How many Employee you want to add this company"))
for i in range(Employee_number):
user_inp = input("enter the Company member ")
word.append(user_inp)
print("Your comapny member list is ",word)
# Book = ["aditya","singh"]
... |
from pygame import mixer
from datetime import datetime
from time import time
def Music_player(file, stopper):
mixer.init()
mixer.music.load(file)
mixer.music.play()
while True:
a= input("")
if a == stopper:
mixer.music.stop()
break
... |
# __author : "Flouis"
# date : 2017/12/28
# Python中字典(dict)的概念就等同于Java中Map——键值对
# 字典的键必须是不可变类型
# Python中字符串、整型和元组是不可变类型,列表和字典是可变类型
dictionary={'name':'Flouis','age':23,'company':'Pactera'}
print(type(dictionary))
print(dictionary)
# 对应操作:
# 1.查询元素:
print(dictionary['name'])
# 取出字典中所有的键:
print(list(dictionary.keys(... |
# __author : "Flouis"
# date : 2018/1/9
# Python中只能用关键字set进行集合的声明定义:
s = set('Hello,world.')
print(s) # {'H', ',', 'l', '.', 'r', 'd', 'w', 'e', 'o'}
#s = set(['abc','asdf','abc'])
#print(type(s))
#mylist = list(s)
#print(mylist)
# 可哈希——就是不可变且能被唯一标识的意思。
# set和list可以看成是两个极端——set:无序不可重复,list:有序可重复
# 因为无序所以set就不能像list那... |
# __author : "Flouis"
# date : 2018/1/23
if True:
x = 1
print(x)
def f():
print('before')
a = 100
print('after')
# Python的四作用域:built-in > global > enclosing > local
x = int(2.9) # 内置变量
# print(x)
g = 0; # 全局变量
def outer():
o_count = 1 # enclosing (嵌套变量)
print('o_count:',o_count)
def in... |
# Quick sort Algorithm
# Last element as pivot
# To get the correct position of pivot element
def pivot_place(list1,first,last):
pivot = list1[first] # first element as pivot
left = first+1 # indexing left
right = last # indexing right
while True:
while left <= right and list1[left] <... |
'''
Write a script that takes three strings from the user and prints them together with their length.
Example Output:
5, hello
5, world
9, greetings
CHALLENGE: Can you edit to script to print only the string with the most characters? You can look
into the topic "Conditionals" to solve this challenge.
'''... |
'''
Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example:
result = {1: 1, 2: 4, 3: 9, ...and so on}
'''
my_dict = {}
items = input (f' how many items would you like to add? ')
for i in range (int(items)):
my_dict[i+1] = (i+1)*(i+1)
print(my_dict) |
# IMPORTS
# for regular expression checking of IP
import re
# CONSTANTS
IP_REGEX = r'^([0-9]{1,3}\.){3}[0-9]{1,3}$'
# CUSTOM ERRORS
class AddressExtractError(Exception):
# Raised when extracting ip and port from address fails
pass
# FUNC:EXTRACT IP PORT
def extract_ip_port(address):
# split address in... |
#!/usr/local/bin/python3
#
# arrange_pichus.py : arrange agents on a grid, avoiding conflicts
#
# Submitted by : [PUT YOUR NAME AND USERNAME HERE]
#
# Based on skeleton code in CSCI B551, Spring 2021
#
import sys
# Parse the map from a given filename
def parse_map(filename):
with open(filename, "r") as f:
return ... |
import sys
# Node class for creating Node object of Graph
# Node class cannot be accessed directly, has to be accesed from the graph
from queue import PriorityQueue
class Node:
def __init__(self, name):
self.id = name
self.latitude = 0
self.longitude = 0
# Dictionaries to create a... |
from pythonapi.domain.line import Line
class Paragraph:
def __init__(self, lines: [str]):
self.lines = lines
# self.paragraph = [Line(line, lines) for line in lines]
def __eq__(self, other):
return self.lines == other.lines
def __len__(self):
return len(self.lines)
de... |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
#判断列表是否有环
class Solution:
def hasCycle(self, head):
if head is None or head.next is None:
return False
node1 = head
node2 = head.next
... |
def mergeSorted(l1, l2):
return mergeSorted_1(l1, l2, [])
def mergeSorted_1(l1, l2, tmp):
if l1 is None or l2 is None:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
tm... |
def hello():
print('hello world')
hello()
def sey_hello(name):
print(f"Hi {name}")
sey_hello("BOb")
def double(number):
return 2 * number
reesult_1 = double(3)
print(reesult_1)
#
def str_combine(str1, str2):
return f"{str1}{str2}"
result = str_combine('Kazuma', 'Takahashi')
print(result)
|
with open('name.txt', 'r') as f:
my_name = f.read();
def myname(my_name):
return("Hello my name is" + my_name)
with open('hello.txt', 'w') as f:
f.write() |
# Authors: Dima and Sarah
# Read the data from superheroes.json
import json
import csv
with open('superheroes.json', 'r') as f:
squad = json.load(f)
# Write header to csv file
with open('superheroes.csv', 'w') as f:
writer = csv.writer(f)
#write header
writer.writerow(['name', 'age', 'secretidentity', 'powers... |
# Given an array of integers, return indices of the two
# numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Given nums = [2, 7, 11, 15], target = 9,
def sumTo(nums, target):
values = {}
for i in r... |
'''
Description: A program that implements functions using list comprehension with map, filter, and reduce.
(I consulted https://www.python-course.eu/lambda.php and the textbook for more examples on list comprehension functions and
how to implement the lambda operator.)
Written By: Anh Mac
Date: 11/12/2018
'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.