blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5ecee322020fc2dae6def1caad331b0f4217bdc3
wpy-111/python
/month01/day03/exercise07.py
206
3.765625
4
# 在终端中录入一个整数,如果奇数为变量state # 赋值为奇数字,否则赋值为偶数 number = int(input("输入一个整数:")) state = "奇数" if number % 2 else "偶数" print(state)
f0b037deac2e69b7a8c314c5791e99feab73a72b
wpy-111/python
/month01/day02/homework03.py
160
3.84375
4
# 温度转换器 # 摄氏度 = (华氏度-32)/18 degree = float(input("摄氏度:")) fahrenheit = (degree * 18) + 32 print("话适度:" + str(fahrenheit))
20a0cccb17791dd72ed74864e1386d484b451885
wpy-111/python
/month01/day03/exercise10.py
331
3.59375
4
#练习1 输出 0 1 2 3 #练习2 输出 2 4 6 8 10 #练习3 输出 1 4 7 10 #练习4 输出 8 7 6 5 #练习5 输出 -1 -2 -3 -4 -5 # count = 0 # while count <= 3: # print(count) # count += 1 # count = 2 # while count <= 10: # print(count) # count += 2 count = -1 while count >= -5: print(count) count -= 1
a9df086e97518365d3aaeb598b06876d8bd57d17
wpy-111/python
/DataAnalysis/day01/demo06_slice.py
736
3.5
4
""" 数组的切片 """ import numpy as np a = np.array([[1 + 1j, 2 + 4j, 3 + 7j], [4 + 2j, 5 + 5j, 6 + 8j], [7 + 3j, 8 + 6j, 9 + 9j]]) import numpy as np a = np.arange(1, 10) print(a) # 1 2 3 4 5 6 7 8 9 print(a[:3]) # 1 2 3 print(a[3:6]) # 4 5 6 print(a[6:]) # 7 8 9 print(a[::-1]) # 9 8 7 6...
d94a1a99925c59f53e0d86349479e27abb205b67
wpy-111/python
/month01/day03/homework02.py
555
3.765625
4
# 在终端中获取年龄,显示 # 婴儿(0-1) 儿童(2-13) 青少年(14-20) # 成年人(21-65) 老年人(66-150) # 要求,重复判断,直到年年龄录入空格为止 while True: str_age =(input("请输入年龄")) if str_age == " ": break int_age = int(str_age) if 0 <= int_age <= 1: print("婴儿") elif 2 <= int_age<= 13: print("儿童") elif 14<= int_age <= 65:...
de582d68c920408d889a571df5f6c2b2796e8bc0
wpy-111/python
/month01/day03/exercise06.py
387
4.0625
4
# 练习在终端中录入一个年份,打印天数 month = int(input("请输入几月")) if month == 1 or month == 3 or month == 5 or month == 7 or month == 10 or month == 12: print("天数为三十一天") elif month == 4 or month == 6 or month == 9 or month == 11: print("天数为三十天") elif month == 2: print("天数为二十八") else: print("月份有误")
b53cf2c97080550a80092731c6a4000f8cd4141e
wpy-111/python
/month01/day11/homework01.py
799
3.75
4
""" 作业:创建技能类(技能名称,消耗法力(0-80),持续时间(1-60) 限制对象打有效范围 """ class Skill: def __init__(self, name="", mana=0,last_time=1): self.name=name self.mana=mana self.last_time=last_time @property def mana(self): return self.__mana @mana.setter def mana(self,value): i...
7bf3ea7d0df41edb17f5768910e416b89b1a3caa
wpy-111/python
/MachineLearning/day02/demo01_line.py
2,468
3.59375
4
""" 线性回归 梯度下降自己会去找最小的 x = x-学习率*导函数(偏导数) """ import numpy as np import matplotlib.pyplot as mp train_x = np.array([0.5, 0.6, 0.8, 1.1, 1.4]) train_y = np.array([5.0, 5.5, 6.0, 6.8, 7.0]) lrate = 0.01 k_list,b_list=[1],[1] losses = [] times = 1000 epoches = [] # 记录每次梯度下降的索引 for i in range(times): loss = ((...
7a4672e080967ec143ddf541987ea3ac1622f360
wpy-111/python
/month02/day06/sum_prime.py
778
3.671875
4
""" 计算质数的和 """ import time from multiprocessing import Process def print_time(sum_prime): def wrapper(*args,**kwargs): start_time=time.time() re = sum_prime(*args,**kwargs) stop_time=time.time() print(stop_time-start_time) return re return wrapper @print_time def sum_p...
034f0aaa4326f30c784e41af6f94231fe41f356e
wpy-111/python
/DataStructure/day01/test.py
710
3.8125
4
""" 若n1+n2+n3=1000,且n1^2+n2^2=n3^2(n1,n2,n3为自然数), 求出所有n1、n2、n3可能的组合 """ #算法一 import time # start_time = time.time() # for n1 in range(0,1001): # for n2 in range(0,1001): # for n3 in range(0,1001): # if n1 + n2 + n3 == 1000 and n1**2 + n2**2 == n3**2: # print('[%d,%d,%d]' % (n1,n2...
f098e1b2f65594177ce9dd0ece82e9565e394244
wpy-111/python
/DataAnalysis/day06/demo07_bitwise.py
164
3.6875
4
""" 位运算 """ import numpy as np a = np.array([0, -1, 2, -3, 4, -5]) b = np.array([0, 1, 2, 3, 4, 5]) #^位异或操作符 相同得0 不同得1 print(a^b)
94b1459febaaf6a14d350400bf0d8742a2311256
wpy-111/python
/month01/day07/homework02.py
311
3.796875
4
""" 定义函数,将二维列表,以表格状打印在zhongduanzhong """ def print_form(list): for r in list: for c in r: print(c, end="\t") print() print_form([ [1,2,3,4], [5,6,7,8,], [9,10,11,12], [13,14,15,16] ] )
1de3a448c0e3261129157d7cd4ba4c3ef058ae7f
wpy-111/python
/month01/day06/exercise02.py
605
3.9375
4
""" 练习:在终端中录入商品信息(名陈/价格), 录入空格停止 将所有商品打 名称和价格打印出来(一行一个) 如果录入蓝"游戏机",则打印其价格 要求:重复打商品,不能重复录入 """ dict={} while True: name = input("请输入商品名称:") if name == " ": break price = float(input("请输入商品价格")) if name not in dict: dict[name]=price for key,value in dict.items(): print(...
eacb4f434d6ccf551e0381f04c5c92dd04ada00e
wpy-111/python
/month01/day10/exercise02.py
886
4.15625
4
""" 练习: 在终端中循环录入学生信息(名字,年龄,成绩,性别) ----创建学生类 ----打印个人信息 """ class Student: def __init__(self, name, old, achement, gender): self.name = name self.old = old self.achement = achement self.gender = gender def print_personal_info(self): print("学生姓名:",...
dd287a75353d450ba181d28549272085ad8f460e
wpy-111/python
/month01/day10/exercise05.py
248
4.0625
4
""" 对象计数器 创建老婆类,记录老婆对象的数量 """ class Wife: count=0 def __init__(self,name): self.name=name Wife.count+=1 w01=Wife("消防") w02=Wife("小妹") w03=Wife("小李") print(Wife.count)
31a66214cc6c33971623c4e220f7a7e1484635f7
wpy-111/python
/month01/day04/exercise06.py
216
3.5
4
""" 显示几斤几两 """ # jin =int(input("请输入斤")) # liang =int(input("请输入两")) # print("%d斤%d两"%(jin,liang)) number01=5.8 number02=6.5 print("%f+%f=%f"%(number01,number02,number02+number01))
2efd8056fc51f7682e27732e3672e136c2561a96
wpy-111/python
/month01/day10/homework02.py
2,207
3.734375
4
""" 作业:创建敌人类 -----数据:名称,血量,攻击力,防御力 -----行为:打印个人信息 -----创建敌人列表 -----在敌人列表中查找“灭霸”对象 -----在敌人列表中查找死人 -----在敌人列表中查找攻击力最大的敌人 -----根据防御力,对敌人列表进行降序排列 """ class Enemy: def __init__(self,name,blood_volume,aggressivity,defense): self.name=name self.blood_volume=blood_volume sel...
af790db4d1a51823163c10e2c665250713833a41
wpy-111/python
/Spider/day07/05_selenium_mzb_handles.py
1,184
3.609375
4
""" selenium切换句柄 抓取民政部网站最新行政区划分代码 """ from selenium import webdriver import time class GovSpider: def __init__(self): self.url = 'http://www.mca.gov.cn/article/sj/xzqh/2020/' self.options =webdriver.ChromeOptions() self.options.add_argument('--headless') self.browser = webdriver....
a1e72b3151f3a5fe61b5e78e163aadd5dafd2116
wpy-111/python
/month01/day09/day08/exercise03.py
574
3.796875
4
""" 练习:定义函数,返回字符串中第一个不重复打字符 输入:ABCACABEFD 输出:E """ def print_fist_not_repeat(target): dict_repeat_info=get_dict_repeat_info(target) for key,value in dict_repeat_info.items(): if value==1: return key def get_dict_repeat_info(target): dict_repeat_info={} for i in target: ...
9a17b143186ba745a367a2f57213134afea2fba5
martinwr57/Tic-Tac-Toe
/BoardGame.py
21,181
4.21875
4
#!/usr/bin/env python import random import itertools import os, sys class TicTacToeGame(): """Base class for Tic Tac Toe game. """ def __init__(self): """Initializes class attributes for Tic Tac Toe game. @type moves: List @param moves: List of X a...
cbfb5c28bbc901b8e25d78955a64b297047ea1eb
hisnameispum/unicodeexplorer
/lab3.py
1,883
4.21875
4
def main(): start = "" gap = 0 end = "" print('*** Welcome to the Unicode Explorer ***') user_input = input('Would you like to start exploring with an alphabet: [Y/N]: ').upper() if user_input == "Y": start = input("Enter first character in exploration: ") gap = int(input("Enter ...
9651b91eea6ebcc9daea674879afe78fc5ae56bd
jamesmilliman/project_euler
/euler/p5.py
275
3.5
4
def p5(n = 20): x = n found = False while True: found = True for i in range(1, n): if x % i != 0: found = False break if found: return x else: x += n print(p5())
dd57c2c4f367c792aa42f798e4b1d04864af418e
Ochirgarid/uhunt
/solutions/1-introduction/starred/11332.py
267
3.765625
4
def dig_sum(x): if x < 10: return x s = 0 while x > 0: s += x % 10 x //= 10 return dig_sum(s) if __name__ == "__main__": while True: x = int(input()) if x == 0: break print(dig_sum(x))
eba8d07c269e1343e54d7f0387d1f033bb5eeaf1
KavinduKDWanasekara/CreditMart-Final
/backend/views/credit_limit_model.py
1,206
3.546875
4
def factorial(num): factorial = 1 if num < 0: return 0 elif num == 0: return 1 else: for i in range(1, num + 1): factorial = factorial * i return factorial # import matplotlib.pyplot as plt import math import statistics def probability_density(pd, num_of_...
a4f50b8aa4cabfa0de8a6b8ddbd727a3d25199f7
JRodDvlpr/cs-sprint-challenge-hash-tables
/hashtables/ex3/ex3.py
1,115
3.921875
4
def intersection(arrays): """ YOUR CODE HERE """ result = [] # dictionary holds key value array_dict = {} # We will loop through every list inside the array for i in arrays: # Loops through every item in each of the list for k in i: # If k is in the dictionary...
28af4cbf45be37872bf99593be0163b621d436d5
dkutlesic/MarkovChains_Planning5GDeployment
/src/State.py
3,647
3.8125
4
import numpy as np def init_state(data, lambda_): ''' Initializes a state Parameters: data: array-like A generated dataset lambda_: float A parameter in the target functio. Return: state: State An instance of class State ''' indices = ...
87cf78d12566ccdeb9a1cbea3eea07387007bed2
shaduk/Parallel-text-processing-using-Hadoop-MapReduce
/mapper_cooccurence_2.py
1,068
3.546875
4
#!/usr/bin/env python import sys import csv import re mydict = {} reader = csv.reader(open('new_lemmatizer.csv'), delimiter = ',') i = 0 for row in reader: key = row[0] if key in mydict: pass mydict[key] = filter(None, row[1:]) c = 0 # input comes from STDIN (standard input) for line in sys.stdin: line = lin...
b6f6655fbb52809b2eaeac97765cd473cbdb093a
herzogz/algorithm009-class01
/Week_01/88-合并两个有序数组.py
1,055
4.09375
4
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- """ * 由于nums1队尾已有0元素作为留给nums2的空间,所以我们可以从对尾将nums2插入 * 设指针p指向nums1队尾,标记待添加元素的位置 * 指针p1指向nums1元素尾m-1,p2指向nums2队尾n-1 * 当p1,p2>=0时,比较p1,p2所指元素,更小的数值放在p的位置,并移动更小数值对应的坐标,p坐标向前移动 * 最后p1,p2<0时,将剩余nums2加入(若nums2先添加完则不用添加) """ class Solution: def merge(self, nums1, m, nums2,n)...
32f2e0973307cd9c99b77f47595523b42937c978
herzogz/algorithm009-class01
/Week_01/189-旋转数组.py
269
3.921875
4
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- # nums[:]并没有开辟新的空间 class Solution: def rotate(self, nums, k) -> None: nums[:] = nums[len(nums)-k:]+nums[:len(nums)-k] nums = [1,2,3,4,5,6,7] k = 3 a = Solution() a.rotate(nums,k) print(nums)
66b62491c575dde97ce9f70342c43e52b755fea5
haerba/SAD
/HangMan/main_game.py
689
3.78125
4
''' Created on 9 Mar 2019 @author: haerba ''' from Hangman_Game import * import pygame if __name__ == '__main__': variable = True pygame.mixer.init() pygame.mixer.music.load("arcade_song.mp3") pygame.mixer.music.play() os.system("clear") print("User, insert your name please:") name = input...
0ca3757eb5df55acfcc3a64ad70799c73ca7f5cc
mingyuema1217/leetcode-practice
/148_Sort List.py
621
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: # TC: O(nlongn + n + n) = O(nlong) , SC: O(n) if not head or not head.next: return head ...
434f80e5c46a7d3393d3b426913ec5626de81286
mingyuema1217/leetcode-practice
/26_Remove Duplicate from sorted Array.py
353
3.5
4
class Solution: def removeDuplicates(self, nums: List[int]) -> int: j = 0 for i in range(1, len(nums)): if nums[i] != nums[j]: j += 1 nums[j] = nums[i] return j+1 # It's more like a slow and fast two pointer # only if the num[n] != nums[n-1...
f68f4e9f41fc9d243c72cf2892d86f615d0f3701
mingyuema1217/leetcode-practice
/937_Redorder_Logs.py
825
3.625
4
class Solution: """ @param logs: the logs @return: the log after sorting """ def logSort(self, logs): nums = [] letters = [] for log in logs: temp = log.split(" ") if temp[1].isdigit(): # if the content is digit, put in there input order ...
7a7afc9fbb92da5f2dfaae110bfd69ec95940961
mingyuema1217/leetcode-practice
/424_Longest Repeating Character Replacement .py
3,637
3.625
4
""" 本题是想让我们找出最长的重复字符的字符串的长度,换句话说 我们其实就是找满足以下条件的最大sub-string的长度就可以了: 条件为:(子字符串长度-出现次数最多的字符串的个数) <= k 备注:这里我们介绍一个库的用法,defaultdict 当我使用普通的字典时,用法一般是dict={},添加元素的只需要dict[element] =value即, 调用的时候也是如此,dict[element] = xxx,但前提是element字典里,如果不在字典里就会报错 这时defaultdict就能排上用场了,defaultdict的作用是在于, 当字典里的key不存在但被查找时,返回的不是keyError而是一个默认值,而下...
39c57d692dbb3d6439ccfe4e9f10d64d84700b43
mingyuema1217/leetcode-practice
/138_Copy List With Random Pointer.py
1,531
3.890625
4
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ from collections import defaultdict class Solution: def copyRandomList(self, head: 'Node') -> 'Node': has...
6bd5db4ecf59e9c076a701ade24099844f9e214a
BrittanyWhiting/AsymmetricRSA
/RSAFinalCode.py
6,297
4.15625
4
#Brittany Whiting, Macie Chudy, and Kaitlin Jones #Project 1 - RSA import random from random import randrange # function to allow user choice and a termination condition def user_input(): choice = input("Press D for a Signature, press M to Encrypt/Decrypt a Message, press E to Exit. ") while (choice != "D" ...
b58b09250814963bef50cbb46f8cd56181b6ed41
ivandersr/my-python-notebooks
/enum/main.py
479
3.734375
4
from enum import Enum, auto class Directions(Enum): right = auto() left = auto() up = auto() down = auto() def move(direction: Directions): if not isinstance(direction, Directions): raise TypeError('invalid direction') return f'Moving {direction.name}' print(move(Directions.right))...
7aee6a0abd2fec0a1028ad103c63ab56b7c3583c
ivandersr/my-python-notebooks
/sqlite3/main.py
1,108
3.6875
4
import sqlite3 conexao = sqlite3.connect('basededados.db') cursor = conexao.cursor() cursor.execute( 'CREATE TABLE IF NOT EXISTS clientes (' 'id INTEGER PRIMARY KEY AUTOINCREMENT,' 'nome VARCHAR,' 'peso DECIMAL(3,2)' ')' ) # cursor.execute('INSERT INTO clientes (nome, peso) VALUES (?, ?)', ('Mari...
5c471f1840f539724986ada3d86421b063ca3b25
ivandersr/my-python-notebooks
/heranca/classes.py
680
3.609375
4
class Pessoa: def __init__(self, nome, idade): self.__nome = nome self.__idade = idade self.nome_classe = self.__class__.__name__ @property def nome(self): return self.__nome @property def idade(self): return self.__idade def falar(self): print(...
d1b3ba452bc48f6ee97256cba2964c18a769bce6
ivandersr/my-python-notebooks
/curso-python/basico-logica/aula008/aula008.py
400
3.890625
4
# from datetime import date # # nome = input('Qual é o seu nome?') # idade = input('Qual é sua idade?') # # ano_nascimento = date.today().year - int(idade) # # print(f'{nome} nasceu em {ano_nascimento}') numero_1 = input('Digite o primeiro número: ') numero_2 = input('Digite o segundo número: ') print(f'Soma sem casti...
ff72f74352b4261f83e279a6d623badc591a6901
ivandersr/my-python-notebooks
/curso-python/basico-logica/aula021/aula021.py
1,363
4.03125
4
# lista = ['A', 'B', 'Cacilds', 'D', 'E'] # # print(lista[:]) # print(lista[::]) # print(lista[:4]) # print(lista[3:]) # print(lista[::2]) # print(lista[::-1]) # lista = list(range(0, 100, 9)) # # soma = 0 # for valor in lista: # soma += valor # print(f'Soma dos valores da lista: {soma}') # # l1 = ['String', True,...
b7ebeaac9094c7a23b9e333cadc0b112151ec613
angelosuporte/PythonLearning
/ChallengePythonDIO/student-averanges.py
543
3.53125
4
n1, n2, n3, n4= input().split() n1 = float(n1) n2 = float(n2) n3 = float(n3) n4 = float(n4) media = float(n1*2+ n2*3 + n3*4 + n4*1) / 10 print('Media: %.1f' %media) if (media>=7.0): print('Aluno aprovado.') elif(media<5.0): print('Aluno reprovado.') elif((media>=5.0) & (media<=6.9)): (print('Aluno em exame...
a299e5961512c16aa1ba26b38820447b9a4f9cf1
angelosuporte/PythonLearning
/app_pyLearning/RepeatLoops.py
782
3.78125
4
# for x in range(100): # print(x) #Descobrir se um número é um número primo # a = int(input('Informe o número: ')) # # div = 0 # for x in range(1, a + 1): # resto = a % x # print(x, resto) # if resto == 0: # div += 1 # # if div == 2 : # print('Número {} é primo'.format(a)) # else: # p...
c38d580fbf6fea5208ccf9216069bb0e940ebedf
drewk2021/opencvplayingcards
/cannify.py
1,410
3.546875
4
import cv2 import numpy as np import argparse import imutils import blur def cannify(image, thres1 = 30, thres2 = 150): """ Purpose: To impose the cv2.Canny() function on an image, which subjects it to Sobel gradients in both dimensions and identifies "edge-like" regions. Parameters: An image (numpy a...
83b1ea4afa4a1fa857452ad3387b761fb105a6bb
ykingdsjj/Student_course_management_system
/xuanke.py
3,646
3.59375
4
# -*- coding:utf-8 -*- from random import randint """ class 文件 用于存储课程,学生的类 """ major_in = ['z_' + str(i + 1) for i in range(24)] # 不会改变的专业list, 24个专业, 动态生成不考虑效率 class Student(object): """ 学生基本信息, 包含学号, 姓名, 性别, 年纪, 专业, 注意:::我们简单实现一个选课系统, 不需要考虑学分是否会合理 学生选课信息, 包含课程编号, 存储在 list 里 其中学号为 唯一 标识 """ ...
a75a59fac98c287443623e129c83270c9fda6a29
codeninja0/Leo
/Codes/leopython.py
2,738
3.828125
4
import turtle from turtle import Turtle, Screen screen=Screen() t=Turtle("square") t.speed(-1) t.pensize(10) s=40 def dragging(x, y): t.ondrag(None) t.setheading(t.towards(x, y)) t.goto(x, y) t.ondrag(dragging) def space(): t.clear() t.penup() t.goto(0.00,0.00) ...
8acf9801a696c45cadedda4f99d984f50d4f1801
GuilhermRodovalho/Algoritmos-e-estruturas-de-dados
/programaçao-dinamica/magiccows.py
873
3.671875
4
# Programação dinâmica / Dynamic programming import math MAX_DAYS = 50 def soma_linha(tabela, day, max_cows): res = 0 for i in range(max_cows+1): res += tabela[day][i] return res max_cows, number_farms, ndays = input().split() max_cows = int(max_cows) number_farms = int(number_farms) ndays = ...
32c9d2a191075be50ebae721c69892054dd1ee1f
oubiwann/ballotbox
/ballotbox/singlewinner/preferential/base.py
1,772
3.640625
4
class PairWiseBase(object): """ This is a base class to hold common code for implementations that utilize pair-wise comparisons. """ def __init__(self): self.preference_options = [] self.lookup = {} def build_lookup(self, ballotbox): pairs = {} for preferences, v...
8755ba7caa337ffca3f7bd7c2202be771bc3f848
TiagooGomess/MNUM_1920
/Prep. teste 1/Método de Newton.py
728
3.84375
4
def f(x): return 2*x**2 - 5*x - 2 def df(x): return 4*x - 5 #---------------------------------------------- x = 0 # first root guess (usando plot2d no máxima) for i in range(10): x = x - (f(x) / df(x)) print("First root:", x) # Erro absoluto 1 r1 = -0.3507810593582121 # raíz 1 calculada no máxima...
61fdf66b0009ca0ff4b4c4f44a0a3d247e29e43e
TiagooGomess/MNUM_1920
/Prep. exame/Exame 2014/Pergunta 1.py
136
3.515625
4
def g(x): return (4*x**3-x+1)**(1/4) x = 4 for i in range(1,3): x = g(x) print("ITR:",i) print("x:",x) print("\n")
cba59064f69eb9fa9db4b4c3ebc5059eac83bd46
TiagooGomess/MNUM_1920
/Prep. teste 2/Euler (Segunda ordem).py
276
3.890625
4
def dz(t, z): return 2 + t**2 + t*z h = 0.25 t = 1 y = 1 z = 0 print("\nEULER:\n") for i in range(3): print("Iteração:", i) print("t:", t) print("y:", y) deltaZ = dz(t, z) t += h y += h * z z += h * deltaZ print("--------------")
79f8f8c1f9367e5419bf167ef2b90a609047e135
TiagooGomess/MNUM_1920
/Prep. exame/Exame 2013/Pergunta 3.py
797
3.765625
4
def Z(x,y): return 3*x**2 - x*y + 11*y + y**2 -8*x def dZ_dx(x,y): return 6*x - y -8 def dZ_dy(x,y): return -x + 11 + 2*y def gradiente(x,y,h,itr): print("xn:",x) print("yn:",y) print("dZ_dx(xn,yn):",dZ_dx(x,y)) print("dZ_dy(xn,yn):",dZ_dy(x,y)) print("Z(xn,yn):",Z(x,y)) for i in...
fd461fd034416cc67622b416df1c6c6dee5bf743
courtneyng/GWC-18-PY
/gwc_py/programs/math/number_guessing.py
635
4.03125
4
# Program ID: number_guessing # Author: Courtney Ng # Period: 7 # Program Description: Modifying the word guessing. number = 2 answer = int(input("I am thinking of a number 1-10. What is it?")) # while word != answer: # print ("That is incorrect.") # answer = input ("Please try again.") whi...
951154e7cde2c91d100da4b4f424b0370ca3c608
courtneyng/GWC-18-PY
/gwc_py/programs/lists/listchallenges2.py
600
4.03125
4
from random import * sides = ["Mashed Potatoes", "Broccoli", "French Fries", "Onion Rings", "Grapes"] main = ["Spaghetti", "Fettuccine", "Linguine", "Tortellini", "Ravioli"] desserts = ["Gelato", "Tiramisu", "Canoli", "Semifreddo", "Panna Cotta"] #aList = [0, 1] aRandomSide = randint(0, len(sides)-1) aRan...
2f34ae6d1cc9d7805d7564158a65dd66adb35efd
thomas-harris-git/Hangman-game
/hangman.py
1,618
3.703125
4
""" ex2.py CE151 assignment 2 created by Thomas Harris 04/12/14 """ import random word = " " fileName = input("Please supply name of input file: ") try : gotIt = open(fileName) except IOError as e : gotIt = None print("Failed to open", fileName) if gotIt != None : mylist = [line.strip() ...
e0b19c9c0b4977545dc363a50950de187182d2f3
3deep0019/python
/basic01/basic.py
436
3.609375
4
# data type # int data type a = 10 print(type(a)) # complex data type c=10.4+3.6j print(c.real) print(c.imag) # bol dat type b = True print(type(b)) # String dat type s1 = "manish" print(s1) # for represting multiline string s2 ="""i am manish i live in sasaram""" print(s2) ...
c76455c3940e3ab840f9b283e9fb6eea3da1e8fd
3deep0019/python
/List Data structure/important fuction of list/2_Manipulating_Element_of_list/2_insert().py
787
4.46875
4
# 2) insert() Function: # ----> To insert item at specified index position n=[1,2,3,4,5] n.insert(1,888) print(n) #D:\Python_classes>py test.py n=[1, 888, 2, 3, 4, 5] n=[1,2,3,4,5] n.insert(10,777) n.insert(-10,) print(n) ''' Note: If the specified index is greater than max index then element ...
25c674fe31c2d7b0eabc2a48b23569d3e97bdb1a
3deep0019/python
/List Data structure/Traversing the Elements of List/by using while loop.py
259
4.125
4
'''Traversing the Elements of List: ----> The sequential access of each element in the list is called traversal. ''' #1) By using while Loop: n = [0,1,2,3,4,5,6,7,8,9,10] i = 0 while i < len(n): print(n[i]) i=i+1
e0c3f5e756537abb0a3085c23aec52eb2fea6adf
3deep0019/python
/Flow control/Iterative Statements/For_loo.py
1,474
4.59375
5
# Iterative Statements # ************* If we want to execute a group of statements multiple times then we should go for # Iterative statements. # ֍ Python supports 2 types of iterative statements. # 1) for loop # 2) while loop # 1)for loop: # ------> If we want to execute some ac...
9fac853a45da43330f5bc4b6c9dfa344b418335c
3deep0019/python
/List Data structure/Accessing Elements of List/By using Index.py
470
4.34375
4
''' Accessing Elements of List: We can access elements of the list either by using index or by using slice operator(:) 1)By using Index: * List follows zero based index. ie index of first element is zero. * List supports both +ve and -ve indexes. * +ve index meant for Left to Right * -ve index meant for Righ...
ae600db725cf4d3de1ce9e031bbec8c6bb209a26
3deep0019/python
/Flow control/conditional statements/If_else.py
325
4.25
4
# 2) if-else: # if condition: # Action-1 # else: # Action-2 # if condition is true then Action-1 will be executed otherwise Action-2 will be executed. name=input("Enter Name:") if name=="durga" : print("Hello Durga Good Morning") else: print("Hello Guest Good Moring") print("How are you...
b4cbe92376ecb0f65fb64f6a08ea3e4f7699ddd9
3deep0019/python
/Input And Output Statements/evil.py
336
4.375
4
# eval(): # ---> eval Function take a String and evaluate the Result. x = eval('10+20+30') print(x) # eval() can evaluate the Input to list, tuple, set, etc based the provided Input. # Eg: Write a Program to accept list from the keynboard on the display l = eval(input('Enter List')) print (typ...
a780d8479d78ec548e9f470451f0f8a8313927ae
3deep0019/python
/STRING DATA TYPE/Formatting the Strings/case 7.py
449
4.53125
5
#Case-7: Formatting dictionary members using format() person={'age':48,'name':'durga'} print("{p[name]}'s age is: {p[age]}".format(p=person)) ''' Output: durga's age is: 48 Note: p is alias name of dictionary person dictionary we are passing as keyword argument More convinient way is to use **pe...
1ac440180a24b4cdb0c7a0cf3ea21bd73fbf9673
3deep0019/python
/STRING DATA TYPE/Checking Starting and Ending Part of the String.py
364
4.46875
4
# Checking Starting and Ending Part of the String: # --------------------------->Python contains the following methods for this purpose # 1) s.startswith(substring) # 2) s.endswith(substring) # Example s = 'learning Python is very easy' print(s.startswith('learning')) print(s.endsw...
70123ebdce7c3a713e949a0a1f1fb1f269188a97
3deep0019/python
/STRING DATA TYPE/Counting substring in the given String.py
466
4.40625
4
# Counting substring in the given String: # ----------------->We can find the number of occurrences of substring present in the given string by using # count() method. # 1) s.count(substring)  It will search through out the string. # 2) s.count(substring, bEgin, end) ...
37325dec0d3dcd6c75ca9cc3d863eb7e5be0b402
3deep0019/python
/basic01/SpecilaOperators.py
1,590
4.5625
5
# Python defines the following 2 special operators # 1) Identity Operators # 2) Membership operators # 1)Identity Operators # ---> We can use identity operators for address comparison. # ---> There are 2 identity operators are available # 1) is # 2) is not # ********** r1 is r2 returns True if ...
63cbb7f29b7731702c6ea0b8a3976e00738556b0
3deep0019/python
/basic01/RangeDataType.py
520
4.53125
5
# Range data type represents a sequence of numbers. # form 1 - range(10) r = range(10) for i in r : print(i) # --- from 2 - range(10,20) r = range(10,20) for i in r : print(i) # from 3 - range(10,20,2) r = range(10,20,2) for i in r : print(i) # we can access element present in the range data ty...
9058601bf75763ece7621fecb26b9c83d42b171f
AllenGFLiu/leetcode
/#2-两数相加.py
1,057
3.953125
4
''' 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 ''' from typing import Optional # 与#415 字符串相加同样的思路 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> L...
2573dc7b5084019324377a985326d3ddd6293960
AllenGFLiu/leetcode
/#15-三数之和.py
1,786
3.53125
4
''' 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] ''' from typing import Optional def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: ...
49aab0733377ba4566df0f22f4ed2a2cb463c48d
AllenGFLiu/leetcode
/#238-除自身以外数组的乘积.py
1,045
3.640625
4
''' 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。 示例: 输入: [1,2,3,4] 输出: [24,12,8,6] 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) ''' from typing import Optional # 题意要求不要使用除法,意思就是先对全部元素做乘积,然后再遍历每个元素,相除即可 # 另外一种解法 # 先从左到右遍历,保存当前元素左侧元素...
343695e8f1378f51230d3477eb0c9fd44ab004c6
AllenGFLiu/leetcode
/#14-最长公共前缀.py
1,583
3.875
4
''' 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 ''' # Pythonic版 def longestCommonPrefix(strs): if not strs: return '' shortest = min(strs, key=len) for index, char in enumerate...
5e490a7f05d6bdbec3876c48077d42762596ba78
AllenGFLiu/leetcode
/#61-旋转链表.py
2,179
3.5625
4
''' 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL 示例 2: 输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NUL...
3da70da34ec48d9fbe474d5eb7d49763c8784702
AllenGFLiu/leetcode
/#121-买卖股票的最佳时机.py
1,015
4
4
''' 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 示例 2: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 ''' import math from ...
2f165ffce7fe0c41a128f22a02c44bf392164cf5
goslim56/python_practice01
/Quiz_6.py
459
3.765625
4
#문제6. 주어진 리스트 데이터를 이용하여 3의 배수의 개수와 배수의 합을 구하여 출력형태와 같이 출력하세요. list = [1,2,3,4,534,5,345,345,34,234,23,213,3126,7,9,44,7,69,67,48,7,95,7,9,0,54,8,9,] count = 0 sum = 0 for i in list: if(i!=0 and i%3==0): count+=1 sum+=i print("주어진 리스트에서 3의 배수의 개수=> %d"%count) print("주어진 리스트에서 3의 배수의 합=> %d"%sum)
ef3ec2734899585c840fbc3b7da6e3acef8ccfc2
IkaeCathy/MThesis
/N_neighbor.py
428
3.625
4
#N_neighbor.py Finding the neighbors of each node in a graph import xml.etree.ElementTree as ET from matplotlib import pyplot as plt import networkx as nx import time from plotgraph1 import * import math def neighborhood(G, node, n): path_lengths = nx.single_source_dijkstra_path_length(G, node) ...
785a19175e48c40491d2a352026ad51391c8db95
awilsoncs/voidstar
/procgen/aspects.py
943
3.515625
4
from typing import List class Aspect: """Define a species aspect.""" def __init__( self, description=None, categories: set = None, naming: List[str] = None, ): if categories is None: categories = set() if naming is None: ...
7e3e21b6b1f7c67373de08a9b01f76285bb6b7fd
andremenezees/CursoPython
/Aulas/2_Meio/Reduce.py
1,008
4.25
4
""" Reduce Para utilizar a função reduce é necessario utilizar o modulo 'functools' Entendendo reduce() #Imagine que voce tem uma coleção de dados: dados = [a1, a2, a3,..., an] #E voce tem uma função que recebe dois parametros: def funcao(x,y): return x * y Assim como map() e filter(), a funcao reduce() rece...
c1ebb5718a2cbf08f342aa73f1b469076d6e0b04
andremenezees/CursoPython
/Aulas/3_Fim/Decoradores.py
3,867
4.15625
4
""" Funções de maior grandeza - Higher ordem functions(HOF) Quando uma linguagem suporta HOF, significa que podemos ter funçoes que retornam outras funcoes como resultado ou mesmo que podemos passar funcoes como argumentos para outras funcoes. """ #Exemplos de higher ordem function: def somar(a, b): return a + ...
1aa94ff69695150f543feeac3e2c9b2e6d7f8d76
andremenezees/CursoPython
/Questoes/Exercicios_secao_13.py
11,162
4.375
4
""" 1) Escreva um programa que: a) Crie/abra um arquivo texto de nome "arq.txt". b) Permita que o usuário grave diversos caracteres nesse arquivo, até que o usuario entre com o caractere '0'. c) Feche o arquivo. d) Abra e leia o arquivo caractere por caractere, e escreva na tela todos os caracteres armazenados """ """...
883759cdfc3abcf4479c4be90aace0345815c647
andremenezees/CursoPython
/Aulas/2_Meio/Sorted.py
1,928
4.65625
5
""" Sorted Pode-se utilizar o sorted() com qualquer iterável. Como o proprio nome diz, sorted() serve para ordenar. #O sorted sempre retornar uma lista ordenada, ele não altera o elemento principal no primeiro exemplo ordenados uma tupla, então os elementos da tupla foram ordenados e adicionados a uma lista pelo sor...
4650b779439adebd959c45d91b9806201d290fae
andremenezees/CursoPython
/Aulas/2_Meio/Dictionary_Comprehension.py
943
4.0625
4
""" Dictionary Comprehension Pense no seguinte: Se quisermos criar uma lista: lista = [1, 2, 3, 4, 5] Uma tupla: tupla = (1, 2, 3, 4, 5) Um set: conjunto = {1, 2, 3, 4, 5} Um dicionario dicionario = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} """ #Exemplos numeros = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} quadrad...
568ebef16a011fa75f054455062d3b55e9987f6f
andremenezees/CursoPython
/Aulas/2_Meio/Filter.py
1,721
3.65625
4
""" Filter filter() -> Serve para filtrar dados de uma determinada coleção. filter(função que filtrara, iteravel a ser filtrado) """ #Filtrar os dados para valores acima da media import statistics #dados coletados de algum sensor valores = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1] media = statistics.mean(valores) #vai usa...
a6d69b619fb83a56036ac3c19ba757f87035bcfb
andremenezees/CursoPython
/Aulas/3_Fim/seek_e_cursor.py
3,855
4.40625
4
""" A função seek serve para movimentar o cursor pelo arquivo. """ arquivo = open('texto.txt') print(arquivo.read()) print(f'a:{arquivo.read()}') #movimentando o cursor pelo arquivo com a função seek(). #A função seek() recebe um parametro para informar a posição do cursor. #Estamos lendo apartir do caracter 14. ...
3ca17092d85193700b078c49fe94e463ec862190
andremenezees/CursoPython
/Aulas/1_Inicio/Tuplas.py
810
4.5
4
""" Tuplas(tuple) Tuplas são representadas por () diferente das listas q são [] Tuplas são imutáveis: Isso significa que ão criar uma tupla ela não muda. Não existem tuplas de um elemento -> T = (4) --> não é uma tupla. As tuplas são definidas pela virgula ou seja --> T =(4,) --> é uma tupla. Diferença de uma list...
9084454dee5058420840e69a1a4cda08ec7101e3
sgav191/ISSSearch
/main.py
1,143
3.5
4
import turtle import time import json import urllib.request ISS_URL = "http://api.open-notify.org/iss-now.json" ASTRONAUTS_URL = "http://api.open-notify.org/astros.json" astronauts_response = urllib.request.urlopen(ASTRONAUTS_URL) astronauts = json.loads(astronauts_response.read()) print ("Welcome to ISS Search, an i...
984a39308882316ade112cbfcf6531ad265b23c0
binaoye/algo
/leetcode/Divide/0493_ReversePairs.py
1,246
3.875
4
class Solution(object): res = 0 def reversePairs(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 self.merge_sort(self, nums, 0, len(nums)-1) return self.res def merge_sort(self, nums, left, right): print...
102f8ca1dc333c47f66c288c10be71830208be82
binaoye/algo
/leetcode/meituan/YourCity.py
8,312
3.578125
4
import sys import time import copy class train: def __init__(self, x, y, price, xtime, ytime): self.x = x self.y = y self.price = price self.xtime = xtime self.ytime = ytime class city: def __init__(self, num): self.num = num # train 与 next对应的城市顺序一致 ...
482986782af2a9136d62c0aad79401425cbef02b
binaoye/algo
/leetcode/compete/flipAndInvertImage.py
1,376
3.515625
4
class Solution(object): def findReplaceString(self, S, indexes, sources, targets): """ :type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str """ d1 = {} d2 = {} if len(indexes) == 0: ...
d2f0613067f900fc8ba45b27fe6cfcea2ae6e36e
binaoye/algo
/leetcode/compete/transpose.py
595
3.6875
4
class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ l, m = len(A[0]), len(A) if m == 0: return [] ans = [[0 for i in range(m)] for j in range(l)] print(ans) for i in range(l): ...
c9fba914b425b7158f72e983b556fadf9837a605
juxiangwu/image-processing
/python-code/misc/viennacl-demo.py
3,193
4.28125
4
""" In this example, we investigate the construction and basic usage of PyViennaCL's dense matrix (Matrix) and Vector types, and discuss some important issues about integration with Python and NumPy data types, and PyViennaCL's computational architecture. If you are familiar with NumPy, you might need about 5 minutes ...
689a148cb0ba37bdd2809c9d35023f05e3f7613a
Mohan110594/Code-Breakers-Code
/30.string_sort.py
430
3.859375
4
def stringsort(string1): # Time comp --> o(n) # space comp --> o(n) value=[0 for i in range(26)] for val in string1: if val==' ': continue value[ord(val)-ord('a')]+=1 out='' for i in range(len(value)): out=out+(chr((i+ord('a')))*value[i]) return out if ...
67900e8223b3d1440febd45c96731f1adf75cbbf
Mohan110594/Code-Breakers-Code
/6.Recursion/sum_of_left_leaves.py
1,805
3.828125
4
#DFS #Time comp --> o(n) #space comp --> o(h) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def __init__(self): self.sum1=0 ...
9dfa2a8b7e96e37fe4dda4da8eb86a00df4c1e97
Mohan110594/Code-Breakers-Code
/8.Graphs/Path_sum.py
1,703
3.640625
4
#DFS #Time comp --> o(n) #space comp --> o(h) # 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 from collections import deque class Solution: def hasPathSum(self, root: Tree...
37266f4b9cf6e2d6a47dc1e699e356b69ab7ac6f
Mohan110594/Code-Breakers-Code
/9.DP/Interleaving_string.py
1,604
3.671875
4
#Time comp --> o(mn) #space comp --> o(mn) class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: if len(s3)!=len(s2)+len(s1): return False dp=[[False for i in range(len(s2)+1)]for j in range(len(s1)+1)] dp[0][0]=True ...
3c9403f8c01aec3c188312fba1792a475e19f4f4
Mohan110594/Code-Breakers-Code
/1.Fundamentals/4.Evaluate_rev_polish_notation.py
726
3.640625
4
# Time complexity --> o(n) # space complexity --> o(n) class Solution: def evalRPN(self, tokens: List[str]) -> int: stack=[] for val in tokens: if val!='+' and val!='-' and val!='*' and val!='/': stack.append(val) else: val1=int(stack.pop()) ...
d18ab1ce337d7b3b69355c4055211ba909c3ff2b
tjmode/100DaysOfCode
/day8_linked_list/circular_linked_list.py
643
4.09375
4
class Node: def __init__(self, value): self.value = value self.next = None class Linked_list: def __init__(self): self.head = None def get_head(self): return self.head def insert_node(self, value): new_node = Node(value) if self.head is None: self.head = new_node else: temp...
c827f4d029a17a02115e8f7c9a7d857a5ee6a8c9
rsirazhdinov/geekbrains_algorithm
/les_7/les_7_task_3.py
2,163
3.703125
4
# -*- encoding: utf-8 -*- # 3. Массив размером 2m + 1, где m — натуральное число, заполнен # случайным образом. Найдите в массиве медиану. Медианой называется # элемент ряда, делящий его на две равные части: в одной находятся # элементы, которые не меньше медианы, в другой — не больше медианы. # Примечание: задачу мож...
7e0cf7d48b644965655b146707bf9e14568040e6
rsirazhdinov/geekbrains_algorithm
/les_5/les_5_task_1.py
1,766
3.65625
4
# -*- encoding: utf-8 -*- # # 1. Пользователь вводит данные о количестве предприятий, # их наименования и прибыль за четыре квартала для каждого # предприятия. Программа должна определить среднюю прибыль # (за год для всех предприятий) и отдельно вывести # наименования предприятий, чья прибыль выше среднего и ниже сред...
48d0701f271c8c06334ab9ab64ffb89912bbe7b1
DarkMemem/Homework
/HomeworkLesson5/Drawing_in_the_console.py
452
3.828125
4
h = int(input('Please enter height: ')) i = 0 while i < h: j = 0 while j < h * 2: if h - 1 - i <= j <= h - 1 + i: print('* ', end="") else: print(' ', end="") j += 1 print() i += 1 print() for i in range(h + 1): for j in range(2 * h + 1): if...
35725fa126d7a2ff9297b48d957a6703e910013b
DarkMemem/Homework
/HomeworkLesson7/17_Dictionaries_2.py
412
3.890625
4
text = input("Введите текст: ") words = text.split(" ") count_mapping = {} for j in words: count_mapping.setdefault(j, 0) count_mapping[j] += 1 if all(v == 1 for v in count_mapping.values()): print("В тексте отсуствуют повторяющиеся слова.") else: for word, count in count_mapping.items(): if cou...