text stringlengths 37 1.41M |
|---|
'''class user:
def __init__(self,name,mob_no,address=""):
self.name=name
self.mobile_no=mob_no
self.address=address'''
class BankAccount:
def __init__(self,name,ph_no):
self.name=name # accesing by using self .methods
self.phone_no=ph_no
#self.acc_no=acc_no
self.generate_acc_no()
self.balance=0
def... |
#---------------------object instantiation-----------------
'''class Person:
pass
jai=Person()#INSTANTIATION
print(type(jai))
s=type(jai) == Person
print(s)'''
#-------------self description---------------------------
'''class Person:
def say_hello(self):
print("Hello")
print(self)
print(jai)
jai=Person()
#jai.... |
test_cases = int(input('Enter number of test cases : '))
for test_case in range(test_cases):
n = int(input())
answer = []
for i in range(n+1):
decimal = i
binary = '{0:b}'.format(decimal)
count = binary.count('1')
# print(str(i)+' = '+str(count))
answer.append(count)
... |
import unittest
def find_repeat(arr):
start = 1
end = len(arr) - 1
while start < end:
mid = start + (end - start)//2
low_start, low_end = start, mid
high_start, high_end = mid + 1, end
actual_num = 0
expected_num = low_end - low_start + 1
for item in arr:
... |
# 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:
node = []
i=0
while i < len(l1):
node
print("in while")
... |
print("Multiplos de un numero en un rango dado (del 10 al 100)")
x=int(input("Ingrese un numero: "))
print("Los multiplos de " + str(x) + " dentro del rango de 10 al 100 son: ")
for i in range(10, 101):
if i % x == 0:
print(str(i)) |
from tkinter import *
import math
root = Tk()
root.title("Calulator")
root.iconbitmap('F:tutorial\calculator.ico')
root.geometry("315x302+785+301")
display = Text(root, width=40, height=2.5,padx=10, pady=15,background="#f4ffd4", foreground="#000000")
display.place(relx=0.032, rely=0.033, relheight=0.179, relwidth=0.9... |
num = int(input("Enter the number: "))
def factorial(n):
a = 1
while n >= 1:
a = a * n
n = n - 1
return a
q = factorial(num)
print(q)
range |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 13:01:15 2021
@author: Sahil Patil
"""
def recursive_binary_search(list, target):
if len(list) == 0:
return False
else:
midpoint = (len(list))//2
if list[midpoint] == target:
return True
else:... |
import os,random
def set_init_cell_position():
for c in range(0,init_cell_number):
x,y=(random.randint(0,grid_rows-1),random.randint(0,grid_cols-1))
grid[x][y]=True
def display_grid():
global generation_counter
print 'Generation counter:',generation_counter
print
for r in range(0,grid_rows):
for c in r... |
#Ugyen Dorji, udorji@uci.edu, 83628422
#------NAVIGATION CLASSES------
import MapQuestAPI
MQ=MapQuestAPI
class STEPS:
def calculate(result:dict)->str:
'''
Finds the directions by iterating through a series of nested dictionaries and lists
till it finds the needed information ... |
def reverse_concatenate (a, b, c):
new_string = c[::-1] + b[::-1] + a[::-1]
return new_string
string1 = input('Enter first string: ')
string2 = input('Enter second string: ')
string3 = input('Enter third string: ')
print(reverse_concatenate (string1, string2, string3))
|
# TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# We need to set up a base case, which will be the way we exit the function. At what point do we want to exit? Should be simple and we should be moving towards it
if end >= start: # As long the end poin... |
"""
Clase 2
@SantiagoDGarcia
"""
def suma (a,b):
return a+b
def producto (a,b):
return a*b
def disparador (f,a,b):
print (f(a,b))
disparador (producto, 1, 10) |
friend = ["Rolf", "Bob", "Anne"]
family = ["Jen", "Charlie"]
user_name = input("Enter your name: ")
if user_name == "Anderson":
print("Hello, Master!")
elif user_name in friend:
print("Hello, friend!")
elif user_name in family:
print("Hello, family!")
else:
print("I don't know you!") |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Authors: tongxu01(tongxu01@baidu.com)
Date: 2017/8/20
"""
import os
import sys
import time
from subprocess import PIPE
from subprocess import Popen
"""
Python-Tail - Unix tail follow implementation in Python.
python-tail can be used to monitor changes to a file.
"""
... |
# coding=utf-8
__author__ = 'xyc'
# The Command Pattern is used to encapsulate commands as objects. This
# makes it possible, for example, to build up a sequence of commands for deferred
# execution or to create undoable commands.
# 讲一个请求封装为一个对象,从而是你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
class Grid:
def __init... |
# if you want to scrape a website :
# 1. using api
# 2. html web scraping using some tool like bs4
# step 0 :
# install these:
# pip install requests
# pip install bs4
# pip install html5lib
import requests
from bs4 import BeautifulSoup
url = "https://codewithharry.com"
# step 1 : get the html
r = req... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy=ListNode(0)
dummy.next=head
slow=fast=dummy
for... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
end=len(nums)-1
i=0
while i<=end:
if nums[i]==0:
num... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(l,r):
if r is None and l is Non... |
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
res=[]
if len(word1)>len(word2):
length=len(word2)
else:
length=len(word1)
for i in range(0,length):
res.append(word1[i])
res.append(word2[i])
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def suc(self,root):
root=root.right
while root.left:
root=root.left
... |
#Testing re.split
import re
import unittest
# string = 'hi'
# #newstring = re.split(r'(\d*)$', string2, maxsplit=2)
# newstring = re.search('(\d*)$', string)
#
# end_number = int((newstring.group(1)) + 1 if newstring.group(1) else 1)
# print(re.split('(\d*)$', string)[0] + str(end_number))
# #newstring[1] = int(newstr... |
'''异常处理
def test(x,y):
try:
return x/y
except ZeroDivisionError:
print('0不可除')
except TypeError:
print('类型错误')
finally:
print('结束')
print(test(4,1))
print(test('111','222'))
'''
'''迭代器
from collections.abc import Iterable
print(isinstance('test',Iterable))
strItr=iter('te... |
# Pandigital prime
# Problem 41
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
# What is the largest n-digit pandigital prime that exists?
from common import is_prime
import itertools
def pandigit... |
# coding: utf-8
# Pandigital products
# Problem 32
# We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
# The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, mul... |
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples_of_3_or_5(below):
i = 3
while i < below:
if i % 3 == 0 or i % 5 == 0:
... |
# Summation of primes
# Problem 10
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#
# Find the sum of all the primes below two million.
from common import PrimeGenerator
def solve():
g = PrimeGenerator(2_000_000)
return sum(g)
if __name__ == '__main__':
print(__file__ + ": %d" % solve())
|
#P = Loan Principal
#J = Monthly Interest Rate (Annual Rate / 1200)
#N = Number of Months (Years * 12)
#M = Monthly Payment
#V = Value of House
#eightyPercent = 80% of the value of the home
#H = Monthly Interest Payment
#C = Monthly Principal Payment
#Q = New Principal Balance
#PMIPmt = PMI Payment
#T = Monthly Tax
P =... |
############################################################################
# Binary classification: Classify movie reviews as positive or negative
# Used IMDB dataset from keras
# This exercise is from the book Deep Learning with Python
# Now we are trying to deal with the overfitting issue by
# reducing th... |
def fancy_divide(numbers,index):
try:
denom = numbers[index]
for i in range(len(numbers)):
numbers[i] /= denom
except IndexError:
print("-1")
else:
print("1")
finally:
print("0")
###
def fancy_divide(list_of_numbers, index):
try:
... |
# a1.py - Jason Leung
import random
import sys
import time
from search import *
from collections import deque
state = []
# Take command line argument input from user if it exists
if (len(sys.argv) == 10):
for i in range (1, 10):
state.append(int(sys.argv[i]))
else:
state = [1, 2, 3,
4,... |
#import libraries
import random
import time
#set up global variables
board = ['Go', 'Mediterranean Avenue', 'Baltic Avenue', 'Reading Railroad','Oriental Avenue', 'Jail']
property_info = {'Mediterranean Avenue':{'cost':100,'rent':50,'ownerID':0},'Baltic Avenue':{'cost':150,'rent':60,'ownerID':0}, 'Reading Railro... |
#!/usr/bin/python3
MAX = 1000000
chain_map = {}
def collatz_sequence(n):
return n // 2 if n % 2 == 0 else 3 * n + 1
def get_chain_count(n):
if n == 1:
chain_map[n] = 1
return 1
elif n in chain_map != None:
return chain_map[n]
else:
res = 1 + get_chain_count(collatz_seq... |
#!/usr/bin/python3
from math import sqrt
def get_prime_factors(nb):
lpf = 0
while nb % 2 == 0:
lpf = 2
nb /= 2
for f in range(3, int(sqrt(nb)) + 1, 2):
while nb % f == 0:
lpf = f
nb /= f
if nb > 2: # nb is prime
lpf = nb
return lpf
print(get... |
#!usr/bin/python3
#"this is basic recursive web crawler that will traverse every url\ link in certain domain "
import urllib.request as r
from bs4 import BeautifulSoup as bs
import sys
import urllib.parse as parse
def scanner (soup): #the function that will scan urls
global unvisited,visited,inp
#if f... |
'''
Prove 3 - scene.py
Abi Priebe
5/8/21
'''
'''
During this lesson, you will write code that draws the sky, the ground, and clouds.
During the next lesson, you will write code that completes the scene. The scene that
your program draws may be very different from the example scene above. However, your
scene must be ... |
'''
Checkpoint 1 - heart_rate.py
Abi Priebe
4/22/21
'''
'''
When you physically exercise to strengthen your heart, you should maintain your heart rate within a range for at
least 20 minutes. To find that range, subtract your age from 220. This difference is your maximum heart rate per
minute. Your heart simply will ... |
#!/usr/bin/python
from sys import stdin
from keyword import iskeyword
if __name__ == "__main__":
n = input()
n_list = list(n)
n_sum = 0
finished = False
for i in n_list:
n_sum += int(i)
if n_sum % 3 == 0:
finished = True
print(0)
else:
sum_remain = n_sum % ... |
#!/usr/bin/env python
# coding: utf-8
# In[19]:
import pandas as pd
import numpy as np
df=pd.read_csv('bankdata.csv')
# In[20]:
df.drop('Unnamed: 0',axis=1,inplace=True)
# In[21]:
X=df.drop('default',axis=1)
# In[22]:
y=df['default']
# In[23]:
from sklearn.linear_model import LogisticRegression
lr=Lo... |
import tkinter
from tkinter import *
from tkinter import messagebox
root=tkinter.Tk()
def btn_is_clicked():
messagebox.showwarning("Warning", "This is info window")
root.geometry('400x500')
Button(
root,
text='Click here',bg='#000000',
fg='#ffffff',width=20,height=2, command=btn_is_clicked).pack()
root... |
# READING FROM FILE
employee_file = open("employees.txt", "r") # opens file read mode
print(employee_file.readable()) # checks file is readable
#print(employee_file.read()) # reads entire file to screen
#print(employee_file.readline()) # can be used multiple times to read next line in file
#print(employee_file.read... |
import os
"""os.walk returns the root folder you want to check use in a for loop
returns 3 values; name of folder, its subfolders as a list and list of files in folder"""
for folderName, subfolders, filenames in os.walk('/Users/kj/Desktop/Certificates/Automate the Boring Stuff'):
print('The folder is ' + fold... |
# import pretty print to make nicer output
import pprint
# We want to count the number of characters in a string
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
# make a dictionary
count = {}
# We loop over the characters in the string
for character in message.upper():
# i... |
row=0
while row<5:
c=0
while c<=row:
print("*",end=" ")
c=c+1
print()
row=row+1
|
num=int(input("enter the num"))
num1=int(input("enter the num"))
if num>num1:
a=num
else:
a=num1
while True:
if a%num==0 and a%num1==0:
print(a)
break
a=a+1 |
total = 0
number_items = int(input("Number of items:"))
while number_items < 0:
print("Invalid number of items!")
number_items = int(input("Number of items:"))
for i in range(number_items):
price = float(input("enter price of items:"))
total += price
if total > 100:
total *= 0.9
print("Total price f... |
"""Class that contains information on each piece of weather data"""
class WeatherData:
def __init__(self, wban, year_month_day, t_max, t_min, t_avg, station, location):
self.wban = wban
self.year_month_day = year_month_day
self.t_max = t_max
self.t_min = t_min
self.t_avg = t... |
# 15-112: Principles of Programming and Computer Science
# Project: AI based Ludo
# Name : Swapnendu Sanyal
# AndrewID : swapnens
# File Created: November 6, 2017
# Modification History:
# Start End
# 27/10 14:30 27/10 20:00
# 30/10 21:05 19/10 22:08
###########... |
with open('input.txt', 'r') as f:
data = f.read().split()
def row_num(row):
"""
decodes first 7 chars and returns the row number using bisection search
"""
max_r = 127
min_r = 0
for char in row:
if char == 'F':
min_r = min_r
max_r = (max_r + min_r) // 2
... |
from collections import defaultdict
from queue import PriorityQueue
import math
class Node:
def __init__(self, data):
self.data = data
self.visited = False
def __repr__(self):
return f'Node({self.data})'
def __lt__(self, other):
return self.data < other.data
def __eq... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class ReverseInK:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next or k == 1:
return head
dummy = ListNode()
dummy.next = head... |
from typing import List
class NextPermutation:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead
"""
i = len(nums) - 2
while i >= 0 and nums[i + 1] <= nums[i]: # find first decreasing element from the end
... |
import heapq
from typing import List
class KClosestPointsToOrigin:
# We keep a min heap of size K.
# For each item, we insert an item to our heap.
# If inserting an item makes heap size larger than k, then we immediately pop an item after inserting (heappushpop).
# Runtime:
# Inserting an item to... |
class LRUCache:
def __init__(self, capacity: int):
self.size = capacity
self.cache = {}
self.next = {}
self.before = {}
self.head, self.tail = '#', '$'
self.connect(self.head, self.tail)
def connect(self, a, b):
self.next[a], self.before[b] = b, a
d... |
class LongestPalindrome:
def longestPalindrome(self, s: str) -> str:
res = ""
for i in range(len(s)):
# odd case, like "aba"
temp = self.helper(s, i, i)
if len(temp) > len(res):
res = temp
# even case, like "abba"
... |
from typing import List
class MergeSortedArray:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead
"""
p1 = m - 1
p2 = n - 1
p = m + n - 1
while p1 >= 0 and p2 >= 0:
... |
# The user enters 10 numbers.
# Numbers displayed - odd numbers
list = []
for number in range(10):
number = int(input('Proszę o podanie cyfry:'))
number = round(number)
if number % 2 != 0:
list.append(number)
print(f'Odd numbers: {list}.') |
#Celsjusz → Fahrenheit. The program is done in a loop from 0 to 200 Fahrenheit, every 20.
#C = 5/9 * (F - 32) # formula Celsius → Fahrenheit
#Write a solution using while / for.
print('.' * 84)
for c in range(0, 200, 20):
cz = 5 / 9 * (c - 31)
print(f'Temperature in degrees Fahrenheit: {c} | Tempera... |
# Create a list.
# The list has dictionary values without duplicates.
days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30}
daysList = days.values()
daysList = list(daysList)
for k in daysList:
daysList.remove(k)
print(daysList) |
# Create a multiplication table as a nested list 10 x 10 list. Table has row x column multiplication results.
width = 50
print('-' * width)
for k in range(1,11):
for m in range(1,11):
print(f'{k * m:^4}', end='|')
print()
print('-' * width) |
# The program asks the user for 4 digits
# then returns the sum of the numbers
print("------------------ SUM OF NUMBERS ------------------")
a, b, c, d = input('Enter 4 digits (separated by spaces): ').split(" ")
print(f'Numbers entered: {a}, {b}, {c}, {d}')
firstNumber = int(a)
secondNumber = int(b)
third... |
# Make an integer tuple.
# The user gives any number.
# If the number is in the program, the program will display the index..
tuple = (1, 2, 3, 4, 5, 6, 7)
number = int(input('Enter the number: '))
if number in tuple:
print(f'Digit index: tuple.index(l)') |
"""
Advantages of Functional programming:
- Modularity: Writing functionally forces a certain degree of separation in solving your problems
and eases reuse in other contexts.
- Brevity: Functional programming is often less verbose than other paradigms.
- Concurrency: Purely functional functions are thread-safe and ... |
def selection_sort(arr):
for i in range(len(arr)):
max = 0
for j in range(len(arr)-i):
if arr[j] > arr[max]:
max = j
tmp = arr[len(arr)-1-i]
arr[len(arr)-1-i] = arr[max]
arr[max] = tmp
return arr |
def bubble_sort(arr):
count = 0
for i in range(len(arr)-1):
for j in range(len(arr)- i - 1):
count += 1
if arr[j] > arr[j+1]:
tmp = arr[j+1]
arr[j+1] = arr[j]
arr[j] = tmp
return arr, count
def short_bubble_sort(arr):
count... |
def justify(words, K):
begin = 0
res = ""
while begin < len(words):
end = begin + 1
count = len(words[begin])
while end < len(words):
if count + len(words[end]) + 1 > K:
break
count += len(words[end]) + 1
end += 1
if end == len(words):
res += words[begin]
for ... |
import math
# Also return closest if not found
def binary_search(arr, val, begin=None, end=None):
if begin is None:
begin = 0
if end is None:
end = len(arr) - 1
if begin >= end:
return end
mid = math.ceil((end - begin) / 2) + begin
print(begin, mid, end)
if arr[mid] == v... |
#a problem I saw where you have a list of values and you want to figure out if a pair of numbers in that list equals a particular sum
#Need a way to track the last move made and not to repeat that once I find a match
def find_pairs(sum, listofnumbers):
left = 0
right = len(listofnumbers) - 1
left_move = Fa... |
#coding:utf-8
def fence_Crypto(msg,priority="row"):
'''
usage:
fence_Crypto(msg[, priority]) ---> to encrypt or decrypt the msg with fence crypto
args:
msg:
a plaintext which will be crypted or a ciphertext which will be decrypted
priority:
row priority or col... |
import random
play=("rock" , "paper" , "scissor" )
game=random.choice( play )
print(game)
user= input(" enter rock , paper , or scissor " )
#while :
if (game==user) :
print ("tie")
while (user!=game) :
if (user=="rock") :
if game=="paper" :
print (" the computer wins the game " )
break
... |
#!/usr/bin/env python
from timer import Timer
from collections import deque
import matplotlib.pyplot as plt
def test_list(timer, iterations):
"""Appends twice & pops form a list for the given number of iterations"""
timer.start()
a = list()
for i in range(iterations):
a.append(i)
a.a... |
import pandas as pd
import numpy
def load_datagrid(data_as_csv):
return pd.read_csv(data_as_csv)
def sort_dataframe(smaller_dataframe: pd.DataFrame):
#NOTE: Sorts the dataframe's values in ascending order based on all columns
smaller_2darray = smaller_dataframe.to_numpy()
# smaller_2darray = smaller_2darray[s... |
class Node:
def __init__(self,item):
self.item = item
self.proximo = None
def __str__(self):
return str(self.item)
class Stack:
def __init__(self):
self.top = None
self._tamanho = 0
def push(self, item):
novo = Node(item)
novo.proximo = self.top
self._tamanho += 1
self.top = novo
def pop(se... |
#Pig latin by Nosa ...
vowel = ['a', 'e', 'i', 'o', 'u', 'y']
total = []
worde = raw_input("Give me a word!").lower().strip()
words = worde.split()
for word in words:
if not word.isalpha():
print(word + " is not a word")
else:
check = [1 if char in vowel else 0 for char in word]
same = (... |
day07回顾:
元组 tuple
元组的运算等于列表的运算
元组是不可变量的序列
字典 dict
可变的容器
键-值对方式进行映射存储
空典的存储是无序容器
添加/修改 字典的元素
字典[键] = 表达式返回值
删除
del 字典[键]
查看:
字典[键]
支持迭代访问
可迭代对象用处:
for 语句
各种推导式: 列表,字典,集合
... |
#先假设没有'a'这个字符
cnt = 0
s = input("请输入任意字符生成字符串")
for c in s:
if c == 'a':
cnt += 1
print('a的个数是', cnt)
print("此时c变量的值为", c) |
# 2.给出一个数n,打印0+1+2+3+.....+n的值
# 说明:争取用函数来做
n = int(input('输入数字'))
def mysum(n):
y = 0
for x in range(n + 1):
y += x
return y
print(mysum(n)) |
# 2. 输入一个字符串,把输入的字符串中的空格全部去掉.
# 打印出处理后的字符串的长度和字符串内容
def huiwen():
s = input("请输入字符串: ")
r = s.replace(' ', '#')
print(r)
print(r[::-1])
if r == r[::-1]:
return True
return False
print(huiwen())
|
#方法1
d = {}
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
for i in range(len(list2)):
d[list1[i]] = list2[i]
print(d)
#引申思考
# list1 和 list2 不等长怎么办
#1
d = {}
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
times = min(len(list1), len(liest2))
for i in range(times):
d[list1[i]] = list2[i]
#2
d = {}
list1 = ['a', 'b', 'c'... |
import time
def alarm(h, m):
while True:
cur_time = time.localtime() # 得到本地时间
print("%02d:%02d:%02d" % cur_time[3:6],
end='\r')
time.sleep(1)
# if h == cur_time[3] and m == cur_time[4]:
if (h, m) == cur_time[3:5]:
print("\n时间到....")
... |
# 4.思考题:
# 有五个朋友在一起,第五位说他比第四位大2岁,第四个人说比第三个人大2岁....第一个人10岁
# 编写程序,算出第五个人几岁
def fn(n):
if n == 1:
return 10
return 2 + fn(n-1)
print('第1个人的年龄是:', fn(1), '岁')
print('第2个人的年龄是:', fn(2), '岁')
print('第3个人的年龄是:', fn(3), '岁')
print('第4个人的年龄是:', fn(4), '岁')
print('第5个人的年龄是:', fn(5), '岁')
|
# 1.用生成器函数,生成质数,给出起始值begin和终止值stop,此生成器函数为
# prime(begin, end)
# 如果[x for x in prime(10, 20)] --> [11,13,17,19]
# 练习使用yield
# 方法1
# def isprime(n):
# for x in range(2, n):
# if n % x == 0:
# return False
# return True
# def prime(begin, end):
# for a in range(begin, end):
# ... |
# if.py
# 输入一个数,判断这个数是奇数还是偶数,并打印出来
# x = int(input("请输入一个整数: "))
# if x % 2 == 1:
# print(x, '是奇数')
# else:
# print(x, '是偶数')
def Judge_the_odd_and_even():
x = int(input("请输入一个整数: "))
if x % 2 == 0:
return '偶数'
else:
return '奇数'
print(Judge_the_odd_and_even()) |
# 练习:
# 1. 已知矩形的长边长6cm,短边长4cm,用表达式求周长和面积
# 并打印出来
# print("周长是:", (6 + 4) * 2, 'cm')
# print("面积是:", 6 * 4, '平方厘米')
x = 6
y = 4
print('c=',eval('(x+y)*2'),'cm')
print('s=',eval('(x*y)'),'平方厘米') |
# # global2.py
# v = 100
# def fn():
# v = 200 # 不建议在global之前来创建局部变量
# print(v)
# # global v
# v = 300
# print(v)
# fn()
# print('v=', v) # 200
# static_method.py
#1
class A:
#@staticmethod
def myadd(self,a,b):
return a + b
a = A() # 创建实例
print(a.myadd(100, 200)) # 300... |
# 制作一个地图
map2048 = [[2, 0, 2, 4],
[2, 2, 4, 4],
[4, 8, 8, 2],
[0, 8, 4, 2]]
def _remove_zero(L):
'''删除列表里的零'''
try:
while True:
i = L.index(0) # index函数为在列表中寻找0,如果没有零则返回一个ValueError
L.pop(i)
except ValueError:
pass
def _left_shift(L):
# ... |
from utils import read_from_file, write_to_file
def naive_search(string: str, substring: str, case_insensitive: bool = False) -> list[int]:
occurrences: list[int] = []
if case_insensitive:
string, substring = map(str.lower, (string, substring))
for i in range(len(string) - len(substring) + 1):
... |
def isFirst_And_Last_Same(numberList):
firstElement = numberList[0]
lastElement = numberList[-1]
if(firstElement == lastElement):
return True
else:
return False
numList = [10, 20, 30, 40, 10]
print("The first and last number of a list is same")
print("result is", isFirst_And_Last_Same(nu... |
"""
__echoes__
~~~~~~~
Functions of typer.echo() and typer.secho() function
FUNCTIONS
~~~~~~~
echo_file_not_found
echo_file_created
echo_file_exist
echo_file_empty
echo_file_found
echo_file_error
echo_file_valid
echo_cmd_changed
echo_cmd_added
generate_path
... |
class Cuadruplo():
def __init__(self, numCuadruplo, operador, operandoIzq, operandoDer, resultado):
self.numCuadruplo = numCuadruplo
self.operador = operador
self.operandoIzq = operandoIzq
self.operandoDer = operandoDer
self.resultado = resultado
#Llena el salto para ir a otro cuadruplo
def LlenaResultado... |
####################################################################
# Copyright (C) Rocket Software 1993-2017
# Geocoding example: Calculate coordinates of a street address
# using Google MAPS API and response in JSON format
# Input is a "postal address" in the form of a human-readable address string and
# an indicati... |
import sqlite3
import csv
CSV_file = 'db_export_file.csv'
conn = sqlite3.connect('first_db.db')
c = conn.cursor()
export_list = []
headers = ["First Name", "Last Name", "Profession", "Age"]
for row in c.execute('SELECT * FROM people ORDER BY age'):
export_list.append(row)
with open(CSV_file, 'w') as ex... |
# general format
##
##a = 0
##b = 5
##while a < b:
## a += 1
## print (a)
##else:
## print("Does the else print?")
## print("Yes. Yes it does, because it never hit a break")
##a = 0
##b = 5
##while a < b:
## a += 1
## print (a)
## break
##else:
## print("Does the else print?")
## print("Yes. Yes... |
###itertools
####from itertools import *
##
### create a new iterator
###syntax: iterttols.count(start,step)
##
###this would go on forever
####x = count(10)
####for i in x:
#### print(x)
##
### but done this way
### it would start at 2, end at but dont include 10
##
####for num in islice(count(), 2, 10):
#### pr... |
# timedelta
from datetime import timedelta, datetime, date
##print(timedelta(days=365))
##print("today is: " + str(datetime.now()))
##print("30 days from day will be:" + str(datetime.now() + timedelta(days=30)))
##print("60 days from day will be:" + str(datetime.now() + timedelta(days=60)))
##print("90 days ago was: "... |
"""
Sprites in Point of No Return
"""
from enum import Enum
from math import atan2, pi
import pygame
from pygame.sprite import Sprite
import src.constants as constants
import src.utils as utils
class Direction(Enum):
"""
An enum that represents the four directions. Evaluated to a tuple of two
ints, which ... |
"""
Controllers for Point of No Return
"""
from abc import ABC, abstractmethod
import pygame
import src.constants as constants
from src.constants import MOVES
from src.sprites import Direction
class Controller(ABC):
"""
Controls sprites in the game
Attributes:
_game: an instance of Game to update... |
# MY FIRST ATTEMPT
# import calendar
#
# year_one = 2017
# year_two = 2020
#
# month_one = 5
# month_two = 11
#
# date_one = 9
# date_two = 27
###############################################################################
# MY SECOND ATTEMPT AFTER VIEWING THE SOLUTION
from datetime import date
first_date = date(2020,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.