blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
b6badc5994cf8c14eb9c6df3a12706e4377e4ea8
Isco170/Python_tutorial
/excercises_folder/01_media.py
276
4
4
#nota1 = input("Digite a primeira nota: ") #nota2 = input("Digite a segunda nota: ") nota1 = 17 nota2 = 18 media = (int(nota1)+ int(nota2))/2 #Converti media em string, porque nao aceita concatenar float com string para imprimir print("A media do aluno é de: " + str(media))
3c148406a30b6b44dd5378160ada039da6f84ea5
lanzhiwang/common_algorithm
/leetcode/37_106.py
1,364
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" 106. 从中序与后序遍历序列构造二叉树 根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树: 3 / \ 9 20 / \ 15 7 buildTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]) root = 3 index = 1 root...
71136831e6cda2d39409d8da13d96c6bb286dd99
MichelleZ/leetcode
/algorithms/python/escapeaLargeMaze/escapeaLargeMaze.py
1,131
3.65625
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/escape-a-large-maze/ # Author: Miao Zhang # Date: 2021-04-06 class Solution: def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool: block = set() for b in blocked:...
0249165577c3e712cb93140d5e52be92af495416
vitcmaestro/player
/sine.py
150
3.78125
4
import math deg = int(input("")) rad = deg*(math.pi)/180 if(rad<1 and rad>0): print(round(math.sin(rad),2)) else: print(round(math.sin(rad)))
9c75cb2befa27e9cc053870c7457205c5b0656bf
clusco-2010/clusco-2010
/Release/PythonCode.py
1,919
3.671875
4
import re import string import collections def Histogram(): # Open both the read and the write files with open('frequency.dat', "w") as wp: # Same code as in "ItemCounter" to store the values as a dictionary with open('CS210_P3.txt') as fp: counts = co...
244fe3f6725bd00c05587719d75e312466038fb7
Vagacoder/LeetCode
/Python/LinkedList/Q0002_Add_Two_Numbers.py
2,343
4.03125
4
# # * Question 2. Add Two Numbers # * Medium # You are given two non-empty linked lists representing two non-negative integers. # The digits are stored in reverse order and each of their nodes contain a single digit. # Add the two numbers and return it as a linked list. # You may assume the two numbers do not contain...
110606dc8c2150216752c843a0ea816ea19938ef
mmastin/Tutorials
/tutorial1.py
2,052
3.78125
4
nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] # my_list = [] # for n in nums: # my_list.append(n) # print(my_list) # my_list = [n for n in nums] # print(my_list) # n^2 for each in n in nums # my_list = [n*n for n in nums] # print(my_list) # my_list = map(lambda n: n*n, nums) # print(my_list) # I want n for each n i...
4791cfc1780df006274f8855eeafcfb8d4dfbb29
yuliang123456/p1804ll
/第二月/于亮_p10/aa/build/lib/工厂模式.py
943
3.515625
4
class CarStore(object): def createCar(self,typeName): pass def order(self,typeName): self.car = self.createCar(typeName) self.car.move() self.car.stop() class XiandaiCarStore(CarStore): def createCar(self,typeName): self.carFactory=CarFactory() return self.car...
fe115f6cd70c3276ef11bb7ecdec0fb54b6ccf14
ace7chan/leetcode-daily
/code/202011/20201107_327_countRangeSum.py
609
3.546875
4
from typing import List class Solution: def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: l = len(nums) res = 0 for i in range(l): cur_val = nums[i] if lower <= cur_val <= upper: res += 1 for j in range(i + 1, l): ...
34f9810d64de2a92c087c978f4fd8d1f4482be1f
MadMerlyn/retirepy
/invest.py
2,012
4.25
4
# -*- coding: utf-8 -*- """ Investment Growth Calculator @author: MadMerlyn """ def Invest(principle, reg_payments, rate, **period): """Principle, + regular (monthly) payments, and rate in APR (eg. 0.08) for period use either 'years=XX' or 'months=XX' --Prints estimated growth schedule based on an...
7aae447479d9e8be15cec62fbb71d759d36b1e69
pangyouzhen/data-structure
/string_/longestNiceSubstring.py
449
3.671875
4
from collections import Counter from typing import List class Solution: def longestNiceSubstring(self, s: str) -> str: if len(s) == 0: return "" c = Counter(s) not_include_str = [] for i in c.keys(): if i.lower() in c.keys() and i.upper() in c.keys: ...
5ec18f9ffa6b9a0230a6b9ed206fe9af84e54deb
prakashreddy31189/Pyhtonprakash
/fpt.py
320
4.28125
4
def even(a): return a%2==0 print filter(even,(3,5,6,8,10)) print filter(lambda name: name.startswith('p'), ['hari','prakash','atm']) #filter used only for filter operation in group of elements print 2**3 print map(lambda x: x%3==0,(1,2,3,4,5)) #map is used for manipulation of each element in group of elements
4566eeb384aa01ac58bc08e9487cf8c112f4c15c
pranjudevtale/functiongithub
/return4.py
189
4.03125
4
def number(): num=int(input("enter the number")) i=0 while i<=num: if i%2==0: print(i,"even") else: print(i,"odd") i=i+1 number()
6f6f5fb5c538cfafb557c689c5f7a8e661600e2f
mutedalien/PY
/less_8/main7.py
784
4.25
4
# Набор чисел numbers = [1, 5, 3, 5, 9, 7, 11] # Сортировка по возрастанию print(sorted(numbers)) # Сортировка по убыванию print(sorted(numbers, reverse=True)) # набор строк names = ['Max', 'Alex', 'Kate'] # Сортировка по алфавиту print(sorted(names)) # Города и численность населения cities = [('Moscow', 1000), ('Los...
c231071347c2f819ade100bc5c12a496d96085a8
watorutart/python_prog
/clock.py
901
3.546875
4
import datetime import turtle screen = turtle.Screen() screen.setup(450, 350) screen.tracer(0) # 画面のちらつきを防止。ただしタートルの移動などのアニメーションが行われなくなる time_turtle = turtle.Turtle() time_turtle.hideturtle() time_turtle.setposition(-150, -80) date_turtle = turtle.Turtle() date_turtle.penup() date_turtle.hideturtle() date_turtle.set...
f532e819d14a5170045bae809abde7d788ef8d7a
Azezl/CodeForces_PY
/Problems_Difficulty_800/Word.py
305
3.90625
4
input_string = input() lst = list(input_string) num_upper = 0 num_lower = 0 for i in range(len(lst)): if lst[i].isupper(): num_upper = num_upper + 1 else: num_lower = num_lower + 1 if num_upper > num_lower: print(input_string.upper()) else: print(input_string.lower())
419534e4ef413c4da3a5c8698edc44fcfa019100
RadkaValkova/SoftUni-Web-Developer
/Programming Basics Python/Exam Problems 15062019/Oscars.py
473
3.640625
4
actor_name = input() academy_points = float(input()) jury_number = int(input()) result = academy_points for i in range(1,jury_number+1): jury_name = input() jury_points = float(input()) if result > 1250.5: break result += (len(jury_name) * jury_points) / 2 if result > 1250.5: print(f'Congr...
09c48a27b153238852c79eea84c64a32fc8ba8df
zokaaagajich/Global-Register-Allocation
/lexer.py
1,137
3.59375
4
import lex tokens = ( 'NUMBER', 'VARIABLE', 'OPERATOR', 'LGT', 'ASSIGN', 'IF', 'GOTO', 'IFFALSE', 'RETURN', 'ARRAY' ) def t_NUMBER(t): r'\d+' t.value = int(t.value) return t def t_IFFALSE(t): r'(ifFalse)|(IFFALSE)|(iffalse)' t.value = "ifFalse" return t...
9abbfa2c0792e57b3910bb75f96a3f6855a8c618
Yegaston/testPython
/Condicionales/bucles.py
336
3.921875
4
# for i in ["primavera", "verano", "otoño", "invierno"]: # print(i) # # email = False # dirEmail = input("Introduce tu direccion de email: ") # # for i in dirEmail: # if(i == "@"): # email == True # # if email == True: # print("Correct email") # else: # print("Bad mail") for i in range(4): ...
c17005e21c75eb9bb55a0bb396a5926a3301f9a0
BManduca/Curso_Python3
/06_resultado_aprovacao_aluno.py
3,936
3.921875
4
''' Peça ao usuario as seguintes informações sobre um aluno: Nome Nota prova 1 Nota prova 2 Total de faltas Considere que foram dadas 20 aulas e que para passar o aluno precisa de pelo menos 70% de presença e média 6,0 ou mais. Ao final imprima -> Nome do Aluno -> Média -> Percentual de Presença(assiduidade) -> ...
f967304f0857d12d4d696baa08dedcb29e5bf7f5
robin025/Flappy-Bird-Game
/main.py
7,866
3.5
4
""" Author : Robin Singh Flapy Bird Game Devlopment """ import random import sys import pygame from pygame.locals import * pygame.init() # Game specific Variables for the game FPS = 40 screen_width = 300 screen_height = 500 game_window = pygame.display.set_mode((screen_width,screen_height)) ground_y =screen_height ...
dce657514fe66437d1315753422211a7a1823e95
wingsthy/python
/eg/eg1.py
411
3.65625
4
name = "ada" print(name.upper()) print(name.lower()) first_name = "hello" last_name = "world" full_name = first_name + " " +last_name print(full_name) print("\tPython") print("Language:\nPython\nC\nJavaScript") favorite_language = 'python ' print(favorite_language) favorite_language.rstrip() print(2+4) age = 24 me...
2e8d6685b9b5b6e22e25024278e049e5ac3d0e4c
himani1213/SpringMicroservices
/New Workspace/BasicPrograms/controlprog.py
116
3.78125
4
n=int(input("Enter a number: ")) i=1 while i<n and i<=100: i+=1 if(i%10==0): continue print(i)
853034927ac1da25edb398f5b2cbd805eafc6c62
hongxchen/algorithm007-class01
/Week_09/G20200343040079/LeetCode_787_0079.py
4,400
3.78125
4
#! /usr/bin/env python # coding: utf-8 # 学号:G20200343040079 """ https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题目描述 787. Cheapest Flights Within K Stops Medium There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w. Now given all the cities and fligh...
6f4bd9adc3a050d83032812aa37941219cc49bf9
fl-ada/Toy_programs
/Python_programming/sudoku.py
1,739
3.734375
4
#sudoku #fill_in_box not yet import numpy as np def find_empty(matrix): for i in range(9): prod = int(1) for j in range(9): prod = int(prod*matrix[i][j]) if prod == 0: return i+1 # return empty row, 1-9 return 0 # sudoku completed def fill_in_row(matrix): f...
0f1aed36b74427ad50c9a9fc67f3944163df5755
jansenmtan/Project_Euler
/23.py
1,260
3.625
4
#-*-coding:utf8;-*- #qpy:3 #qpy:console '''Thanks Stack Overflow!''' def factorizer(number,limit): factors = [] gate = isinstance(limit,int) for x in range(1,int(number ** 0.5) + 1): '''if x % round(number / 100) == 0: print("Iteration: {}".format(x))''' ...
0a13894b42fe38779a259891aeea085007f7f27a
Luoxsh6/superintendent
/src/superintendent/controls/timer.py
1,227
3.96875
4
import time from math import nan from contextlib import ContextDecorator class Timer(ContextDecorator): """ A timer object. Use as a context manager to time operations, and compare to numerical values (seconds) to run conditional code. Usage: .. code-block:: python from superintendent.c...
7170cf11792aabb7ea9d265b790c2a4d31f0eaad
BOYGABAS/Activity2-Fibonacci
/fibbonacci.py
2,034
3.984375
4
''' Isaiah Andre Pabillon BSCS-2 2018-5769 Algorithm(Do Better): Combining recursion and iteration algorithm to produce "Andre" algorithm 1) Define a function that has 1 non-default(fib) and 3 default(kawnter,lead and tail) parameters 2) The after every iteration, plug in the sum of the lead ...
2178b28727be547b157bf16959d474e9efce8457
daniel-reich/ubiquitous-fiesta
/GAbxxcsKoLGKtwjRB_16.py
301
3.828125
4
def sum_primes(lst): sum = 0 if len(lst)!=0: for num in lst: if num==2: sum += num elif num==1: continue else: for i in range(2,num): if num%i==0: break else: sum += num return sum else: return None
885a7d173a135e751cc2a0b3ba66a673331528d2
baloooo/coding_practice
/inorder_traversal.py
2,152
4.15625
4
# coding:utf-8 """ Given a binary tree, return the inorder traversal of its nodes’ values. Example : Given binary tree 1 \ 2 / 3 return [1,3,2]. """ def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] Inorder using morris traversal https://en.wiki...
3226bbae5aaeb6172fcaecb6e6b1e55a58354a5a
AayushRajput98/PythonML
/Practice/Tut1/Program12.py
267
4.28125
4
def is_palindrome(s): if s == s[::-1]: print("The string '{0}' is a palindrome string".format(s)) else: print("The string '{0}' is not a palindrome string".format(s)) s=input("Enter the string to be checked for palindorme: ") is_palindrome(s)
fb9b6327e89dbfad188af38427b81f4d69ad1cc3
banalna/pip-services3-commons-python
/pip_services3_commons/convert/IntegerConverter.py
2,237
3.578125
4
# -*- coding: utf-8 -*- """ pip_services3_commons.convert.IntegerConverter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Integer conversion utilities :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ class...
9d030c689096d8f4652003ddf090700dded63317
williamh890/annual_return
/python/annual_return.py
2,937
3.546875
4
import csv import random import time import copy random.seed(time.time()) class Year(object): def __init__(self, year=None, stocks=None, bonds=None, treasuries=None): self.year = int(year) self.stocks = float(stocks) / 100 self.bonds = float(bonds) / 100 self.treasuries = float(tr...
13ff4e38a6849f94813bd02d5791e0cf42c9bdee
DiegoMeruoca/Python4-String
/Ex3-Pesquisa in e not in.py
742
4.4375
4
# Exemplo 3 - Pesquisa in e not in S = "Maria Amélia Souza" # Cria a String print("Amélia" in S) # Verifica se Amelia está na String, neste caso True print("Maria" in S) # Verifica se Maria está na String, neste caso True print("Souza" in S) # Verifica se Souza está na String, neste caso True print("a A" in S)...
627bafe8a115b7ecca57e2bd051698ffb315cc77
ifnfn/haha_video
/kola/singleton.py
409
3.546875
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- class SingletonType(type): def __call__(cls): if getattr(cls, '__instance__', None) is None: instance = cls.__new__(cls) instance.__init__() cls.__instance__ = instance return cls.__instance__ # Usage class Singleton(o...
508077440da08e8da892bf0d7631c634df0cb0c1
jwymanumich/SI650Team
/ir_work.py
4,361
3.53125
4
''' file that handles code for parsing tweet text and doing TFIDF type things ''' import math from document import Document from invertedindex import InvertedIndex class Collection(): ''' Just a bunch of documents ''' def __init__(self): self._documents = [] self.num_docs = 0 self.avg...
1e86b1477e8095224a251a9c3532d9a8e7c199e8
kurama1711/Tic-Tac-Toe
/tic-tac-toe.py
2,671
3.640625
4
cross = True step = 1 moves = {} for i in range(0, 3): for j in range(0, 3): moves[(i, j)] = '-' def print_field(): print(" 0 1 2") for i in range(0, 3): row = str(i) for j in range(0, 3): row += " " + moves[(j, i)] print(row) def game_check(): print_field() for...
6d318977d45d98ba702520934f00f18bb706d7cc
WakeArisato/Personal_Stuff
/Bubble Sorting.py
656
3.78125
4
import time import random List_Range = input("What is the length of your list? ") list = random.sample(range(int(List_Range)), int(List_Range)) def sorting(bad_list): M = int(0) length = len(bad_list) - 1 Sorted = False while not Sorted: Sorted = True for i in range(length): ...
fc0204347dd2ac4e29914007bf37f2fd1d99f6ce
chaotism/python-snake
/my_snake/game_source/snake.py
2,615
3.53125
4
# coding: utf-8 from __future__ import generators, print_function, division, unicode_literals from collections import deque import pygame from random import randrange import sys from pygame.locals import * from graphics import Blocks, Point, DIRECTION_RIGHT from settings import SNAKE_START_LENGTH, SNAKE_SPEED_INITIAL,...
b2ee6358773ea249caf04489d09c993e0ad732ce
Asadullo-aka/python_darslar
/python_10-dars/takrorlash.py
549
3.65625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 13 09:55:26 2021 @author: Asadullo """ #primitiv data types a= int () b=float() c=bool() d=str() #non -pritive data types n1=list() n2=tuple() n3=set() n3=dict() #%% print(*'salom',sep=',',end='?') son= int(input ('son :')) print('son_',son) print(" salom "*5) print(10**...
898f2b3dc6ed130bf7fb1aab68d956d2df3b402e
ChadDiaz/CS-masterdoc
/1.2 Data Structures & Algorithms/Hash Tables II/wordPattern.py
1,366
4.15625
4
""" Given a pattern and a string a, find if a follows the same pattern. Here, to "follow" means a full match, such that there is a one-to-one correspondence between a letter in pattern and a non-empty word in a. Example 1: Input: pattern = "abba" a = "lambda school school lambda" Output: true Example 2: Input: pat...
15a092964af045d2f619f4b2f0034ff8def8bee4
Emfir/task-5
/NumberGuesser.py
974
3.59375
4
import random import enums class NumberGuesser(): def __init__(self): self.numberToGues = random.randint(0 , 100); def nextGuess(self, clientNumber): if clientNumber == self.numberToGues: return enums.resultsOfTheGuess.goodGuess elif clientNumber > self.nu...
03b9a0158268e6850721657f340a2ba9374e2f07
AtIasz/TWweekNo1
/TWweekNO1/MinMaxAvg.py
391
3.6875
4
RandomList=[-5,23,0,-9,12,99,105,-43] numMin=RandomList[0] numMax=RandomList[0] numAVG=0 for i in range(len(RandomList)): if numMin>RandomList[i] : numMin=RandomList[i] if numMax<RandomList[i]: numMax=RandomList[i] numAVG+=RandomList[i] numAVG=numAVG/len(RandomList) print("Maximum: "+str...
35b231b41e328a8d7b37ff1994fde31ed2504ea0
brouse12/othello
/othello_viz.py
2,949
4.1875
4
''' Brian Rouse CS5001 Homework 7 - othello_viz.py December 2, 2018 Module for drawing a game of Othello. Note: some functions take Point objects as arguments. See othello.py module. ''' TILE_RADIUS = 20 import turtle def draw_tile(point, color): '''parameters: x,y coordinates for turtle to draw an Othello til...
7a7b5ec82a43ec332c91726532c00b71ce79629e
goytia54/Epicduelz
/board.py
2,026
3.890625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Dec 6 18:15:23 2016 @author: Michael """ import random import os from prompt import * def board(): playing_board = [[0 for y in xrange(7)] for x in range(7)] #board grid return playing_board def dice_roll(player): roll = random.randin...
59b707eae414f35c4de2ab3007a468507fc82323
TomaszSkrzypinski/kurs_taps_2020
/scripts/pętle.py
342
3.546875
4
liczby = [1, 2, 3, 4, 5] for i in liczby: print(i) for i in range(5, 10): print(i) licznik = 0 while licznik < 10: print(licznik) licznik += 1 licznik2 = 0 while True: print(licznik2) licznik2 += 1 if licznik2 >= 5: break for x in range(20): if x % 2 == 0: ...
5957ba25a4c2d9e2e9f606d595eb4e70a82d795c
Samuel-Sorial/Python-Parser
/parsers/utils.py
1,591
3.75
4
import re import argparse import sys import os # Compile the pattern to improve performance # Inspired by: https://stackoverflow.com/a/1176023/13089670 pattern = re.compile(r'(?<!^)(?=[A-Z])') def pascal_to_snake_case(text): text = text.strip() return pattern.sub('_', text).lower() def extract_args(): ...
ebb71fb4a4cebe86eaba583605906284e589aa23
WeTySun/Python-Algorithms
/InsertionSort.py
759
4.40625
4
# Insertion sort algorithm in the beginning compare the two first elements, compare them and sort in correct order # Then algorithm pick up third element and compare between previous two elements. This algorithm must be write # in very efficient way because for longer and unsorted list it can take longer to compare e...
d47077d467e592c4b0e8bd8815a68a81768ccc11
FabioFortesMachado/WebScraping
/1-web_scraping_paises.py
2,446
3.515625
4
''' Nesse script eu leio as informações dos países deste website https://scrapethissite.com/pages/simple/ Depois eu salvo no MySQL. Aviso: coloque a sua senha para fazer a conexão com o banco de dados e confira se o database exista também, ou crie um ''' import requests from bs4 import BeautifulSoup from mysql.connec...
2cf532b74535e65f17d5ca37f22d04cad5794369
gonzarugil/BD
/Utils/Text.py
1,329
3.6875
4
import re from bs4 import BeautifulSoup from nltk.corpus import stopwords # Import the stop word list from stemming.porter2 import stem import config_vars def textCleaner(input): # 1. Remove HTML # To avoid joining of words when html is cleaned we add spaces input = input.replace("<", " <") input =...
017e84ea12d179e38e0024cfd123a54bf360904d
crazcalm/Py3.4_exploration
/Tk_practice/Basics/learn_windows_and_text.py
4,553
4.25
4
""" In this chapter, we were suppose to build a text editor. However, the code is incomplete and (in some places) incorrect. My new game plan is to write notes on this section. """ """ The below code creates a scrollbar. Issues: ------- Because I do not know how to set the default size of the main window, the enti...
32366e0bca332c49b9607adf0d26a10e3bf77854
AdamZhouSE/pythonHomework
/Code/CodeRecords/2219/60750/257186.py
337
3.546875
4
import math def solve(): num = int(input()) i = 1 while True: tmp = num - i *i if tmp <0: print(False) return else: if tmp - math.sqrt(tmp) * math.sqrt(tmp) == 0: print(True) return else: ...
f1fb18a9f520d798d799bcdeffe14dd2b8e2890f
Wb-Alpha/PythonStudy
/Chapter15/knowledge.py
914
3.671875
4
#Python内置了SQLite3,可以直接使用import导入SQLite3模块 import sqlite3 ''' #连接到数据库文件'mrsoft.db'没有文件会自动创建 conn = sqlite3.connect('mrsoft.db') #创建一个curosr(游标) cursor = conn.cursor() #SQL语句 cursor.execute('CREATE TABLE user (id int(10) primary key, name varchar (20)') #关闭游标 cursor.close() conn.close() #本段代码仅能执行一次,若重复执行则因为user表已经存在而报错 ...
6bc48b7fa38268f4cb4471dc91cb6aff670c70d9
sidd315/BFS-2.1
/employeeImportanceDFS.py
914
3.9375
4
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def __init__(self): self.dataStore = dict() self.result = ...
81a30674bc85c80753876cfaa94bb8d0a61d9077
timothyshort/data_analysis
/03_data_analysis/03-data_analysis-process/21_visuals_quiz.py
877
3.984375
4
# coding: utf-8 # # Exploring Data with Visuals Quiz # Use the space below to explore `powerplant_data_edited.csv` to answer the quiz questions below. # In[4]: # imports and load data import pandas as pd get_ipython().magic('matplotlib inline') df = pd.read_csv('powerplant_data_edited.csv') df.head() # In[7]: ...
a13d878c144a08f1ae62729efdac0b7c74a87afb
catomania/Random-late-night-time-wasters
/ctci/Chapter-1/question_8.py
932
4.40625
4
#Assume you have a method isSubstring which checks if one word is a #substring of another. Given two strings, s1 and s2, write code to check if s2 is #a rotation of s1 using only one call to isSubstring (e.g.,"waterbottle" is a rotation of "erbottlewat"). def rotatedStringHasSubstring(s1, s2): # make sure s1 and s2...
0b76a68a12c43a86f32794f6abfa613bfbbef677
shrutisaxena0617/Data_Structures_and_Algorithms
/all/longestUniqueSubstring.py
418
3.78125
4
def longestUniqueSubstring(mystr): if mystr: i = 0 j = 0 max_len = 0 myset = set() while i < len(mystr) and j < len(mystr): if ord(mystr[j]) not in myset: myset.add(ord(mystr[j])) j += 1 max_len = max(max_len, j-i) else: myset.remove(...
3510b76b69ee2c462837609d79f1ea30976723ee
TheDycik/algPy
/les2/les4.py
1,432
3.71875
4
# 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив # со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5 (помните, что # индексация начинается с нуля), т. к. именно в этих позициях первого массива стоят четные числа. from random import ...
1f3622410bc78a38c83ec9eec32eee2ee5b09d60
deepakpm92/Data-Structures-and-Algorithms-in-python
/recursive_binarysearch.py
675
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 10 11:27:15 2019 @author: d.padmanabhan.menon """ # Recursive Binary Search def binarySearch (arr, low, high, element): if high >= low: mid = int(low + (high - low)/2) if arr[mid] == element: return mid elif arr[mid] > element: return binarySearc...
5b440d20da93d0cd4c212da7271d2558a635cf54
4WHITT04/COM411
/visual/plots/simple.py
234
3.515625
4
import matplotlib.pyplot as plt def display (x, y): plt.plot(x, y) plt.show() def run (): print("displaying data in readable format....") xVal = [1, 2, 3, 4, 5] yVal = [1, 4, 9, 16, 25] display(xVal, yVal) run()
4bbca3fcd2f13517a68056cbb7496be1f248d3fe
srinaveendesu/Programs
/leetcode/day6.py
1,015
3.703125
4
# https://leetcode.com/problems/add-binary/submissions/ class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a, 2) + int(b, 2))[2:] #https://leetcode.com/problems/merge-sorted-array/submissions/ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int)...
359c7a21f8da36c6321cda40afc13cc8aa00b843
sabiul/python-practice
/looop.py
1,506
3.828125
4
__author__ = 'Rashed' # n = 1 # while n <= 10: # print(n) # n = n+1 # n = 1 # while n <= 10: # print(n) # n = n+1 # a = {'name' : 'MD. Maksudur Rahman Khan', 'nickname' : 'Maateen', 'email' : 'maateen@outlook.com', 'phone' : '01711223344'} # # print(a) # print(type(a)) # for item in a: # print(item...
39bd032d717237d92b5f92384fbd5811d92fb0e9
ryu-0406/study-python
/basic/pythonweb/tuple/pythonweb07-01-07.py
579
4.46875
4
# coding:utf-8 # 指定した値と同じ値を持つ要素が含まれているかの確認 mytuple = ("A", "B", "C", "D", "E") print("B" in mytuple) print("D" in mytuple) print("G" in mytuple) # 指定の値と同じ要素が何個タプルに含まれているかの確認 mytuple = ("A", "B", "A", "A", "C") print(mytuple.count("A")) print(mytuple.count("B")) print(mytuple.count("D")) # 指定の値と同じ値を持つ要素のインデックスを取得 my...
9c76fb3e690c309586465dac8f63c9818c80ae25
Divyansh-03/PythoN_WorK
/NewNumber.py
530
4.3125
4
''' If a five-digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits. For example if the number that is input is 12391 then the output should be displayed as 23402. ''' n = int(input( " Enter a 5-digit number ")) temp = n d1=n%10 n//=10 d2=n%10 n//=10 d3=n...
da091469fada726200ea26e1f63d45a5303239b9
devAmoghS/Algorithms-Princeton-University
/quick_find_eager.py
511
3.546875
4
# Eager implementation of the Quick Find algorithm # Problem: Dynamic Connectivity # ** Peformance # 1. is_connected: takes constant time - O(1) # 2. union: takes linear time - O(N) class QuickFindUF: def __init__(self, arr, size): self.arr = [i for i in range(0, size)] def is_connected(self, p, q): arra...
d5a547319776a8616cae6e58ca64812ba8dd8205
magnuskonrad98/max_int
/FORRIT/python_verkefni/leika/circumference.py
214
4.375
4
import math my_radius = float(input("Enter the radius: ")) circumference = 2 * math.pi * my_radius area = math.pi * ( my_radius ** 2 ) print("Your circumference is:", circumference, "and your area is: ", area)
50e14926fce55d9f86860cc109e3f6f424fe1bbb
Seun1609/Python-Training
/Thursday/class_sample.py
1,011
3.78125
4
class Dog: # It should have the properties name, color, weight # It should have the methods bark, eat, sleep def __init__(self, n, c, w): self.name = n self.color = c self.weight = w def bark(self): print("Woof!") def eat(self): print(self.name + " is eating...
05fbaab4600359a57227dd8fa959af5d3c780df0
jfriend08/LeetCode
/CombinationSumII.py
1,240
3.625
4
''' Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, ... , a...
591f431083f1ef79188aaf417e9b6a2707f857b2
ramnathj/CodeArena
/PythonCodes/Ex8.py
322
4
4
''' Sort strings in lexicographic order ''' class Sorting(object): def __init__(self,lst): self.lst=lst def sortStrings(self): self.lst = sorted(self.lst) def printStrings(self): print ','.join(self.lst) s = raw_input() S = Sorting(s.split(',')) S.sortStrings() S.printStrings(...
6e07c33d80e198c58d98e2102115ffb7a41834d0
rafaelperazzo/programacao-web
/moodledata/vpl_data/132/usersdata/189/40905/submittedfiles/al14.py
203
3.9375
4
# -*- coding: utf-8 -*- n=int(input('digite o numero de pessoas:')) soma=0 cont=1 for i in range(1,n+1,1): i=int(input('digite a idade:') soma=soma+i media=(soma/n) print('%.2f' %media)
48a547d778fd39776de9af748974e70e039a7243
MikhailErofeev/a3200-2015-algs
/classic-algs/lab2/Morozov/test.py
335
3.765625
4
__author__ = 'vks' def sieve(n): primes = [True for i in range(n + 1)] primes[0] = False primes[1] = False i = 2 while (i ** 2 <= n): if (primes[i] == True): for j in range(i * i, n + 1, i): primes[j] = False i += 1 return primes n = int(input()) p...
afbc644cdcd7c8ecfae5685e84d7230b2fe3818d
nikhilp93/cmpe287
/arraysort.py
1,107
4.25
4
# Python program to merge two sorted arrays # Merge A[0..n1-1] and # B[0..n2-1] into # C[0..n1+n2-1] def mergeArrays(A, B, n1, n2): C = [None] * (n1 + n2) i = 0 j = 0 k = 0 # Traverse both array while i < n1 and j < n2: # Check if current element of first array is smaller than ...
f9fa8435852de5b4e42a63241bc5b251bae1663b
EduardaValentim/programacao-orientada-a-objetos
/listas/lista-de-exercicio-04/questao1.py
1,450
3.515625
4
# Variáveis para a item 1 a = [] a_sem_ponto = [] item1 = [] # Variáveis para a item 2 item2 = [] # Variáveis para a item 3 c = [] c_sem_ponto = [] item3 = [] # Variáveis para a item 4 d = [] d_sem_ponto = [] item4 = [] # Leitura do arquivo arquivo = open('amazon.csv', 'r') for linha in arquivo: dados = linha.str...
fdf6dd9972fea07abd24ff3b085e867efd16ba8a
xandhiller/learningPython
/picnicItems.py
466
4
4
# Is testing the .center(), .rjust() and .ljust() functions. def printDictionary(d, lWidth, rWidth): print('PICNIC ITEMS'.center(lWidth + rWidth, '-')) for k,v in d.items(): print(("k is: " + k).center(lWidth + rWidth, ' ')) print(("v is: " + str(v)).center(lWidth + rWidth, ' ')) # Must...
0f43c1f32ca27f8d917815f1638f6b06a077ab4c
mmeadx/python-challenge
/PyPoll/main.py
3,355
3.640625
4
#PyPoll - Vote Counting #Thanks to Allan Hunt for the help! #Import add ons import os import csv #Define path to collect data from election_data.csv election_data = os.path.join("Resources", "election_data.csv") #Define Values TotalVotes = 0 #Create Lists & Dictionaries candidate_votes = {} #This will hold unique ...
76c2b53506eecd8cba094bbc9a023817b3b7b72c
ehivan24/learnigPython
/Animal.py
2,077
3.9375
4
''' Created on Jan 12, 2015 @author: edwingsantos ''' class Animal(object): __name = "" __height = 0 __weight = 0 __sound = 0 def setName(self, name): #setter self.__name = name def getName(self): #getter return self.__name def setWeight(self, weight...
d09cd5636e518cf5aa3be4523ff05c1648cf35fd
Symbii/python_Oj
/keyboard_row.py
968
3.734375
4
#!/usr/bin/env python import string import sys import traceback def findwords(list): res=[] flag=1 dict={'q':1,'w':1,'e':1,'r':1,'t':1,'y':1,'u':1,'i':1,'o':1, 'a':2,'s':2,'d':2,'f':2,'g':2,'h':2,'j':2,'k':2,'l':2, 'z':3,'x':3,'c':3,'v':3,'b':3,'n':3,'m':3} for k in list: tem...
81f7b858db7018c07d6f31e2506327b7a9b95872
tsevans/AdventOfCode2020
/day_2/puzzle_1.py
1,378
4.3125
4
# Count the number of invalid passwords based on rules in the input.txt 'database'. def load_input(): """ Load the contents of input.txt into a list. Returns: ([str]): Lines of input.txt as a list of strings. """ with open("input.txt", "r") as infile: lines = [line.rstrip() for line in infile] ret...
a5cfa8c6e56d2508e36e2465801382f63219cec7
ninjaboynaru/my-python-demo
/leetcode/11.py
611
3.625
4
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: i = 0 j = len(height) - 1 areaMax = (j-i) * min(height[i], height[j]) while (i < j): print("i: {}, j: {}, areaMax: {}".format(i, j, areaMax)) if height[i] < height[j]: ...
5fa01e89ffd56a15ae1a26d396740141c6238818
Shawn-H-Wang/Python-Tutorial
/7.5.py
954
3.546875
4
d = {} while True: cho = input("请输入选择功能:1-添加 2-查询 3-退出:") if cho is "1": f = open("dictionary.txt","w") word = input("请输入添加的单词:") mean = input("请输入添加单词的意思:") lw = [word , mean] f.writelines(lw) elif cho is "2": f = open("dictionary.txt","r") ...
9665582f0149cb39bf01e546692a2356e79d0115
stevenwongso/Python_Fundamental_DataScience
/7 Beautiful Soup/0_basic.py
554
3.640625
4
### web scraping: pip install beautifulsoup4 from bs4 import BeautifulSoup ### from html text: soup = BeautifulSoup('<p>Some<b>bad<i>HTML', 'html.parser') print(soup) ### from html file: soup = BeautifulSoup(open('0.html', 'r'), 'html.parser') print(soup) ### from website: import requests r = requests.get("https://e...
d161602381f50dd9976fc299570c516560582811
Reed1114/2020_2d
/grafiske_brugerflader/eks1/knap.py
880
3.515625
4
import tkinter as tk class KnapProgram1(tk.Frame): def __init__(self): tk.Frame.__init__(self) #Her oprettes en knap. Med argumentet "command" vælges hvilken #funktion, der skal udføres når man klikker på knappen. self.button1 = tk.Button(self, text = 'OK', command = self.knap1_act...
b73951e73296ce1b9b681a150d929549748a503e
sanbaideng/Python-SQLite
/SqliteHelper.py
1,222
3.96875
4
import sqlite3 class SqliteHelper: def __init__(self,name=None): self.conn = None self.cursor = None if name: self.open(name) def open(self, name): try: self.conn = sqlite3.connect(name) self.cursor = self.conn.cursor() ...
692057566b2620f899797b0f3e6e3098d54ded51
Bruceaniing/environment
/matlib.py
1,826
3.546875
4
import pandas as pd import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true") df.head() top_10 = (df.groupby('name')['ext price', 'quantity'].agg({'ext price': 'sum', 'quantity': 'count'}) ...
35e037f6d3130e8bbd7f3d445c8873c43725769a
alvaroabascar/algorithmic_toolbox
/challenges/week1/2_maximum_pairwise_product/max_pairwise_product.py
776
3.671875
4
import numpy as np def max_pairwise_product(numbers): idx_max1 = -1 idx_max2 = -1 for i, num in enumerate(numbers): if idx_max1 == -1 or num > numbers[idx_max1]: idx_max2 = idx_max1 idx_max1 = i elif idx_max2 == -1 or num > numbers[idx_max2]: idx_max2 = i...
3764c5838770336bf5ed906ac7762bcab5f574c9
pavelnyaga/MITx_6
/Week-1.Python Basics/set1.py
1,158
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 8 15:58:19 2017 @author: Pavel """ #Assume s is a string of lower case characters. # #Write a program that counts up the number of vowels contained in the string s. #Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. #For example, if s = 'azcbobobegghakl', your program sh...
4f5208b3dab69892a4dee695774ec08fdb112c19
subedisapana/python-fundamentals
/Python Modules & Packages/list_comprehension.py
642
3.921875
4
# square of list and storing in another list l= [100,200,300,400,500,600] l1=[] for i in l: l1.append(i*i) print(l1) #Similarly using list comprehension l2= [100,200,300,400,500,600] l3=[value*value for value in l2] print(l3) #Sum of all the elements l4 = [10,20,30,40,50,60] l5 = [] sum=0 for v in l4: sum=sum...
7a684770293655b93699b2ec08d0c6c77113449a
hardikahalpara/Translator-using-Python
/Translator.py
627
3.71875
4
import tkinter as tk from googletrans import Translator win=tk.Tk() win.title("Translator") win.geometry("250x150") def translation(): word=entry.get() translator=Translator(service_urls=['translate.google.com']) translation1=translator.translate(word,dest="gu") label1=tk.Label(win,text="translated to g...
fd9b120d8c1a0b88d42c95d8feec4a2fac29a2da
JemrickD-01/Python-Activity
/Fibonacci2.py
572
4.34375
4
def myFib(number): if number<=0: return None if number<3: return 1 summ=0 num1=1 num2=1 for i in range(3,number+1): summ=num1+num2 num1=num2 num2=summ return summ only=['y','n'] choice='y' while True: myNumber=int(input("Enter you...
dbf59f2c9f314d1faf5744f374d0269c0e879344
civitaslearning/openclass-python-api
/openclass/api.py
6,769
3.578125
4
import json, requests, urllib class OpenClassAPI(object): """ OpenClassAPI class handles all requests to and from Pearson's OpenClass.com API. Example: get info on a course. >>> oc_api = OpenClassAPI('sam@classowl.com', 'password', 'openclass_api_key') >>> r = oc_api.make_request...
ed44dd41c1f76f4244bf6f837ac6b27430340b58
boro1234/Algorithm
/Anagrams.py
664
4.15625
4
# Given two strings str1 and str2, write a function to determine if str1 is an anagram of str2. The string will only contain lowercase english letters. def anagrams(str1,str2): str1List = [ s for s in str1] str2List = [ s for s in str2] str1Set = set(str1List) str2Set = set(str2List) return str1Set...
3ef299ac5b6ea423efa0a7982e9bcbb3c063c820
lddsjy/leetcode
/python/kthNode.py
1,395
3.546875
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): arr = [] arr = self.minnode(pRoot,arr) print(arr) if k<=len(arr) and k>0: ...
a1aa4505cd02c90e73cdca3262a2b3fb02d9332b
umnstao/lintcode-practice
/binary tree/453.flatten_binary_tree_toList.py
564
3.90625
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ class Solution: # @param root: a TreeNode, the root of the binary tree # @return: nothing def flatten(self, root): if not root: return None ...
c725cef6feff4939ebf55579861960c5cb188a01
kendraregmi/Assignment1
/Assignment/DataTypes/problem40.py
231
4.34375
4
# 40. Write a Python program to add an item in a tuple. tuple1= (1, "Bob", "Kathmandu") add_item= input(" Insert the item to add in tuple: ") tuple2= (add_item,) print(type(tuple2)) new_tuple= tuple1+tuple2 print(new_tuple)
56db65775c008f5f4d555c621efe580e0da5698c
Subaru3000/my_python
/ИТ.py
1,131
3.5625
4
import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/dm-fedorov/pandas_basic/master/data/it.csv') wage = df[df['З/п в валюте найма'].str.contains('₽')] meanWage = wage['З/п в валюте найма'].str.translate(str.maketrans({'₽': '', ',': '.', '\xa0': ''})).astype(float).mean() print('Средняя зарплата по...
1e7ce57a37b25440e448b376bf7d912cacc4614c
Rohan-J-S/school
/seq_neg.py
366
3.9375
4
x = float(input("enter a number: ")) n = int(input("enter nth power: ")) out = 0 sign = -1 for y in range(n+1): sign *= -1 out += (x**y)*sign if y != n: if sign == -1: print(x,"^",y,sep = "",end = " - ") else: print(x,"^",y,sep = "",end = " + ") else: prin...
c49b4601811b1faacebcb2ec13f03a72b2cbab84
dbabby/ForeverLove
/python3/student.py
1,313
4.09375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # def get_grade(self): # if self.score >= 90: # return 'A' # elif self.score >= 60: # return 'B' # else...
dc199ca573cbbe0c9c33e86bfe43d9dc659f3582
sachinjose/100_days_of_code
/Day_2/day2.py
816
3.859375
4
# x# Python has 4 primitive data type 1. Integer 2. String 3. Float 4. Boolean # # Strings # print("Hello"[0]) # print("Hello" + "World") # #Integer # print(123+345) # print(123_456_789) # ## Float # print(3.1415) # ##Boolean # print(True) # print(False) # num_char = len(input("What is your name: ")) # pri...
27ede59a4240ea65507b9a4b132c01249efbbe19
NicVG/curso1-miniproyecto2
/miniproyecto2.py
3,262
3.890625
4
nombres=input("Ingrese los nombres de los jugadores de la siguiente manera:(nombre1) (nombre2)\n") nombres_lista=nombres.split() nombre1=nombres_lista[0][0:3].upper() nombre2=nombres_lista[1][0:3].upper() if nombre1==nombre2: nombre2+="2" print("\n") print(nombre1+" 501") print(nombre2+" 501\n") ...
6e34b6ec628c1dd70405d176ee0258fdb916c1b4
tango1542/Capstone-Lab-1
/q1 guess.py
454
4
4
import random for x in range(1): rando = random.randint(1,20) print (rando) guesses = 0; while True: print ("Guess a number between 1 and 20") guess = input() guess = int(guess) guesses += 1 if rando > guess: print("Too low, guess again") if rando < guess: print ("T...