blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
8916e63c5a3365c2a7860d4b8e6b221b86fb25c6 | xumaxie/pycharm_file-1 | /Algorithma and Data Structures/图解算法数据结构/10剑指offer59滑动窗口的最大值(作者的方法).py | 1,920 | 3.515625 | 4 | #@Time : 2021/11/721:09
#@Author : xujian
# 本题难点: 如何在每次窗口滑动后,将 “获取窗口内最大值” 的时间复杂度从 O(k)降低至 O(1)。
# Python 通过 zip(range(), range()) 可实现滑动窗口的左右边界 i, j 同时遍历。
# 时间复杂度 O(n)O(n)O(n) : 其中 nnn 为数组 numsnumsnums 长度;线性遍历 numsnumsnums 占用 O(n)O(n)O(n) ;每个元素最多仅入队和出队一次,因此单调队列 dequedequedeque 占用 O(2n)O(2n)O(2n) 。
# 空间复杂度 O(k)O(k)O(k... |
110c2ed76ba72599dc12ac9bbdb992233935d986 | xumaxie/pycharm_file-1 | /Algorithma and Data Structures/图解算法数据结构/03剑指offer09用两个stack实现Queue.py | 1,931 | 3.796875 | 4 | #@Time : 2021/11/211:22
#@Author : xujian
# Question:
# 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,
# 分别完成在队列尾部插入整数和在队列头部删除整数的功能。
# (若队列中没有元素,deleteHead 操作返回 -1 )
from typing import List
class CQueue:
def __init__(self,s1:List[int],s2:List[int]):
self.s1=s1
self.s2=s2
... |
b82acd649cbce927bfee671291ae065aac1ed405 | xumaxie/pycharm_file-1 | /Algorithma and Data Structures/图解算法数据结构/09剑指offer58左旋转字符串.py | 861 | 3.84375 | 4 | #@Time : 2021/11/68:36
#@Author : xujian
# 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
# 请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,
# 该函数将返回左旋转两位得到的结果"cdefgab"
# 我的方法与作者的第二个一样
#作者的三个方法:字符串切片 , 列表遍历拼接 , 字符串遍历拼接
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
if not s:return
if... |
2ebb6ab66046326520ce21d84e5617ae771aed7d | xumaxie/pycharm_file-1 | /Algorithma and Data Structures/图解算法数据结构/05剑指offer翻转链表(作者).py | 653 | 3.921875 | 4 | #@Time : 2021/11/221:20
#@Author : xujian
class ListNode():
def __init__(self,val):
self.val=val
self.next=None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
tmp = cur.next # 暂存后继节点 cur.next
cur.next ... |
459e46558d82ce081f60b27b9f1cc5531a3158a8 | pilagod/leetcode-python | /002.py | 965 | 3.5625 | 4 | __author__ = 'pilagod'
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(l1, l2):
addone = False
head = l1
while(l2 is not None):
l1.val = l1.val + l2.val + (1 if addone else 0)
if l1.val >= 10:
addone = True
... |
b01750894a6880eede69f3ac59f44c7b2c5ce499 | pilagod/leetcode-python | /336.py | 937 | 3.5 | 4 | class Solution(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
dict = {}
result = []
for i in range(len(words)):
dict[words[i]] = i
for i in range(len(words)):
for j in range(l... |
9054614257b01d1128ef68fcb1a9a80bae676bf1 | cblanc3666/Word-Salad-Bot | /moikoalBot.py | 1,643 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 01:18:33 2020
@author: chase
"""
# bot.py
import discord
# note: I store the token in a separate text file for security purposes
# I have uploaded the text file (token.txt) it to the git repository
# This is okay because the git repository is private
# THE TOKEN MUS... |
b56d7a6fe43829ead5c2949946f863c3fa258440 | ZainPain/Mnist-Neural-network | /deepnet.py | 2,910 | 3.609375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def constant():
x1 = tf.constant([5])
x2 = tf.constant([6])
#result = x1 * x2
result = tf.multiply(x1,x2)
#sess = tf.Session()
#print(sess.run(result))
#sess.close()
with tf.Session() as sess:
output = sess.run(result)
pri... |
88db8f87b369d7626c0f2e0466e60cc73b1d11cc | BrettMcGregor/coderbyte | /time_convert.py | 499 | 4.21875 | 4 | # Challenge
# Using the Python language, have the function TimeConvert(num)
# take the num parameter being passed and return the number of
# hours and minutes the parameter converts to (ie. if num = 63
# then the output should be 1:3). Separate the number of hours
# and minutes with a colon.
# Sample Test Cases
#
# Inp... |
6eb3619bec8465aab552c5ad9043447217d81334 | BrettMcGregor/coderbyte | /check_nums.py | 578 | 4.1875 | 4 | # Challenge
# Using the Python language, have the function CheckNums(num1,num2)
# take both parameters being passed and return the string true if num2
# is greater than num1, otherwise return the string false. If the
# parameter values are equal to each other then return the string -1.
# Sample Test Cases
#
# Input:3 &... |
1c798e8857ccfb63586c7373d8d3d45c6853e52c | YakunAlex/MIPT-Python-NewsBot | /s_graphics.py | 1,152 | 3.578125 | 4 | import matplotlib.pyplot as plt
def plot(x, y, title, xlabel, ylabel, file):
"""
Построение графика
:param x: разметка по х-координате
:param y: разметка по у-координате
:param title: название графика
:param xlabel: название х-координаты
:param ylabel: название у-координаты
:param file... |
419d361407ebf8cbd3764e704f49d76d6f084463 | Ederbal/python_algoritmos | /lista/idades.py | 311 | 4 | 4 | continuar = True
idades = []
while continuar:
idade = int(input('Digite uma idade: '))
idades.append(idade)
opcao = input('Deseja digitar outra idade (S/N): ')
continuar = (opcao == 'S')
maior = 0
for idade in idades:
if idade > maior:
maior = idade
print('Maior: '+str(maior))
|
68dd818afd4b688616d5bd4fa773a578ec3b0df1 | Ederbal/python_algoritmos | /2016.1/exercicios/estagio2/q2.py | 232 | 3.84375 | 4 | numero = int(input('Digite um número: '))
primo = True
for num in range(2,numero):
if (numero % num) == 0:
primo = False
break
if primo:
print(numero, "é primo!")
else:
print(numero, "não é primo!") |
b27ab7123dcfff79d8eaef9ece1b64d5949483e5 | wesley-cantarino/Python | /ESTUDO/brincando.py | 1,118 | 4.03125 | 4 | """
#parecido com scanf do C
X = int(input("Digite aqui: "))
X = X**2
print("valor digitado ao quadrado foi: ", X)
"""
"""
#if else
X = int(input("digite um valor: "))
Y = int(input("digite outro valor: "))
print("\n\n\n")
if X > Y:
print("O primeiro valor (", X,") eh maior que o segundo(", Y, ")")
elif X < Y:
... |
befa8495a5bf606793d0fc325541c9fd3f255751 | mgar216/leetcode | /LC20_Valid_Parenthesis.py | 667 | 3.796875 | 4 | """
Runtime: 28 ms, faster than 83.24% of Python3 online submissions for Valid Parentheses.
Memory Usage: 14.1 MB, less than 95.25% of Python3 online submissions for Valid Parentheses.
"""
class Solution:
def isValid(self, s: str) -> bool:
if not s or len(s) & 1:
return False
match = {
... |
2b5c549ea6ff3ee9ec98c52340bb3787d545bc31 | ArifFokka/basic_algoritm | /roots_of_quadratic_equation.py | 341 | 3.890625 | 4 | #quadratic equation ax2+bx+c=0.
from math import sqrt
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
D=b**2 - 4*a*c
if D>=0:
x1=(((-b)+sqrt(D)) /(2*a))
x2 = (((-b) - sqrt(D)) / (2 * a))
print(x1, 'and', x2, 'as root')
else:
rp=b/(2*a)
ip=sqrt(-D)/(2*a)
print(rp+ip,'and... |
82b619e2a7981347fd9baba00cc9ea1a4ce5fca1 | cnishina/address-locator-py | /lib/locator/location.py | 1,492 | 3.828125 | 4 | import json
class Location(object):
"""The location model that includes network information."""
def __init__(self, **kwargs):
"""The location object.
Args:
name: Location name of the this machine.
"""
# The name to associate with this location.
self.name = None
if 'name' in kwargs:
... |
b00b6e62413c8b6bc7fab1f0498fca36bf98e968 | Tantatorn-dev/2DdataStructure | /2D_dataStructure_L3Q1.py | 687 | 3.65625 | 4 | #lab test 3rd
# dataStructure
# by CXZ
# 1st December 2018
# start 8:27 PM
# @NoThaankCafe with Pejoable and suugar
list = [-1,8,3,1,9,11,15,20,6,4,9]
def insertion(l):
ans = []
for i in range(len(l)):
#print('consider->',l[i])
print('pass #',i,end ='\t-> ')
index =... |
88c627627f22eacff1b7083e07341d678897b610 | Tantatorn-dev/2DdataStructure | /2D_dataStructure_L1Q3.py | 1,930 | 3.5 | 4 | # problem #2
# Linklist LL = 5->5->2->3->0->3->4->4->7->7->5->4->8->9
# p = delRepeat(LL)
# result p = 2->0->8->9
# **** DO NOT IMPLEMENT LINKLIST CLASS ***
# *** CAN USE ONLY NODE CLASS(data,next) ***
# start 2:47 AM
# 9/22/2018
# by CXZ
class node:
def __init__(self,data,next = None ):
se... |
adef6d32e3da74f562d5d567fa0fe514c0eccd0d | mzietara/University-Textgame | /University Adventures.py | 8,813 | 3.90625 | 4 | from random import choice, randint, shuffle
import sys
import os
from time import sleep
def char_setup(s):
'''This is the process of setting up the character that will be used. Return
a list that contains the character name, starting level, starting health,
and starting damage.'''
name ... |
c4c3967177cdd35ad20f214028366dea27aa965b | heber77/ProjetoPOO | /Classes_do_sistema/Aluno.py | 2,402 | 3.546875 | 4 | from Pessoa import Pessoa
import string
from random import choice
class Aluno(Pessoa):
def __init__(self, nome, cpf, data_de_nascimento, email, telefone, senha):
super().__init__(nome, cpf, data_de_nascimento, email, telefone)
self.senha = senha
self.codigo = self.geraCodigo()
self.... |
db1137aead8baca434f8a9cbad1d747ad2cda4c5 | Yabde/backend | /level3/model/Cars.py | 526 | 3.671875 | 4 | class Cars:
"""Class Car"""
def __init__(self, attributes_dict):
"""Constructor
:param attributes_dict: Dictionnary with all class instances in the Json file
"""
self.id = attributes_dict["id"]
self.price_per_day = attributes_dict["price_per_day"]
self.price_per... |
af0504dc13382cd101a41dc5bb30c81f8dfa96cf | harman31/TwilioQuest | /branching.py | 309 | 3.59375 | 4 | import sys
first_num = int(sys.argv[1])
second_num = int(sys.argv[2])
sum_to_use = first_num + second_num
if sum_to_use <= 0:
print('You have chosen the path of destitution.')
elif sum_to_use <= 100:
print('You have chosen the path of plenty.')
else:
print('You have chosen the path of excess.') |
be82c313cb9bab4da6388c9d0c0ddef0e7bec0a6 | khchan/Project-Euler | /python/PE_06.py | 539 | 3.59375 | 4 | #The sum of the squares of the first ten natural numbers is,
#12 + 22 + ... + 102 = 385
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10)2 = 552 = 3025
#Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.
#Find... |
1f67cd39d6061e1c7689691feb32b1585329540f | khchan/Project-Euler | /python/PE_20.py | 362 | 3.96875 | 4 | #n! means n * (n - 1) ... 3 * 2 * 1
#For example, 10! = 10 * 9 ... 3 * 2 * 1 = 3628800,
#and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#Find the sum of the digits in the number 100!
from math import factorial
sum = 0
length = len(str(factorial(100)))
for i in range(0, length):
su... |
eaaf5bc8157525092e36f5539cd347e4278a4af3 | ajay6763/Mantle_Composition_from_Melting_model | /mg_number.py | 398 | 3.671875 | 4 |
MgO =input('Enter MgO wt%: ')
ans =input('Do you have FeO--1 or Fe2O3--2 (choose 1 or 2 ):')
FeO =input('Enter FeO wt%: ')
MgO_w=40.3044
FeO_w=71.844
if ans==1:
mg_No= ((MgO/MgO_w)/((MgO/MgO_w)+(FeO/FeO_w)))*100
print( 'Mg number FeO',mg_No)
elif ans==2:
## Need to conver Fe2O3 to Feo
FeO= FeO*0.8998
mg_No= ... |
416343cbf9715f86e75e484e7e83ba6fb634a877 | Us-manArshad/Python_CSV | /main.py | 3,483 | 3.84375 | 4 | # Find the hottest/Coldest temp of every month and overall data
import os
class Weather():
# Method to find hottest and coldest temperature from all files
def search_all_files(self, DATA_DIR, max_temp, min_temp):
max_months_list = []
min_months_list = []
for filename in os.listdir(DAT... |
1a30e11b29054dbe3d24ac62d9d861edfc308b69 | jimrahman/problem-solving | /test.py | 708 | 3.90625 | 4 | data = "mom"
def palendrom(name):
reverseName = ''
for i in range(len(data)):
reverseName += data[-i-1].upper()
if name.upper() == reverseName.upper():
print("palendromic")
else: print("Not palendromic")
data = "mom"
unique = set(data)
unique.update("dog", "god")
print(unique)
... |
b5457cdddf6f92abb9d32e1aef2e7a168320209c | jmarsh12/cse210-tc08 | /batter/game/Brick.py | 572 | 3.875 | 4 | """
Craig
"""
from game.actor import Actor
from game.point import Point
class Brick(Actor):
"""An actor in the batter game. Brick inherits from Actor.
Attributes: Point: the position on the screen
Velocity: the speed it is moving; always set to zero
Text: visual representation... |
1645c0e1b348decce12680b6e3980b659f87c82a | RahulBantode/Pandas_python | /Dataframe/application-14.py | 702 | 4.40625 | 4 | '''
Write a program to delete the dataframe columns by name and index
'''
import pandas as pd
import numpy as np
def main():
data1 = [10,20,30,40]
data2 = ["a","b","c","d"]
data3 = ["jalgaon","pune","mumbai","banglore"]
df = pd.DataFrame({"Int":data1,"Alpha":data2,"city":data3})
print(df)
... |
1a5574faf02d05532e77baed63be35ba8719a0eb | RahulBantode/Pandas_python | /Series/application-6.py | 459 | 3.96875 | 4 | '''
write a prgram to calculate or to get the first and and last few rows from series
'''
import numpy as np
import pandas as pd
def main():
series = pd.Series(np.arange(1,20,1))
print("First row of series : ",series[0])
print("First few rows of series : ")
print(series.head(3))
print(... |
717593f18f04b22e4a10c90c6ae6328ab3bd42df | RahulBantode/Pandas_python | /Dataframe/application-7.py | 732 | 4.15625 | 4 | #Write a program to create a dataframe using pandas series.
import pandas as pd
import matplotlib.pyplot as plt
def main():
Author = ["Rahul","Nitin","Kunal","Mohit"]
b_price = [900,450,740,100]
Article = ["C-lang","Java-lang","Flutter","Native-core"]
auth_series = pd.Series(Author)
book_series ... |
981ef04ede97da1121d9da683149277f38e63632 | mayraguajardo/10-Days-of-Statistics-HackerRank | /quartiles.py | 602 | 3.875 | 4 | size = int(input())
numbers = sorted(list(map(int,input().split())))
def get_median(size, numbers):
if size %2 == 0:
median = (numbers[int(size/2)-1] + numbers[int(size/2)]) / 2
else:
median = numbers[int(size/2)]
return int(median)
# verifiy even or odd list
if size % 2 == 0:
data_low... |
66be53218a12e741ee9319c21b5fcb3370622cda | mayraguajardo/10-Days-of-Statistics-HackerRank | /the_central_limit_theorem_3.py | 220 | 3.734375 | 4 | import math
n = float(input())
mean = float(input())
std = float(input())
percent_ci = float(input())
value_ci = float(input())
ci = value_ci * (std / math.sqrt(n))
print(round(mean - ci,2))
print(round(mean + ci,2)) |
141abe7dfe844acd5ce5f999880197ce266a2865 | ziyadedher/birdynet | /src/game/strategy.py | 2,091 | 4.1875 | 4 | """This module contains strategies used to play the game."""
import random
import pygame
from game import config
class Strategy:
"""Defines an abstract strategy that can be built on."""
def __init__(self) -> None:
"""Initialize this abstract strategy.
Do not initialize an abstract strateg... |
22310ba88859c375bab506d8f334a7d129a0603c | SamuelHDieterich/Walkthrough-Python | /7 - Funções/7.2 - Parâmetros/mensagem_para_todos.py | 319 | 3.609375 | 4 | # MENSAGEM PARA TODOS
# 'mensagem' é um argumento posicional
# Tudo que vier depois vai se tornar uma lista salva em 'nomes'
def mensagem(mensagem, *nomes):
"Manda uma 'mensagem' para a lista de 'nomes'"
for i in nomes:
print(f'{mensagem}, {i}.')
mensagem('Oi', 'Carol', 'Beatriz', 'Pedro', 'Carlos') |
94826879bcf2962aba27e805d9c64825926e7158 | SamuelHDieterich/Walkthrough-Python | /2 - Tipos de dados/2.2 - Numérico/int.py | 155 | 3.84375 | 4 | # A variável 'x' recebe o valor 10
x = 10
# x = int(10)
# Retorna o valor da variável
print(x) # 10
# Retorna o tipo
print(type(x)) # <class 'int'> |
13d2ebfb6057df4d4c2ee381736ddcab47dc935f | SamuelHDieterich/Walkthrough-Python | /4 - Bibliotecas/funcao_seno.py | 364 | 3.515625 | 4 | # GRÁFICO DA FUNÇÃO SENO
# Bibliotecas
import numpy as np
import matplotlib.pyplot as plt
# Valores de x e y para o gráfico
x = np.linspace(-5, 5, 100) # Array com 100 valores indo de -5 até 5
y = np.sin(x) # Array com os valores da função seno em 'x'
plt.plot(x, y) # Gera o gráfico de linha
plt.show(... |
6225dedc0d32d327d62c52bcf99446ed232c7569 | SamuelHDieterich/Walkthrough-Python | /6 - Estruturas de repetição/6.3 - Alterar loop/pass.py | 344 | 3.65625 | 4 | # PASS
# Para 'i' de 0 até 9
for i in range(10):
# Se i for igual a 5...
if i == 5:
pass # Só ignora
print('Número é ' + str(i))
print('Fim do loop!')
# Número é 0
# Número é 1
# Número é 2
# Número é 3
# Número é 4
# Número é 5
# Número é 6
# Número é 7
# Número é 8
# Número é 9
# Fim do loop! |
214abb236635ece5146094111337f8e71ab07dcd | madhusivaraj/maze-runner | /dynamic_algo.py | 6,102 | 3.578125 | 4 | import numpy as np
import math
import random
def dynamic(initial_map, q_value): # Computes A* euclidean distance
print("INIT", initial_map)
dynamic_map=initial_map
visited=[(0,0)]
discovered = [(0,0)]
path=[]
previous={}#neighbor of current node that has smallest distance
distance={(0,0):0,... |
b3cc966f6c40c39ce405cbbe2b2f39eaf9594c77 | k501903/pythonstudy | /C03_Iterator.py | 1,388 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# 迭代
import math
import collections
# 列表
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#迭代显示
for name in L:
print(name)
# tuple
L = ('Michael', 'Sarah', 'Tracy', 'Bob', 'Jack')
#迭代显示
for name in L:
print(name)
# 字典
D = {'a':1, 'b':2, 'c':3}
#迭代显示key
for key in D... |
c21c42410636368c035790c212e1e41c925ad85e | k501903/pythonstudy | /C07_useproperty.py | 1,356 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'@property的练习'
__author__ = 'Jacklee'
# 导入模块
#import types
# 装饰器@property
class Student(object):
__slots__ = ('name', '_birth', '_age', '_score')
def Test():
pass
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not i... |
28287d94a090ac3b9643a8d652896bd534211c0d | k501903/pythonstudy | /C01_dict.py | 771 | 4.125 | 4 | # -*- coding: utf-8 -*-
# 字典dict
grades = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(grades['Tracy'])
# 添加
grades['Adam'] = 67
print(grades['Adam'])
# 修改
grades['Adam'] = 66
print(grades['Adam'])
# 删除
grades.pop('Adam')
print(grades)
# 判断是否存在
if 'Thomas' in grades:
print(grades['Thomas'])
else:
grades['Thoma... |
c65710674d3194cd7a5453a490660d898118f7b8 | k501903/pythonstudy | /C03_Iteration.py | 832 | 4.25 | 4 | # -*- coding: utf-8 -*-
# 迭代器
# 迭代对象Iterable
from collections import Iterable
print('[]是Iterable吗? ', isinstance([], Iterable))
print('{}是Iterable吗? ', isinstance({}, Iterable))
print('abc是Iterable吗? ', isinstance('abc', Iterable))
print('(x for x in range(10))是Iterable吗? ', isinstance((x for... |
d806987da2c367b50c2a80952696ba6d1028e635 | k501903/pythonstudy | /any.py | 2,058 | 3.546875 | 4 |
def lazy_range_from(up_to):
"""
生成器返回一个从0到up_to值的整数序列
"""
index = 0
def gratuitous_refactor():
nonlocal index
while index < up_to:
yield index
index += 1
yield from gratuitous_refactor()
def lazy_range(up_to):
"""Generator to return the sequence of i... |
bd548d271d365ac9eb646dbac0ae874424c30fee | k501903/pythonstudy | /C03_Slice.py | 1,127 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# 切片
import math
# 列表
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#取前三个
print('取前三个')
print(L[0:3])
#取第一个
print('取第一个')
print(L[:1])
#取后两个
print('取后两个')
print(L[-2:])
#取最后一个
print('取最后一个')
print(L[-1:])
#取1、3、5
print('取第1、3、5个')
print(L[::2])
# tuple
T = ('Michael', 'Sarah', 'Tracy', '... |
322ae861143b55bd6e1d2c5d02dad3721b03bc59 | k501903/pythonstudy | /C01_list.py | 956 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# 可以维护的有序集合
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates)
print('集合classmates的元素个数为: %d' % len(classmates))
print('集合中的第一个元素: %s' % classmates[0])
print('集合中的最后一个元素: %s' % classmates[-1])
classmates.append('Adam')
classmates.insert(1, 'Jack')
print(classmates)
classmates.pop()
c... |
fc349cfebd5bc3d9360832b989811d1847c34eb3 | guimasharing/snake_game | /snake_game.py | 3,406 | 3.609375 | 4 | import pygame
import random
GRIDS_WIDTH = 30
GRIDS_HEIGHT = 20
BLOCK = 40
BG_COLOR = (23, 126, 137)
GAME_RUNNING = True
FOOD_COLOR = (219, 58, 52)
OUTLINE_COLOR = (8, 76, 97)
SNAKE_COLOR = (255, 200, 87)
FONT_COLOR = (8, 76, 9)
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
TICK = 5
class Snake(object):
... |
75451e59e43dbf55b87c717cfd88809aa1b78746 | edxz7/GameTreeSolver-N-puzzle-game-Artificial-Inteligence | /board.py | 5,079 | 4.25 | 4 | import random
from typing import Final
# *****************************************************************************
# Execution: none
# Dependencies: nonez
# Representation of a n-puzzle board object
# @author Eduardo Ch. Colorado
# ********************************************************************... |
1712928fa8f2c7046f697f9270a518caeb015da7 | DanielQFK/Numpy | /Numpy-12.py | 747 | 3.84375 | 4 | # Filtering Arrays...
import numpy as np
array1 = np.array([41, 42, 43, 44, 45, 46, 47])
array2 = [True, False, True, False, False, False, True]
array3 = array1[array2]
print(array3)
"""output:[41 43 47]"""
# Creating the Filter Array
Filtering = np.array([41, 42, 43, 44])
Filtering1 = []
for element in Filtering:
... |
02db5e385108980d78a2fbb0b8ad151be7a5eadb | DanielQFK/Numpy | /Numpy-20.py | 297 | 4.09375 | 4 | # Add the Elements of Two Lists...
import numpy as np
one = np.array([1, 2, 3, 4, 5])
two = np.array([6, 7, 8, 9, 10])
three = []
for i, j in zip(one, two):
three.append(i + j)
print(three)
"""output:
[7, 9, 11, 13, 15]"""
four = np.add(one, two)
print(four)
"""output:
[ 7 9 11 13 15]"""
|
3e4e13180d4536c9d2d342069e578cd2bbc8d849 | Faisal-Alhazzani/Hill_Cipher | /Source code Hill.py | 7,387 | 3.71875 | 4 | import numpy as np
def encrypt(plaintext):
# Ask for key to get k matrix
k = createKey()
# Ask for plaintext to get p matrix
P = createMatrixFromStringToInt(plaintext)
# Calculate C = P * K mod 26
c = ""
for i in range(2):
# Dot product
row_0 = P[0][i] * k[0][0] + P[1][i... |
705d2be414c3c47823269525c150b5e42ce3f5b0 | AbhinavPelapudi/ML-Precourse | /precourse.py | 1,026 | 3.546875 | 4 | #Name : Abhinav pelapudi
# Machine Learning/Data Science Precourse Work
# ###
# LAMBDA SCHOOL
# ###
# MIT LICENSE
# ###
# Free example function definition
# This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing ... |
e35e2d8f2d7f63cdbc5e5b813cc417ec5e2c1024 | Montuseth/Cursopython | /Fundamentos/Tareas/Tarea4.py | 270 | 4 | 4 | numero1 = int(input("Proporcione el numero 1: "))
numero2 = int(input("Proporcione el numero 2: "))
if numero1>numero2 :
print("El numero mayor es ",numero1)
elif (numero2>numero1):
print("El numero mayor es ",numero2)
else:
print("Los numeros son iguales") |
dadaab812f4ce7ee2e0a5a95436088f109a0a63d | saadhasanuit/Lab-04 | /question 11.py | 487 | 4.125 | 4 | print("Muhammad Saad Hasan 18B-117-CS Section:-A")
print("LAB-04 -9-NOV-2018")
print("QUESTION-11")
# Program which calculates the vowels from the given string.
print("This program will count total number of vowels from user defined sentence")
string=input("Enter your string:")
vowels=0
for i in string:
if(... |
96358a86be28c27ee558be9df77ea712dda312b0 | saadhasanuit/Lab-04 | /question 1 a.py | 502 | 3.828125 | 4 | print("Muhammad Saad Hasan 18B-117-CS Section:-A")
print("LAB-04 -9-NOV-2018")
print("QUESTION-01 PART A")
# Practicing IF condition
a=400
b=500
if a==400:
print("The value of a is equal to 400")
if a<b:
print("The value of a is less than b")
if a>b:
print("The value of a is greater than b")
if ... |
b0e72e4c184783271408178a2a5e1a20d866a580 | keerthana20656/python-programs | /cost_recrangle.py | 653 | 4.03125 | 4 | class rectangle():
def __init__(self,length,breadth,price):
self.length=length
self.breadth=breadth
self.price=price
def perimeter(self):
return 2*(self.length + self.breadth)
def area(self):
return self.length*self.breadth
def totcost(self):
ret... |
a8a48746f3ec04395eb037b6368cdd2960ea0bc6 | JayDeeJaye/polynesia | /shoe.py | 1,112 | 3.953125 | 4 | import random
class Shoe:
#
# Cards are dealt from a shoe, or a chute containing a number
# of decks of cards which are randomly shuffled.
# For this exercise, there's no need to differentiate between
# individual cards, so we'll keep instances of point value instead.
#
# There are 52 cards... |
877a89267774f79b7b4516e112c8f73a1ebad162 | MariyaAnsi/Python-Assignments | /Assignment_5.py | 363 | 4.34375 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file,
#and print the contents of the file in upper case.
fname = input("Enter file name: ")
fh = open(fname)
print("fh___", fh)
book = fh.read()
print("book___", book)
bookCAPITAL = book.upper()
bookCAPITALrstrip = boo... |
676caf40b5411b172382e5487a929c41e990190c | hangfei/Python | /Game Battleship/battleship_game.py | 19,475 | 4.09375 | 4 | # This homework is done by Hangfei Lin and Ruochen Zhang
import random
class Ship(object):
"""Create Ship Class with specific methods and variables"""
def __init__(self):
"""Initialize the instance variables with empty sets"""
self.locations = set()
self.hits = set()
def ok_to_pla... |
f84f3ab01dc881286a0f3b1793fdd66ec3a305c7 | JoseMR87/BECAS-DIGITALIZA | /05_calculator.py | 1,355 | 4 | 4 | print "BIENVENIDO A LA CALCULADORA PERSONAL DE PYTHON"
print " QUE OPERACION DESEA REALIZAR "
print "1.suma"
print "2.resta"
print "3.multiplicacion"
print "4.division"
print "5.exponencial"
def suma ():
z = x + y
print z
def resta ():
z = x - y
print z
def multiplicacion ():
z = x * y
... |
9b956f5ea9318f4f645326714b75cbe9f47a1bc0 | apaleyes/python-ml-learn | /pythonprogramming.net/linear_regression/simple_regression_implementation.py | 1,258 | 3.546875 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
import random
def best_fit_line(xs, ys):
m = ( (mean(xs) * mean(ys) - mean(xs * ys)) /
((mean(xs)**2) - mean(xs**2)) )
b = mean(ys) - m * mean(xs)
return m, b
def squared_error(ys_orig, ys_line):
return sum((ys_orig - ys_line)**2)
... |
e8b537fbde40d314f68959556009eaae369bef2e | apaleyes/python-ml-learn | /machinelearningmastery.com/backpropagation_from_scratch/dataset_operations.py | 3,005 | 3.53125 | 4 | from random import randrange
def load_csv(filename):
'''
Reads dataset csv and stores it as list
Assumes arbitrary number of spaces as a delimiter
'''
data = []
with open(filename, 'r') as datafile:
for row in datafile:
if not row:
continue
data.... |
ca8ed38c49697553abaca2c6263904dd120ef93a | johbo477/AdventOfCode2020 | /01/01.py | 864 | 3.625 | 4 | file = open('input.txt', 'r')
lines = file.readlines()
numbers = []
for line in lines:
number = int(line)
numbers.append(number)
# part 1
for i in range(0, len(numbers) - 2):
for j in range(i + 1, len(numbers) - 1):
if (numbers[i] + numbers[j] == 2020):
product = numbers[i] * numbers[j... |
2c8e57cf2b59949b7609f63223054617744c7ea0 | guoylyy/uband-python-s1-july | /B21056/checkin02/day5.py | 609 | 3.609375 | 4 | #!/user/bin/python
#-*- coding: utf-8 -*-
#@author:karen
def main():
good1 = ' 大白菜'
good2 = '空心菜'
good3 = '小龙虾'
#…………省略100个
good100 = '蚌壳'
print '老妈看到了 %s'%(good1)
print '老妈看到了 %s'%(good2)
def main2():
goods = '大白菜,空心菜,小龙虾'
print '老妈看到了 %s'%(goods)
def main3():
print '---------------'... |
6d713f2d753164f543b964a1029e38d22f78753e | guoylyy/uband-python-s1-july | /B21056/checkin10/karen-HW16-2.py | 760 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Guo
def main():
import time
ticks=time.time()
print ' 当前时间戳为:',ticks
print '---------'
localtime=time.localtime(time.time())
print ' 本地时间为:',localtime
print '---------'
localtime=time.asctime(time.localtime(time.time()))
print '本地时间为:'... |
9e60d316dd88943b4344426bce7b6e35084fe34b | guoylyy/uband-python-s1-july | /week3/day19-sample-code.py | 607 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*
class Fish():
def __init__(self, name, location):
self.name = name
self.location = location
def jump(self):
print '来自 %s 的鱼 %s 开始跳起来了' %(self.location, self.name)
class Bird():
def __init__(self, name):
self.name = name
def fly(self, height):
pri... |
e0a1f9d1c2bbd7f9302e82497da930a48159a15f | guoylyy/uband-python-s1-july | /homework/A16042/check-in10/day13-homework.py | 1,544 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
week_overnight =[False,False,True,False,False]
for index,is_overnight in enumerate(week_overnight):
print '今天是星期%d'%(index + 1)
try:
overnight_check(is_overnight)
except Exception,e:
print '发生错误:%s'%(e)
print '老妈骂了老爸一顿,然后原谅了他'
else:
print '附带脚... |
b0c05311c7494aac85dd625613fabe3d9db5c320 | guoylyy/uband-python-s1-july | /homework/A16042/check-in04/day5-homework.py | 958 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author: Guoshushu
def main():
good1 = '大白菜'
good2 = '空心菜'
good3 = '花菜'
good4 = '生姜'
good5 = '小龙虾'
# ....... 省略掉 100 个
good100 = '蚌壳'
print '老妈看到了 %s '% (good1)
print '老妈看到了 %s '% (good2)
print '老妈看到了 %s '% (good3)
print '老妈看到了 %s '% (good4)
print ... |
d58767bebd4a08a036751ee3d2d78053fb0c7728 | matematikk/vgs_eksamener | /løsningsforslag/S2/S2_16V/figs/oppgave_2_d_plot.py | 472 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 6 13:16:53 2017
"""
import numpy as np
import matplotlib.pyplot as plt
def P(x):
return x**3 - 6*x**2 + 32
def Pd(x):
return 3*x**2 - 12*x
x = np.linspace(-3, 6, num = 500)
plt.style.use('seaborn-ticks')
plt.rc('text', usetex = True)
plt.plo... |
148cdff2c82b977ac63d1aa7452c84d62a1a374d | natevrl/hardtrain_python | /algo_franceioi/algo_poidstotal.py | 664 | 3.71875 | 4 | #! /usr/bin/env python3
# coding: utf-8
nb_membres = int(input())
poid_total_equipe2 = 0
poid_total_equipe1 = 0
for poid_par_joueur in range(1, nb_membres*2 + 1):
if (poid_par_joueur % 2) == 0:
print("ce chiffre est pair")
get_poid_equipe2 = int(input())
poid_total_equipe2 += get_poid_equipe2
else:
print("c... |
55e3778ceb24a8ed688f721ff54dff1b94003d5b | natevrl/hardtrain_python | /algo_franceioi/cloture2_booleen.py | 389 | 3.65625 | 4 | plus_petit_x = int(input())
plus_grand_x = int(input())
plus_petit_y = int(input())
plus_grand_y = int(input())
nombre_maisons = int(input())
maison_dans_la_zone = 0
for maison in range(nombre_maisons):
x = int(input())
y = int(input())
if x >= plus_petit_x and x <= plus_grand_x:
if y >= plus_petit_y and y <= p... |
5c6bfda43aee68d928f4aa976b449f4e1612108f | natevrl/hardtrain_python | /algo_franceioi/departement_darchitecture.py | 336 | 3.53125 | 4 | max_pierres = int(input())
etage = 0
construction = 0
somme_pierre = 0
while somme_pierre < max_pierres:
construction += etage + (etage + 1)
somme_pierre += construction
etage += 1
if somme_pierre > max_pierres:
somme_pierre -= construction
etage -= 1
break
print(etage)
print(s... |
7f73a6a406b825ecd1403858ce3158678ad5e977 | kenland78/speedtest | /speedtest.py | 115 | 3.71875 | 4 | #!/usr/bin/env python3
import time
start = time.time()
i = 0
while time.time() < start + 5:
i += 1
print(i)
|
9775f4ab538d8e5c00e706f77f7d09a2990f4024 | kedarpujara/MachineLearningPython | /LinearRegression/RegressionProject.py | 998 | 3.515625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def LearningRegressionCustomer():
customers = pd.read_csv("Ecommerce Customers")
# customers.head()
# customers.info()
# customers.describe()
# sns.set_palette("GnBu_d")
# sns.set_style('whitegrid')
# sns.jointp... |
da6d7a2e824ecef3891665b37c32f375c007e572 | hxpaul/python-training | /ascii.test.py | 827 | 3.734375 | 4 | #!/usr/bin/env python3
'''
tests for our ascii code
'''
__copyright__ = 'Copyright 2015 Holiday Extras'
__licence__ = 'GPL'
import unittest
from ascii import Square
from ascii import Rectangle
class TestFactorial( unittest.TestCase ):
def test_3_x_2_rectangle( self ):
rectangle = '***\n***\n'
self.assertE... |
e23db0c2b2df63611d1066b76cf1606fd40852ba | TewariUtkarsh/Python-Programming | /Tuple.py | 553 | 4.1875 | 4 | myCars = ("Toyota","Mercedes","BMW","Audi","BMW") #Tuple declared
print("\nTuple: ",myCars)
# Tuple has only 2 built in functions:
# 1.count()- To count the number of Element ,that is passed as the Parameter, in the Tuple
print("\nNumber of times BMW is present in the Tuple: ",myCars.count("BMW"))
print("Number... |
6717306792716cbc062e400eeb7c6d434f28544a | gorkememir/PythonProjects | /Basics/pigTranslator.py | 1,160 | 4.21875 | 4 | # Take a sentence from user
original = input("Please enter a sentence: ").strip().lower()
# Split it into words
splitted = original.split()
# Define a new list for storing the final sentence
new_words = []
# Start a for loop to scan all the splitted words one by one
for currentWord in splitted:
# If the first l... |
7b6adab3f2ca4de7e2433cb8139ca863296b2489 | mathsjames/Safe-AF | /Decision_Problems/sleeping_beauty.py | 2,788 | 3.59375 | 4 | import numpy as np
from Decision_Problems.decision_problem import Decision_Problem
from Decision_Problems.training_data import *
import math
#import matplotlib.pyplot as plt
## WARNING! This decision problem has a non-standard internal structure
class Sleeping_Beauty_by_bet(Decision_Problem):
# Reward given by ... |
849e7999c5eee1567b7fe22a0496b5e3d2a86d24 | Jurenik1/python | /lista.py | 89 | 3.859375 | 4 | #Ejemplo de lista
lista= ("Uno", 1,10, "Pepito")
print lista[2]
for x in lista:
print x |
2ec7326a27d8ec122f104c640da6325c699417c0 | JeanChrist/Algorithms | /leetcode/arrays/plus_one.py | 1,377 | 3.828125 | 4 | """
>>> plus_one = Solution().plusOne
>>> plus_one([1,2,3])
[1, 2, 4]
>>> plus_one([1])
[2]
>>> plus_one([1,2,9])
[1, 3, 0]
>>> plus_one([1,2,5])
[1, 2, 6]
>>> plus_one([0])
[1]
>>> plus_one([9,9])
[1, 0, 0]
"""
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
... |
f5015d1f35dd34776ec59635f1bef529a57acd6a | JeanChrist/Algorithms | /leetcode/linked_lists/remove_Nth_from_end.py | 1,513 | 3.953125 | 4 | """
>>> remove_node_from_end = Solution().removeNthFromEnd
>>> head = LinkedList.create([1, 4, 5, 2])
>>> res = remove_node_from_end(head, 2)
>>> list(res)
[1, 4, 2]
>>> head = LinkedList.create([1, 4, 5, 2])
>>> res = remove_node_from_end(head, 3)
>>> list(res)
[1, 5, 2]
>>> head = LinkedList.create([1, 4, 5, 2])
>... |
7a4180222f7827fd7a7ae342ab04245a201f8c54 | JeanChrist/Algorithms | /leetcode/linked_lists/delete_node.py | 649 | 3.828125 | 4 | """
>>> linked_list = LinkedList.create([1, 4, 5, 2])
>>> delete_node = Solution().deleteNode
>>> delete_node(linked_list.next.next)
>>> list(linked_list)
[1, 4, 2]
>>> linked_list = LinkedList.create([1, 4, 5, 2])
>>> delete_node(linked_list.next)
>>> list(linked_list)
[1, 5, 2]
"""
from leetcode.linked_lists import... |
dc83ccdd6b06b2dff7080b9691e773f5f0636a0c | JeanChrist/Algorithms | /leetcode/strings/valid_palindrome.py | 2,000 | 3.578125 | 4 | """
>>> is_palindrome = Solution().isPalindrome
>>> is_palindrome("A man, a plan, a canal: Panama")
True
>>> is_palindrome("race a car")
False
>>> is_palindrome("a.")
True
>>> is_palindrome("..........a. c....")
False
>>> is_palindrome(".,")
True
>>> is_palindrome("''''''''''''''''''''''''''''''''''''''''''''... |
67bfe903bec5720822d9f0eb1bc907ddc3e5913c | GospodinJovan/raipython | /Homeworknew.py | 218 | 3.734375 | 4 | """mean, median, mode, euclidian_distance (v1, v2)"""
# Example points in 2-dimensional space... Euclidian Distance
import math
x = [5, 6]
y = [8, 9]
distance = sqrt((x[0]-y[0]**2 + (x[1]-y[1]**2))
print(distance)
|
a23034a6ada538ad5c35ec45b514900a68183d1f | GospodinJovan/raipython | /Triangle.py | 1,234 | 4.5625 | 5 | """""
You are given the lengths for each side on a triangle. You need to find all three angles for this triangle. If the given side lengths cannot form a triangle
(or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order.
Eac... |
b7bc153be93ada350ec19590f378ad215583bada | LnlyPineapple27/Pac-man_AI | /Pacman/Point.py | 912 | 3.765625 | 4 | import math
import copy as cp
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __eq__(self, another):
return self.x == another.x and self.y == another.y
def manhattan_distance(self, another):
return abs(self.x - another.x) + abs(self.y - another.y)
... |
6681c74eed15a86ce699efb6e28cbf1e98630cfb | bipuldev/US_Bike_Share_Data_Analysis | /Bike_Share_Analysis_Q4a.py | 2,117 | 4.4375 | 4 | ## import all necessary packages and functions.
import csv # read and write csv files
from datetime import datetime # operations to parse dates
from pprint import pprint # use to print data structures like dictionaries in
# a nicer way than the base print function.
def number_of_trips(fil... |
4cdde60fd9de8611be30b17782d8d48ef33bff5e | Dronebaba00/-Inbspace-15thmay_B1_ML | /Home_work_2.py | 320 | 3.5625 | 4 | ## String
S=input('Enter String :- ')
Cal={i:S.count(i) for i in set(S)}
print('All Alphabtes',Cal)
D=str(dict(Cal))
Len=len(Cal)
Val=list(Cal.values())
Max=max(Val)
New = [Max-Val[i] for i in range (Len)]
if (New.count(0)==Len or New.count(0)==1):
print("My string")
else:
print("Not my string")
|
a764e5cded7e9e0e4e326e396c95bf024bdd1390 | Prem55555/Assignment1 | /321810304013 perimeter of rectangle.py | 117 | 4.03125 | 4 | l=float(input("enter the length :"))
b=float(input("enter the breadth:"))
print("perimeter of ractangle is:",2*(l+b)) |
6e9f22c64916fb77619f88f73e2a0f457db8f183 | Luvlore/edutech-pr | /Curso 10/example.py | 853 | 3.734375 | 4 | def dividir(dividendo, divisor):
if not (isinstance(dividendo, int) and isinstance(divisor, int)):
raise ValueError('dividir() deve receber apenas argumentos inteiros.')
try:
aux = dividendo/divisor
except:
print(f'Não foi possível dividir {dividendo} por {divisor}.')
... |
b0641a331d792f97dd4d28abf6f5495bbbe4ef22 | chathaway-codes/gutenberg_readability | /src/process/average_words.py | 502 | 3.609375 | 4 | import unittest
from process.story import Story
def main(book):
return (1.0 * len(book.words)) / len(book.sentences)
class AverageNumberOfWordsTest(unittest.TestCase):
def test_average_number_of_words(self):
class FakeBook:
def __init__(self):
self.words = ["Hello", "my", ... |
78d89b62f9f9b009dff378b3a117f94039c8dd09 | tezz15/AI | /FirstClass/string_fun.py | 209 | 3.875 | 4 | '''
a = []
a.append("hello")
a.append(1)
a.append(2.3)
print(a)
'''
a = ['Ram', 'Shyam',2,3,5.1]
for i in a:
print(i)
x = a.pop(2)
print(a)
print("Deleted item:", x)
print(a)
del a[0]
print("New list:",a) |
862d88cb2175d9aa0494cc4dc0436479542159ba | shanksy24/Python-stuff | /vonkoch_snowflake_combined.py | 1,117 | 3.890625 | 4 | #Gives perimeter and area for vonkoche snowflake at "n" stage
user_input = int(raw_input("Stage num : "))
#fractional
area_tally = [1,1]
new_fractn = [9,9]
perimeter = [3,1]
if user_input == 0:
print "Perimeter : 3 units"
print "Area : 1 unit squared"
exit()
for n in range(1, user_input+1):
if n == 1:
ar... |
a91c1beb09f16cec6c5d03b4eef2d84ca4b208e2 | shanksy24/Python-stuff | /battleship.py | 1,616 | 4.0625 | 4 | from random import randint
def print_board(board):
print "\n 1 2 3 4 5"
print " | | | | |"
for index, row in enumerate(board):
print index + 1, "-",
print " ".join(row)
print "\n"
def random_row(limit):
return randint(1, limit)
def random_col(limit):
return randint(1, limit)
def col_guess_func():
r... |
dca9f130762a196052016a40599d2f47662476fe | roneill/luhnybin | /src/luhncheck.py | 3,080 | 3.609375 | 4 | #! /usr/bin/env python
import sys
import re
def toArray(number):
components = []
while number != 0:
digit = number % 10
components.append(digit)
number -= digit
number /= 10
components.reverse()
return components
def luhnChecksum(number):
numbers = toArr... |
d59a3a58b3cc73976c685c0e634fea373283868c | ShiJingChao/Python- | /PythonStart/0722Python/0805Python/day05/集合/demo01_集合的定义.py | 1,731 | 4.4375 | 4 | """
集合: set
python的基础数据类型之一;
定义: 用于存储一组无序的不重复的数据;
特点:
1. 集合是无序的;
2. 集合中的元素是不重复的, 唯一的;
3. 集合中存储的数据必须是不可变的数据类型;
4. 集合是可变的数据类型;
语法:
set1 = {1, 2, 3} # int --> 不可变
增加:
add()
update() 参数: 可迭代对... |
6b1a1bcd97eef7a980affd92338c173ffc5f169a | ShiJingChao/Python- | /PythonStart/0722Python/0805Python/day10/demo09_多继承.py | 713 | 3.765625 | 4 | """
python中支持多继承: 多个父类
子类可以同时拥有多个父类功能;
python2
c3算法 , 深度优先
python3
c3算法, 广度优先
注意点: 如果使用多继承(一个子类同时继承自多个父类), 保证父类中没有相同名字的方法;
method resolution order
可以根据 类.__mro__属性查看 当前类的父类的排序
也可以根据 类.mro() 查看当前类的父类的排序
"""
class A:
def func1(self):
print("A")
class... |
3554ace4a4e7fa8bd9153226290087c22c245987 | ShiJingChao/Python- | /PythonStart/0722Python/0805Python/day12/demo_生成器为啥叫迭代器.py | 729 | 3.953125 | 4 | """
可迭代对象: 实现了__iter__方法的对象就是可迭代对象;
迭代器: 实现了__iter__方法和__next__方法的对象就是迭代器;
迭代器 是 可迭代对象;
生成器 是 可迭代对象;
生成器 是 迭代器;
__iter__()方法的返回值是 迭代器;
可迭代对象.__iter__(), 就会生成一个 迭代器;
---------------------
生成器:
1. 生成器表达式;
2. 生成器函数; 函数中使用了关键字 yield ;
"""
g = (x fo... |
b6cb42b758b8e54bfd063ae46d7b4034466386cb | ShiJingChao/Python- | /PythonStart/0722Python/DAY3/列表元组字典集合.py | 3,844 | 3.78125 | 4 | # 练习 列表的学员管理系统
# 需求分析:添加学员,删除学员,修改资料,多种方式查询
# 增加 一组 史景超
stu_info = [["demo", "nan", 18]]
while True:
lst_tip = ["1.添加学员", "2.修改资料", "3.查询", "4.删除学员", "5.退出"]
for i in lst_tip: # 遍历列表循环输出提示
print(i)
choose = input("请输入你要选择的操作:")
if choose != "1" and choose != "2" and choose != "3" and choose !=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.