blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bd1a656c78aa96049d38aa24fdb16299e66609dd
santiago-quinga/Proyectos_Python
/matrix9.py
245
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:13:36 2020 @author: Santiago Quinga """ import numpy as np matrix=np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.int64) print(matrix) print("\n") print("La matriz Tiene: ",matrix.ndim, " dimensiones")
0bf61fd2e18b26a5333a1d7db931f22b5ba0b2a8
LucasLCarreira/Python
/ex004.py
530
4.25
4
# Exercício Python 004: # Faça um programa que leia algo pelo teclado e # mostre na tela o seu tipo primitivo e # todas as informações possíveis sobre ele. a = (input('Digite algo: ')) print('O tipo primitivo deste valor é {}'.format(type(a))) print('É alfabético?',a.isalpha()) print('É numérico?',a.isnumeric()) print...
9e067912c8eb8c8a5c400c8d8b570b35c63e032d
BigBricks/PythonChallenges
/SumNegCountPos.py
233
3.703125
4
def count_positives_sum_negatives(arr): #your code here pos = 0 neg = 0 for x in arr: if x > 0: pos += 1 else: neg += x if arr == []: return [] return [pos, neg]
20b41691fc0593dd0c92bdd689b57e92e23390ad
Lynette-Zhang/Assessment-3
/a3 game.py
3,318
3.515625
4
import pygame, random from pygame.locals import * def print_text(src, font, x, y, text, color=(250,25,200)): imgText = font.render(text, True, color) src.blit(imgText, (x, y)) def game(screen, lives, score): rect_x, rect_y, rect_w, rect_h = 300, 460, 120, 40 ball1_x, ball1_y = random.randin...
4f8847b77e2a7dbff9d2829c889b4d4d23c2ed63
cabrossman/developingInPython
/LSTM3/sequences_vs_states.py
1,548
4.03125
4
from tensorflow.keras.models import Model from tensorflow.keras.layers import Input from tensorflow.keras.layers import LSTM from numpy import array """Return Sequence""" # define model inputs1 = Input(shape=(3, 1)) """ setting return_sequences=True will return a hidden value for each time step This is required whe...
6ec43ff02d4ac0f8d3a7333674a6d2032885c416
NikhilPrakashrao/PythonProgramming
/CalculateBMI.py
475
4.28125
4
"""SCOPE: 1:Get the input from user 2:use the input to calculate the Body Mass Index """ height=input("Enter the height in Meters\n") weight=input("Enter the weight in kilograms\n") height=float(height) weight=int(weight) bmi=(weight/(height*height)) print(bmi) if(bmi<16): print("The person is underweight") elif(bm...
3c02768e2aec736f2b076f594cd639320671aed2
manueldelatourquintero/weky-bird-en-python
/fisica/Colisiones.py
2,137
3.5625
4
import math from fisica.Punto import Punto class Colisiones: """ Calcula algunas colisiones basicas entre objetos 2D """ def _init_(self, mundo): self.Mundo = mundo def ColisionCirculoRectangulo(self, circulo, rectangulo): """ Comprueba si un circulo colisiona con un rectangulo. No func...
f2a75d2f1876ab1d582ba556948a7336b676cc78
Prem-chouhan/fellowshipProgram_PremsinghChouhan
/Programs/datastructure/primenumber.py
551
3.875
4
from datastructure.Utility import prime1 def main(): while True: try: start = int(input("Enter start of the number:- ")) end = int(input("Enter End of the number:- ")) # for i in range(0, 10): prime_num = prime1(start, end) print(f"Prime number in betwe...
2f2f810576e5526e604e12c8559643d44b48942f
catwang42/Algorithm-for-data-scientist
/valid_palindrome.py
512
3.703125
4
#PROBLEM #maxium remve one char and be palindrome def testPalindrome(): assert validPalindrome('asbcba') is True , "Function error" def validPalindrome(s: str) -> bool: start, end = 0, len(s)-1 while start<end: if s[start] != s[end]: left = s[start+1:end+1] right = s[start...
d819a75c302a40ca4206391e2f7bc8e87bd3544b
bmmtstb/adventofcode
/2022/Day04.py
2,817
3.578125
4
import unittest from typing import Dict, List, Tuple, Set from helper.file import read_lines_as_list Range = Tuple[int, int] RangePair = Tuple[Range, Range] def load_ranges(filepath: str) -> List[RangePair]: """load list from file, get list of two Ranges""" return [( tuple(map(int, range_pair[0].spl...
6bb7970f618c4c620c3b7d1fa3143cc12d71e6e8
Ashutosh-gupt/HackerRankAlgorithms
/Algorithmic Crush.py
1,690
3.609375
4
""" You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusi...
0c0d5baae7687f50b722f54247f53af00cbc3bfa
Sinoh/CalPoly-CPE-103
/Lab 5/list_queue_tests.py
2,428
3.5
4
import unittest from list_queue import * class TestQueue(unittest.TestCase): def test00_interface(self): test_queue = empty_queue() test_queue = enqueue(test_queue, "foo") peek(test_queue) _, test_queue = dequeue(test_queue) size(test_queue) is_empty(test_queue) ...
65d24accfee45199e65672a065f015a335c9592d
us19861229c/Meu-aprendizado-Python
/ExPyBR/ExESPy010.py
251
3.953125
4
""" 10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Farenheit. """ celcs = float(input("Digite o grau em Celcius: ")) faren = (celcs * 9)/ 5 + 32 print(f"O grau {celcs:.1f}ºC corresponde a {faren}ºF")
47124ad31f35c8246feac9cc6e6c8d7e23e35421
aditi0330/Codecademy-Python-for-Data-Science
/Pandas/Modifying_dataframes.py
1,807
4.03125
4
# Modifying dataframes import pandas as pd df = pd.DataFrame([ [1, '3 inch screw', 0.5, 0.75], [2, '2 inch nail', 0.10, 0.25], [3, 'hammer', 3.00, 5.50], [4, 'screwdriver', 2.50, 3.00] ], columns=['Product ID', 'Description', 'Cost to Manufacture', 'Price'] ) # Add columns here df['Sold in Bulk...
034c70b0c8549ca7c7da84b728fe45ac10d0a7c2
HusseinSahib/Egyption-fraction-calculator
/Egyption calculator.py
4,598
4.125
4
#Author: Hussein Sahib #Course: Introduction to programming 142 #Date: December 10 2016 #Program informarion: This program is a Egyption fraction calculator, #it takes a pizza number and number of students then outputs the Egyption fraction for pizza over student. #for extra credit I added a function called extrac...
830b532d426f9dcf7a5d9f628e145fc217dd24d2
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/17_Cleaning Data in Python [Part - 2]/4_cleaning-data-for-analysis/06_custom-functions-to-clean-data.py
2,060
4.15625
4
''' Custom functions to clean data You'll now practice writing functions to clean data. The tips dataset has been pre-loaded into a DataFrame called tips. It has a 'sex' column that contains the values 'Male' or 'Female'. Your job is to write a function that will recode 'Male' to 1, 'Female' to 0, and return np.nan f...
e413a655a2c9f9ecadd04e0d4b7debf7bc9667f0
ZMbiubiubiu/SwordOffer
/reverse_number.py
888
4
4
""" Flow++ 实习生面试题 """ from functools import reduce # 使用str的内置方法 def reverse1(num:int): # 保存符号 symbal = 1 if num >=0 else -1 num = abs(num) return symbal * int(str(num)[::-1]) # 不使用str方法,使用reduce规约方法 def reverse2(num:int): symbal = 1 if num>= 0 else -1 num = abs(num) tmp = [] whi...
d1103e1c80899e8c045201219fa7ef8ef50609a4
jonfang/cmpe273-fall17-ChatBot
/hotel.py
1,122
3.796875
4
class Hotel: def __init__(self, name, s, d, l): self.name = name self.dates = {} self.types = {"single": s, "double": d, "luxury": l} def get_name(self): return self.name def book_room(self, start, end, room_type): booked = True while end >= start: ...
d54ca7b6bc12baf46e932e9d6e242f7c0a39e55d
alqamahjsr/InterviewBit-1
/06_HeapsAndMaps/n_max_pair_combinations.py
1,814
3.515625
4
# N max pair combinations # https://www.interviewbit.com/problems/n-max-pair-combinations/ # # Given two arrays A & B of size N each. # Find the maximum n elements from the sum combinations (Ai + Bj) formed from elements in array A and B. # # For example if A = [1,2], B = [3,4], then possible pair sums can be 1+3 = 4 ,...
1def1cbfa639e5509f57a05c2f51356e3bc33384
Mahmoud-Dinah/data-structures-and-algorithms
/python/code_challenges/graph/graph/graph.py
1,875
3.859375
4
class Vertix: def __init__(self,value): self.value = value class Edge: def __init__(self,vertix, weight=1): self.vertix = vertix self.weight = weight class Graph: def __init__(self): self.adjacency_list = {} def add_vertix(self, value): v = Vertix(value) ...
1e5f1146e4c05edc8b0953e893476382f65c8049
Krishnaarunangsu/ArtificialIntelligence
/src/datascience/datahandling/csv_reader.py
1,907
3.765625
4
# Implementing class of FileReader from abc import ABC import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from src.datascience.datahandling.file_reader import FileReader class CSVReader(FileReader, ABC): """ class for specific implementation of reading a csv file """ def __in...
7ba14438299090997ea4726d665326d7e0631a57
maecchi/PE
/pe112.py
798
3.859375
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # # pe112.py - Project Euler # # 数字(リスト)がはずみ数であるか確認 def isBouncy(nums): is_inc, is_dec = False, False for i in range(len(nums) - 1): if nums[i] < nums[i+1]: is_inc = True elif nums[i] > nums[i+1]: is_dec = True # 増加した状態と減少した状態両方ある場合ははずみ数 # 数字が同じ値が続いた場合は変数が...
f32c71299fc4da3fa86b1600e5d1c61c27f44ee9
bilalsp/enspired
/enspired/coord/_coord.py
658
3.953125
4
class Coord: """Represent a coordinate of old-format plan matrix.""" def __init__(self, x: int, y: int) -> None: """Create a coordinate for plan-matrix cell. Args: x: x-coordinate y: y-coordinate """ self.x = x self.y = y def __repr_...
ce8052789c365baa87ef34e59bc02dfd06b2985d
fp-computer-programming/cycle-3-labs-p22melsheikh
/lab_3-2.py
244
3.984375
4
# Author MEE 09/29/21 x = int(input(" How many points did the team score")) if x >= 15: print("They won the gold!") elif x >= 12: print("They won the silver!") elif x < 9: print(" No Medal") else: print(" They won bronze")
ff289ebb78de5b82e79a7752846a90d8b9af0c5c
RunningShoes/python_lianxice
/5/5.py
213
3.78125
4
filepath='5.txt' letter=[] str='' with open(filepath) as file: f=file.readline() for line in f: str+=line print(str) letter=str.split(' ') for word in letter: print(word) print(len(letter))
b8fd438a1723b11faad19d37aa509c468489533c
anurag9657/Natural-Language-Processing
/nlp_using_regex.py
11,214
3.640625
4
import nltk as n import re from nltk.corpus import stopwords from nltk.stem import * from nltk.tokenize import RegexpTokenizer from collections import Counter # problem 1 # a) funny = 'colorless green ideas sleep furiously'; print(funny.split()) # b) seq = ''; funny = funny.split() for word in funny: ...
a05700e34fc7c5cfa6cc9f4863d00f4e720d36d0
varunkudva/Programming
/AppleStock.py
1,780
4.1875
4
""" Problem: Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. The values are the price in dollars of Apple stock. A higher index indicates a later time You must buy before you sell. No shorting Algorithmi...
dd46bec4b487e470c088b9bcb0a9410b54c9c3e5
CodeMrSheep/LeetCode
/triangle.py
570
3.71875
4
# Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. # [ # [2], # [3,4], # [6,5,7], # [4,1,8,3] # ] class Solution(object): def minimumTotal(self, triangle): """ :type triangle: List[List[int]] ...
27e8fba14821523b638dd604077acdaebcfa827b
blinerabytyqi/DS_1819_Gr13
/Four Square Cipher.py
4,392
3.671875
4
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'] #letter Z ommited def getData(): #get data from user dataInput = input() data = [] for char in dataInput.upper(): if char.isalpha(): data.append(char) return ''.join(data) def makeMatrix(...
99a894692fe8aecd87f1e5d1f86457b11d188068
arwamais/ArwaTest
/BFS.py
900
4.03125
4
""" create a sample graph as a dictionary Where the key is a node and values are next nodes""" graph = { 'a' : ['b', 'c'], 'b' : ['d', 'e'], 'c' : ['f'], 'd' : [], 'e' : ['f','g'], 'f' : [], 'g' : ['a'] } visited = [] # a list of all vis...
995e7b273bda99491ff79ee609d080de27911ba2
PranavBharadwaj-1328/SPOJ
/mul.py
207
3.71875
4
def multiply(): n = int(input()) n1 = [] n2 = [] for i in range(0,n): x,y = input().split() n1.append(int(x)) n2.append(int(y)) for i in range(0,n): print(n1[i]*n2[i]) multiply()
a9e9667b811c3f4eeb18c3ef2ba738255a71cc7e
joaovicentefs/cursopymundo2
/aulas/aula16b.py
369
3.921875
4
lanche = ('Hamburger', 'Suco', 'Pizza', 'Pudim') '''for comida in lanche: print(f'Eu vou comer {comida}') print('Comi muito!')''' '''for c in range(0, len(lanche)): print(f'Eu vou comer {lanche[c]}') print('Comi Muito!')''' for pos, comida in enumerate(lanche): # Essa é outra maneira de mostrar o index da Tupla prin...
96c4cea09752b5648bb3e16d1c1873422cafb688
rtmonteiro/python
/learning free_code_camp/list.py
456
3.796875
4
lucky_numbers = [4, 8, 5, 9, 12] friends = ["Kevin", "Karen", "Kim", "Kade", "Kuzko"] friends.append("Karol") #adiciona no final friends.insert(1, "Kelly") #adiciona aonde quiser friends.remove("Kim") #remove friends.clear() #limpa tudo friends.pop() #elimina o último friends.index("Kevin") #caça a posição do que quis...
db48dcba6bb933cbb77f7b862fda119d32f50a19
ToshikiShimizu/AtCoder
/ARC/001/a.py
257
3.625
4
#coding:utf-8 from collections import Counter n = int(input()) c = list(str(input())) if (Counter(c).most_common()[0][1]==n): least = str(0) else: least = str(Counter(c).most_common()[-1][1]) print (str(Counter(c).most_common()[0][1]) + " " + least)
281b23c5428e0ee5a2db7c2c121ccd318e8ebef8
rdaniela00/proyectos
/python/herencia.py
1,318
3.6875
4
class vehiculos(): def __init__(self, marca, modelo): self.marca=marca self.modelo=modelo self.enmarcha=False self.acelera=False self.frena=False def arrancar(self): self.enmarcha=True def acelearar(self): self.acelera=True def detener(self): self.frena=True def estado(self): print("marca:", se...
bbb439bf93b457f72f3a00924fbdb72e87792a35
Raj6713/Project1
/Graphs/python_scripts/mrl_exponential.py
815
3.9375
4
#Write a program which will create the graph for the mean residual life function and will show it on the screen. import matplotlib.pyplot as plt import numpy as np import math x=np.arange(1e-10,10,0.1) sigma1=2 sigma2=1 sigma3=0.5 sigma4=0.2 y1=[(sigma1*math.exp(-xi/sigma1))/(math.exp(-xi/sigma1)) for xi in x] y2=...
51a3b795585f4d63f383292a6b0609e6ea94612f
Venky1313/venky-python
/second day.py
59
3.515625
4
x=input("Enter name") y=int(input("Enter age")) print(x,y)
753fd4063bfe966ba037eb542be47ad389111369
ksooklall/Python-Projects
/Pramp/Finding_Duplictes.py
1,103
4.09375
4
""" Given two sorted array find of unequal extreme lengths return all duplicates """ # Since both arry are sorted use binary search on the larger to find # T: O(n*log(m)) <> O(m*log(n)) where log(x) x smallest # S: O(1) def find_duplicates(arr1,arr2): # Determine which array is larger smallest, largest = (arr...
449cbb57428491d527aa378b3b3937541f063b12
kouddy3004/learnPython
/BasicPython/basicProgramming/genericConcept/thread.py
553
3.59375
4
from threading import * import time class PrintMessage(Thread): lock=Lock() def __init__(self,message): Thread.__init__(self) self.message=message def run(self): for i in range(5): print(str(i)+" time "+self.message) time.sleep(1) startTime=time.perf_coun...
f3bb3a8472197b928b660368854f850f57d2134a
lollocat3/Coding-Challenges
/palindrome.py
529
3.90625
4
import math import numpy as np def digit_finder(num, index): return ((num%10**index)-(num%(10**(index-1))))/(10**(index -1)) def isPalindrome(x): if x < 0: return False for i in range(int(math.floor(len(str(int(x)))/2))): if int(digit_finder(x, i+1)) ==int(digit_finder(x, len(str(x))-i...
d759712d4c18d72b93a030e6e2b9d14640726087
nangunurimanish/pythonpublic1
/2.py
319
3.96875
4
"""number=['manish',2,'3',4,'5',6,] num=[11,12,13] print(number[1]) number.remove(6) number.pop(2) removed=number.pop() print(removed) print(number) nums=[101,256,348,658,452] nums.sort(reverse=True) print(nums)""" """print('maths' in courses )""" import turtle my_turtle=turtle.Turtle() turtle.done()
d85cc01cf4bc7102f77146bb46c7ffa4e152ac23
salman1819/HackerRank-Problem-Solving
/strange_counter.py
623
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the strangeCounter function below. def strangeCounter(t): lst=[1] temp=1 n=0 while t>=temp: # print('t temp n: ', t, temp, n) lst.append(1+3*(1+2*n)) n=1+2*n temp=lst[-1] print('lst: ...
d35235dab167227393873d917bee3b00164184a9
jakemiller13/School
/MITx 6.00.1x - Introduction to Computer Programming Using Python/fancy_divide.py
2,201
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 30 08:56:56 2017 @author: Jake """ def fancy_divide(numbers,index): try: denom = numbers[index] for i in range(len(numbers)): numbers[i] /= denom except IndexError: print("-1") else: print("1"...
eb95409d7b07b2c20b99cdac06230fc329b1ba9f
Ldarrah/edX-Python
/PythonII/3.3.4 Coding Exercise 2 threewhile.py
829
4.34375
4
mystery_int_1 = 2 mystery_int_2 = 3 mystery_int_3 = 4 #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Above are three values. Run a while loop until all three #values are less than or equal to 0. Every ti...
09f58f9f75eeb31b292e6f8e674091e34645956b
wanguishan/leetcode
/209.长度最小的子数组.py
1,525
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 19 20:18:54 2018 长度最小的子数组: 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。 如果不存在符合条件的连续子数组,返回 0。 ---------------------------------------------------------------------------------------- 示例: 输入: s = 7, nums = [2,3,1,2,4,3] 输出: 2 解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。 @author...
e7a0b2926677495bb55511eb6b08c359fb95e99f
erwin-willems/adventofcode
/day3a/solution.py
233
3.5625
4
#!/usr/bin/env python3 list = open("input.txt").readlines() count = 0 pos = 0 # Skip first line list.pop(0) for line in list: pos += 3 if pos>30: pos = pos - 31 if line[pos]=="#": count += 1 print(count)
beac30b9f0dec0e85dfea71ffdd917c92fff8197
robin9804/RoadToDeepLearningKing
/Jinu/week1/problem93.py
406
3.703125
4
print('네 수를 입력하세요 :', end= ' ') a = int(input()) b = int(input()) c = int(input()) d = int(input()) # 어떻게 한 줄에 입력을 다 받지?? aver = float((a + b + c + d) / 4) def aa(x): res = (x - aver) ** 2 return res boonsan = float((aa(a) + aa(b) + aa(c) + aa(d)) / 4) print("평균 : {}".format(av...
0b7be685c0e24091ac9a644ccb358f168a806406
lucascantos/stocks
/src/functions/execution.py
786
3.515625
4
''' Once decided which asset, if the asset is worth it and how much to buy/sell, Theses strategies decide the best way to implement the action ''' import pandas as pd from src.functions.trends import moving_average def twap(df): ''' time weighted average price effect, reduce impact on market avg(open,c...
a0984657e3caa8413657f4bef93402d92eea417f
punchabird/Learn-Python-The-Hard-Way
/my_adventure_game.py
7,130
4.125
4
from textwrap import dedent from sys import exit class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = cur...
618f42d39cf54e4060230196364b5d92f4d3f909
JKLee6470/Deep_learning_from_scratch-
/computational_graph/mul_layer.py
936
4.28125
4
#곱셈 계층과 덧셈 계층의 구현 class MulLayer: def __init__(self): self.x = None self.y = None #순전파시의 x 와 y의 값을 전역변수로 저장하는 것은, backpropagation시 x 와 y를 사용하기 때문! def forward(self,x,y): self.x = x self.y = y out = x * y return out def backward(self, dout): ...
073dcb8168623d2dfdfb65d2bb0432149fb4b180
gbuchdahl/term_blackjack
/card.py
842
3.90625
4
import typing class Card: def __init__(self, num: int, suit: str): self.num = num self.suit = suit # a function that translates card numbers to names def get_name(self) -> str: if self.num == 11: return "J" if self.num == 12: return "Q" if s...
36a4194e13d5637f85cf7dc691cb861d9891b836
rongzhen-chen/optimization
/optimization.py
10,944
3.640625
4
import time, random, math import numpy as np import matplotlib.pyplot as plt def getminutes(t): x = time.strptime(t,'%H:%M') return x[3]*60+x[4] def printschedule(r): for d in range(len(r)/2): name = people[d][0] origin = people[d][1] out = flights[(origin,destination)][r[2*d]] ...
7a190365f3f04192a07a0375c6c4262540df27d8
Fernando-Rodrigo/Exercicios
/Ex073.py
968
4.1875
4
"""Crie uma tupla preenchida com os 20 primeiros colocados do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Apenas os 5 primeiros colocados. b) Os últimos 4 colocados da tabela. c) Uma lista com os times em ordem alfabética. d) Em que posição está o time da Chapecoense.""" times = ('Flamen...
a9d574ddddec5ac23c3fa6f9bf95517048ef2eb9
qeedquan/challenges
/poj/3048-max-factor.py
1,371
4.0625
4
#!/usr/bin/env python """ Description To improve the organization of his farm, Farmer John labels each of his N (1 <= N <= 5,000) cows with a distinct serial number in the range 1..20,000. Unfortunately, he is unaware that the cows interpret some serial numbers as better than others. In particular, a cow whose seria...
f5e5abcf3ff826f1a5837ba63601d81f44f89b59
geonsoo/HCDE310
/Homeworks/hw1/hw1.py
1,821
3.921875
4
# Geon Soo Park # HCDE 310 # HW1 lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] #fname = "test.txt" fname = "/Users/CalebP/CourseFiles/Homeworks/hw2/hw2feed.txt" #fname = raw_input("Please enter a file name: ") numChars = 0 numLines = 0 numWords = 0 file_name = open(fname, 'r') for line in file_name.readlines(): numLines...
f96a10aaea7b842b1caf389433576aae9ed46ce0
saurabhsisodia/Project_Euler
/smallest_multiple.py
261
3.578125
4
from math import gcd from collections import defaultdict d=defaultdict(int) def lcm(a,b): g=gcd(a,b) return (a*b)//g l=lcm(1,2) d[1]=1 d[2]=l for _ in range(3,41): l=lcm(_,l) d[_]=l #print(d[20]) t=int(input()) while t>0: n=int(input()) print(d[n]) t-=1
ecef4209f34ada4bee73608c84380f2605c8caf4
mgcristino/Toastmasters
/runChangeDate.py
2,509
3.625
4
#!/usr/bin/python # # Change File Date import argparse import os.path, time, datetime dateFormat = "%Y-%m-%d %H:%M:%S" def is_valid_date(parser, arg): """ Check if arg is a valid file that already exists on the file system. Parameters ---------- parser : argparse object arg :...
dbb476461a9685bbb576ba1ad308f90beef3e608
RRedwards/coursework
/05-Principles-Python/a0_2048.py
5,433
3.5625
4
""" Clone of 2048 game. """ import poc_2048_gui import random # Directions, DO NOT MODIFY UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # Offsets for computing tile indices in each direction. # DO NOT MODIFY this dictionary. OFFSETS = {UP: (1, 0), DOWN: (-1, 0), LEFT: (0, 1), RIGHT: (0...
67ecd8d271d544f71fc4ec3900ee94e884cff378
Zero-opps/CYPPedroRR
/libro/problemas_resueltos/Cap-03/problema3-008.py
528
4.03125
4
NUM= int(input("\nIngresa un número entero positivo: ")) if NUM>0: print(f"\nEl resultado de la conjetura de ULAM en el número {NUM}, es: ") while (NUM!=1): print(f"\n{NUM}") if (-1)**NUM>0: print(f"{NUM}/2 = {NUM/2} ") NUM/=2 else: print(f"({NUM}*3)...
cd9edd6275b1f68e471d3a70834951fa2281fe6e
JG0328/programacion-ii-python
/queens.py
1,317
3.75
4
class EightQueens: def __init__(self, size): self.size = size self.solutions = 0 self.Start() def Start(self): positions = [-1] * self.size self.PlaceQueen(positions, 0) print("Se han encontrado: " + str(self.solutions) + " soluciones.") def PlaceQueen(self,...
2d8603a4d21955787543691bbeca2bb8858ecb85
Caaddss/livros
/backend.py
2,283
3.609375
4
import sqlite3 import sqlite3 as sql def iniitDB(): database = "minhabiblioteca.db" conn = sqlite3.connect(database) cur = conn.cursor() cur.execute("""CREATE TABLE livros(id INTEGER PRIMARY KEY, titulo TEXT, subtitulo TEXT, editora TEXT, autor1 TEXT, autor2 TEXT, autor3 TEXT, cidade TEXT, ano TEXT, ed...
b27e94c6e88cf20a267c7a61f2d0241954dca7bb
amirrezamafi/SHAP-integration
/SHAP_integration_v1.py
2,906
3.640625
4
import pandas as pd import numpy as np import shap shap.initjs() def calculate_shap1 (model , data): ''' The input data is a dataframe, consists of only the model`s features columns The shap values by default are toward class_1 Parameters ---------- ...
ce5d7e4704fe6e9f70efee21ecc5ecf0794c2708
iCodeIN/data_structures
/sorting/merge_two_sorted.py
1,080
3.625
4
def merge_two_sorted_arrays(A, m, B,n): a, b, write_idx = m - 1, n - 1, m + n - 1 while a >= 0 and b >= 0: if A[a] > B[b]: # fill in at the end A[write_idx] = A[a] a -= 1 else: A[write_idx] = B[b] b -= 1 write_idx -= 1 while b >= 0: ...
22025c116d03d1626e8b4c337d035a5c290137ff
fwcd/advent-of-code-2015
/src/day07.py
1,105
3.578125
4
import functools import re def parse_circuit(raw): circuit = dict() @functools.lru_cache def wire(x): try: return int(x) except: return circuit[x]() for x, op, y, dest in re.findall(r'([0-9a-z]+)?\s*([A-Z]+)?\s*(\S+)?\s+->\s+(\w+)\n', raw): if op == 'AN...
9cf92c3fc95edd2d2bb0178b8472c5be9101003a
vovunku/NeverNote
/task.py
798
3.53125
4
class Task: def __init__(self, date, name, info, complexity, state): # strings, state in lower case self.date = date self.name = name self.info = info self.state = state self.complexity = int(complexity) easy_color = [50, 205, 50] hard_color = [255, 0, 0] ...
e5d3dc0471a78a81bee10f72f9dbc2ab81808d71
tcarreira/adventofcode
/2020/day-12/solver_1.py
1,488
4.125
4
#!/usr/bin/env python3 import os curdir = os.path.dirname(os.path.realpath(__file__)) # N # W - E # S class Ship: def __init__(self): self.lon = 0 # x self.lat = 0 # y self.direction = 0 # E=0º, N=90º... def get_direction(self): return {0: "E", 90: "N", 180: "W", 270:...
d136c178450cf488e6ae75cfd62921a0b884cbad
jeevananthanr/Python
/PyBasics/tuples.py
590
3.8125
4
#Tuples #constant/immutable list num_tup=(1,5,'hello','Python',1.5) print num_tup,"->",type(num_tup) num_tup=tuple(range(5,11)) #reassign num_tup=tuple(range(1,11)) print num_tup #num_tup[5]=10 --will throw an error #count print num_tup.count(5) #index print num_tup.index(7) print num_tup.index(7,3...
e1e600edfb8923fb855e475ea7963081bd84a07f
jorgeduartejr/Ex-PYTHON
/mundo 2/ex044.py
774
3.96875
4
print('Calculadora de preços') print('--' * 10) valor = float(input('Digite o valor do produto: ')) print('''Escolha uma forma de pagamento: [1] à vista no dinheiro/cheque com 10% de desconto. [2] à vista no cartão com 5% de desconto. [3] em até 2x no cartão (preço normal sem desconto). [4] 3x ou mais no cartao com acr...
f606464c72dae12c4825b05b279b73d22e0dd3dc
nlafferty235/iterative-prisoners-dilemma
/1_3_9-10_sourceFiles/Team 3 - Adrian Jacob Ethan.py
1,751
3.734375
4
import random #### # Each team's file must define four tokens: # team_name: a string # strategy_name: a string # strategy_description: a string # move: A function that returns 'c' or 'b' #### team_name = 'E3' strategy_name = 'Trust Meter.' strategy_description = '''Always start with a collude. Next thre...
bc49251f67052bdb7c8148da2e395a1377451801
prathamtandon/g4gproblems
/Arrays/rearrange_array_elements.py
790
3.984375
4
import unittest """ Given an array A of size n, where every element is between 0 and n-1, rearrange given array such that A[i] becomes A[A[i]]. Input: 3 2 0 1 Output: 1 0 3 2 """ """ Approach: Frankly, don't really know why it works! 1. Increment each A[i] by (A[A[i]]%n)*n. 2. Divide each A[i] by n. """ def rearrang...
d670751b6b6f6e3cc6706a989341dfad82888d9e
dmitryzykovArtis/education
/42.py
1,234
3.5
4
""" Ориентированный граф называется полуполным, если между любой парой его различных вершин есть хотя бы одно ребро. Для заданного списком ребер графа проверьте, является ли он полуполным. Формат входных данных Сначала вводятся числа n ( 1 <= n <= 100) – количество вершин в графе и m ( 1 <= m <= n(n - 1)) – количеств...
9950e64291a837adc79494573406ae1c9f463f34
apapiez/clock_challenge
/Alex/tkinterFramework.py
2,984
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 16 00:33:52 2017 @author: alexp """ import tkinter as tk import time def labelmaker(_master, _text): return tk.Label(master=_master, text=_text) def callback_adder(_element, _callback): _element["command"] = _callback return class Screen(tk.Frame)...
ee2639c0cf19c34d6e9e8ade7fab6ae2729c7b94
eprj453/algorithm
/PYTHON/BAEKJOON/1316_그룹단어체커.py
584
3.578125
4
ans = 0 alphabets = 'abcdefghijklmnopqrstuvwxyz' for i in range(int(input())): checked = [False] * 26 word = input() # isGroup = True # print(i,"번째") for l in range(len(word)-1): checked[alphabets.index(word[l])] = True # print('{} , {}'.format(word[l], word[l+1])) ...
24eec5f0d0bee42161061e8684967bde1705b757
Phoenix-Zura/python-learnings
/4faultycalculator.py
533
4.125
4
op = input("Enter the operation you want to perform:") a = int(input("Enter the number1:")) b = int(input("Enter the number2:")) if op == "*": if a == 45 and b == 3: print("45 * 3 = 555") else: print(a, "*", b, "=", a*b) elif op == "+": if a == 56 and b == 9: print("56 + 9 ...
2b0640188f973c3ba6358b9bac544f5c712fe92a
KirillRedin/PythonTasks
/Ch2/tax_calc.py
721
4.09375
4
""" Program: tax_calc.py Author: Kirill Redin Last Modified 10.11.2018 This program computes person's tax Pseudocode: gross income = Input gross income number of dependents = Input number of dependents income tax = (gross income - 10000 - number of dependents * 3000) * 0.2 print income tax """ # Initialize the consta...
fd25e1cf67132a913359ecbcc5d13eb1374a4f7f
SchlossLab/snakemake_cluster_tutorial
/code/plotcount.py
3,533
3.5
4
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import sys from collections.abc import Sequence from wordcount import load_word_counts def plot_word_counts(counts, limit=10): """ Given a list of (word, count, percentage) tuples, plot the counts as a histogram. Only the first lim...
3b4e66f095f0d76360cc995def3f53a704fd680c
optimum007/python_learn
/python/cubed.py
132
3.9375
4
def print_num(): num = input("数字を入力してね:") num = int(num) multiple = num ** 3 print(multiple)
5e711a0c2a30500407326392a9f9932cc4284474
gamesbrainiac/Project_Euler
/__3.py
709
3.9375
4
__author__ = 'Nafiul Islam' __title__ = 'Largest prime factor' number_in_question = 600851475143 def largest_prime_factor(number_in_question): """Finds the largest prime factor for the given number Args: number_in_question Returns: largest_prime_factor """ diviso...
d1c92b8cb12a0d281283f95219f39e09c0ec01ad
KoliosterNikolayIliev/Softuni_education
/Python OOP 2020/OOP_2020_exam_prep/Python OOP - Exam Preparation - 2 April 2020/tests/test_beginner.py
1,143
3.578125
4
import unittest from project.player.beginner import Beginner class TestBeginner(unittest.TestCase): def setUp(self): self.beginner = Beginner("Gosho") def test_beginner_creation(self): self.assertEqual(self.beginner.username, "Gosho") self.assertEqual(self.beginner.health, 50) ...
341e7c8daa12ff25e20ea3a1fc7f6f644cc169aa
Jangwoojin863/python
/실력향상예제62.py
315
3.765625
4
# 실력 향상 예제 62 import random nums = [0 for i in range(10)] for i in range(100): num = random.randint(1, 9) nums[num] += 1 print("%i, " %num, end='') print("\n--------------------------------------------------------------\n") for i in range(1,10): print("%i : %i" %(i, nums[i]))
cc7da2cb7e1fd9ac49cd9700bcf1924becfd2cd9
eric-s-s/dice-tables
/dicetables/eventsbases/protodie.py
2,202
3.59375
4
""" The abstract class for any die represented by a set of events """ from dicetables.eventsbases.integerevents import IntegerEvents class ProtoDie(IntegerEvents): """ This is the basis for all the dice classes. all Die objects need: - get_size() - returns: int > 0 - get_weight() - returns: int ...
3d0c88397604eaa13f44860c71a91bcf1118309b
jennysol/PythonIntroduction
/Cursopython/PythonExercicios/ex019.py
270
3.59375
4
import random # random usado para sorteio a1= (input('Digite o nome do aluno 1:')) a2= (input('Digite o nome do aluno 2:')) a3= (input('Digite o nome do aluno 3:')) a4= (input('Digite o nome do aluno 4:')) num= random.randint(1,4) print( ' O escolhido foi o aluno', num)
64ce57f9b8d3b2c60dfab85cbcccaeccec054268
nishantchaudhary12/Starting-with-Python
/Chapter 8/average_number_of_words.py
539
4.03125
4
#average number of words def average_words(length_list): print('The average number of words in a sentence is:', format(sum(length_list)/len(length_list), '.2f')) def main(): file = open('text.txt', 'r') length_list = list() line = file.readline() while line != '': line = line.rstrip(...
821e9b6d831be8822d895c7548a09513b7e49335
RamonCris222/Ramon-Cristian
/questao_22_repeticao.py
501
3.9375
4
def euclides(a, b): if b == 0: return a else: return euclides(b, a % b) a, b = int(input("Forneça dois números inteiros positivos: ")), int(input()) if a > 0 and b > 0: print("O MDC entre %d e %d é %d." % (a, b, euclides(a, b))) # 8 e 10: # euclides(8, 10) #...
1691dbfffb888d02d6bc579e6ef0941665a9e20a
langjity/Python-spider
/firstspider/BlogSpider.py
874
3.53125
4
# 编写第一个网络爬虫 from urllib3 import * from re import * http = PoolManager() disable_warnings() def download(url): result = http.request('GET', url) htmlStr = result.data.decode('utf-8') return htmlStr def analyse(htmlStr): aList = findall('<a[^>]*titlelnk[^>]*>[^<]*</a>',htmlStr) result = [] for a...
540da150f8350fa723b913850444b14fbf20da51
DanielCasagallo/ejerciciostkinter
/EjerciciosTkinter.py
3,401
3.8125
4
#Ejercicio 1 from tkinter import * root = Tk() etiqueta1= Label(root, text="Hello Tkinter!") etiqueta1.pack() root.mainloop() #Ejercicio2 master = Tk() whatever_you_do = "Whatever you do will be insignificant, but it is very important that you do it. \n(Mahatma Gandhi)" msg = Message(master, text = whatever_you_do) ...
d7eda712c949a4eb7fe366f496ef9531d3d024fb
chaddymac/learningprojects
/Cats.py
790
4.34375
4
# Given the below class: class Cat: species = "mammal" def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats sam = Cat("sam", 10) lam = Cat("lam", 8) dex = Cat("dex", 7) # 2 Create a function that finds the oldest cat # def...
01853602611b58f10d0e44f8de0874069bf7bd92
darraes/coding_questions
/v2/_leet_code_/0024_swap_node_pairs.py
1,909
3.75
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ node = head if node and node.next: swapper = [node.next, node] t...
0930d27eab577fdfbab898860e6fc0b568264e7f
oran2527/holbertonschool-machine_learning
/math/0x00-linear_algebra/14-saddle_up.py
202
3.53125
4
#!/usr/bin/env python3 """ program to multiply two matrices """ import numpy as np def np_matmul(mat1, mat2): """ function to return the mult of two matrices """ return np.matmul(mat1, mat2)
df7c139f2e00d9e5395da0987d0c824c354e6ef1
FMularski/tkinter-tutorial
/file_dialog.py
578
3.546875
4
from tkinter import * from PIL import ImageTk, Image from tkinter import filedialog root = Tk() def open_file(): global img filename = filedialog.askopenfilename(initialdir='./', title='Select a file', filetypes=(('png files', '*.png'), ('all files', '*'))) file_...
e39bf514c02a1eb450d4bf7767eb654c548c52b4
JoshuaQChurch/SW-Arch-7
/Backup - Python v1.0/User.py
2,917
3.671875
4
import database as db from Mailboxlayer import * import sqlite3 class User(): def __init__(self, first, last, email, password, balance, history): self.first = first self.last = last self.email = email self.password = password self.balance = balance self.transactionHistory = [] def updateName(self): s...
e015059464613c73bac0d31449ecc56d25de28da
thewizardplusplus/robot-fan
/robot_fan/interval.py
720
3.75
4
class Interval: def __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum def __len__(self): return abs(self.maximum - self.minimum) def get_proportion_by_value(self, value): minimum = min(self.minimum, self.maximum) maximum = max(self.mini...
18740161085f569b3db62e172ce82975c6ae1691
bmasoumi/BioInfoMethods
/pattern_count.py
1,434
4.15625
4
# Input: Strings Pattern and Text # Output: The number of times Pattern appears in Text def PatternCount(Pattern, Text): count = 0 # output variable for i in range(len(Text)-len(Pattern)+1): if Text[i:i+len(Pattern)] == Pattern: count = count+1 return count ### DO NOT MODIFY THE CODE ...
12a984a4dacd9ff9586ed4982f764bedd13ffa53
Vostbur/cracking-the-coding-interview-6th
/python/chapter_2/08_loop_detect.py
1,304
3.6875
4
# Для кольцевого связного списка реализуйте алгоритм, возвращающий начальный # узел петли. Определение: # Кольцевой связный список — это связный список, в котором указатель следующего # узла ссылается на более ранний узел, образуя петлю. # Пример: # Ввод: A->B->C->D->E->C (предыдущий узел C) # Вывод: C import unittest ...
5fd4cdd45cd898aab04202ff9340d4c7d68b4dc9
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/705.py
2,229
3.5625
4
#! /usr/bin/python # -*- coding: utf-8 -*- import logging logging.basicConfig(level=logging.DEBUG) def search_winner(line): for values in ("XT", "OT"): if all(char in values for char in line): return values[0] def solve_case(case): grid = case.split("\n") for line in [grid[i] for i in range(4)] + [[grid[j][...
e0d5ec70bc483d21e4aab727ddfa0c50f2d47102
CapGalius/Exercicios-python
/mediaaluno.py
1,591
4.09375
4
nome = input("Digite o nome do aluno: ") valid_nota = False while valid_nota == False: nota1 = input("Digite nota da Prova 1: ") try: nota1 = float(nota1) if nota1 <0 or nota1 >10: print("Nota inválida. Use valores entre 0 e 10") else: valid_nota = True exce...
9f85456cdef9adf6c6bf4ad63463547bdce7fb22
khushi3030/Master-PyAlgo
/Algebra/Set_Union.py
909
4.46875
4
''' Aim: To find the total number of elements in the union of the entered sets. ''' # getting the size of set 1 n1=int(input().strip()) s1=[] s1o=[] # getting the elements of the set 1 s1o=(input().strip().split()) for i in s1o: s1.append(int(i)) # getting the size of set 2 n2=int(input().strip()) ...
8d404551edb1811ef881cfb2a8a8e8f44dad88cf
MrSamuelLaw/excel_sucks
/web_excel_tools.py
3,861
4.46875
4
#!/usr/bin/env python3 import re import argparse from pathlib import PurePath """allows the user write an excel equation in a .txt file then convert that into a single line equation which can be pasted in the excel function bar. Also allows the user to convert relative references into "indirect" function. see the rel...
365acd418090b8b85611edb13dfbfe430ea076ed
GolamRabbani20/PYTHON-A2Z
/DATA_STRUCTURE_AND_ALGORITHMS/C-Algorithms/B-Sorting/Merge-Sort.py
700
3.8125
4
def MergeSort(x,lb,ub): if lb<ub: mid=(lb+ub)//2 MergeSort(x,lb,mid) MergeSort(x,mid+1,ub) Merge(x,lb,mid,ub) def Merge(x,lb,mid,ub): i=lb j=mid+1 k=lb while(i<=lb and j<=ub): if x[i]<=x[j]: b[k]=x[i] i+=1 else: b[k...
ddcc40de8cb40e58afa10df07f2d72cbfd66a702
ImLeosky/holbertonschool-higher_level_programming
/0x03-python-data_structures/6-print_matrix_integer.py
245
3.96875
4
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): cadena = '' for i in matrix: cadena = cadena + '\n' for a in i: cadena = cadena + "{:d} ".format(a) cadena = cadena[:-1] print(cadena[1:])