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 |
|---|---|---|---|---|---|---|
f4877ce87cdf4c457beab854a36410484b6fe6a7 | ignaciorosso/Practica-diaria---Ejercicios-Python | /Estructura secuencial/estr_secuencial4.py | 508 | 3.921875 | 4 | # Escribir un programa en el cual se ingresen cuatro números, calcular e informar la suma
# de los dos primeros y el producto del tercero y el cuarto
num1 = int(input('Ingrese el primer numero: '))
num2 = int(input('Ingrese el segundo numero: '))
num3 = int(input('Ingrese el tercero numero: '))
num4 = int(input... |
6f07bcca69bafd2a27fcfca940c3dfedd796479e | bandofcs/boilerplate-arithmetic-formatter | /arithmetic_arranger.py | 5,491 | 3.890625 | 4 | import re
#Enable checking by printing to console
DEBUG= False
def arithmetic_arranger(problems, count=None):
#Variables definition
#To be printed out
firstrow=list()
secondrow=list()
thirdrow=list()
forthrow=list()
#Length of each operand
firstlen=0
secondlen=0
thirdlen=0
m... |
52cc76357437997addea4a148547c42b0f457751 | daniel-reich/ubiquitous-fiesta | /MbPpxYWMRihFeaNPB_8.py | 123 | 3.734375 | 4 |
def sum_of_evens(lst):
total = 0
for el in lst:
total += sum([num for num in el if num % 2 == 0])
return total
|
3f8f0b0f1d28a1277fea3536766ec20b765c9e2b | phanhr/c4t-20 | /hack3/part3_2.py | 288 | 3.859375 | 4 | computer = {
"HP" : 20,
"Dell" : 50,
"Macbook" : 12,
"Asus" : 30
}
computer["Toshiba"] = 10
for k,v in computer.items():
print(k, ':', v)
computer["Fujitsu"] = 15
computer["Alienware"] = 5
Sum = 0
for eachItem in computer.values():
Sum = Sum + eachItem
print(Sum)
|
b8ca5e3e8c0a3a2616289f75cd14c45be22c7bf6 | AlbinoGazelle/TSTP | /Chapter2/challenge3.py | 164 | 4.0625 | 4 | x = 10
if x <= 10:
print("x is less than or equal to 10")
if x >= 25:
print("x is greater than or equal to 25")
if x > 25:
print("x is greater than 25") |
8b47c306f41b9b343b7c90e9e2a5bd8267cbf79b | rohit98077/pythonScripts | /dateDifference.py | 770 | 4.0625 | 4 | def date_diff(date1,date2):
dateLst=date1.split('/')
d1,m1,y1=int(dateLst[0]),int(dateLst[1]),int(dateLst[2])
dateLst=date2.split('/')
d2,m2,y2=int(dateLst[0]),int(dateLst[1]),int(dateLst[2])
if d2<d1:
if m2==3:
if y2%100 !=0 and y2%4==0 or y2%400==0:
d2+=29
else:
d2+=28
elif m2==5 or m2==7 or m2... |
ad100ef069dcd0fd3a4a0a44a1c9fd451cc53efd | ledao/lufly-im | /scripts/segger.py | 889 | 3.6875 | 4 | from typing import List, Set
class Segger(object):
def __init__(self, words: Set[str], max_len: int=5):
super(Segger).__init__()
self.words: Set[str] = words
self.max_len: int = max_len
def cut(self, sent: str)-> List[str]:
index = 0
segments = []
w... |
8eff17c354245e2833542f701211120bf3e0694b | mcfair/Algo | /Path Sum/437. Path Sum III.py | 3,201 | 3.96875 | 4 | # https://leetcode.com/problems/path-sum-iii/discuss/91892/Python-solution-with-detailed-explanation
"""
Double DFS - elegant
similar to the way we write preorder traversal
Time = O(nlogn) if balanced tree, else worst case O(n^2)
"""
#Find number of paths
class SolutionFindNumberOfPaths(object):
def find_paths(self... |
4ece20b96c9b958a85ea76a960a2765a80a91680 | amakumi/Binus_TA_Session_Semester_1 | /QUIZ 1/QUIZ 1 - #1.py | 297 | 3.90625 | 4 | p = str(input("Input Symbol Character: "))
x = int(input("Input Number: "))
print("")
for row in range(0, x, 1):
for col in range(0, x, 1):
if row == col or (row == x - col - 1):
print(p, end = "")
else:
print(" ", end = "")
print("")
|
8b92c6f01c7ae5125e8075579c4ffc177eb6b87e | alexsidorenko/testing | /main.py | 99 | 3.625 | 4 | my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in my_list:
if i < 15:
print(i)
|
28e3996306992c7ee353f37863b18fa1da09d694 | YusiZhang/leetcode-python | /DFS_BackTrack/array_wordSearch.py | 1,316 | 3.640625 | 4 | __author__ = 'yusizhang'
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board or not board[0]:
return False
n = len(board)
m = len(board[0])
visited = [... |
de9481dc132ceee4e4d068ff3eb52f298b5fbf41 | DreamDZhu/python | /week-4/day29_tcp编程,粘包/tcp粘包/struct模块.py | 696 | 3.515625 | 4 | import struct
num1 = 2147483646
num2 = 138
num3 = 8
# struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型,可以把这里的字符串理解为字节流,或字节数组)。其函数原型为:struct.pack(fmt, v1, v2, ...),参数fmt是格式字符串,关于格式字符串的相关信息在下面有所介绍。v1, v2, ...表示要转换的python值。
ret1 = struct.pack('i', num1)
print(ret1)
ret2 = struct.pack('i',num2)
print(ret2)
r... |
90b661bbea71fe598c1cec93f2a55d50d5b19aac | wycleffsean/coursera-coding-the-matrix | /politics_lab.py | 6,515 | 4.25 | 4 | voting_data = list(open("voting_record_dump109.txt"))
## Task 1
def create_voting_dict():
"""
Input: None (use voting_data above)
Output: A dictionary that maps the last name of a senator
to a list of numbers representing the senator's voting
record.
Example:
>>> creat... |
238203066fa834bab1978997aeaef3527c3c63d0 | sxxzin/Algorithm | /Algorithm04_Bit/Factorial.py | 289 | 3.515625 | 4 | import math
import sys
while(True):
n = sys.stdin.readline().strip()
if(n=='0'):
break
else:
length=len(n)
sum=0
for i in range(1,length+1):
n=int(n)
sum+=int(n%10)*(math.factorial(i))
n/=10
print(sum) |
bcdc7d5e10842d3f0fc699f98f11e7f94a0a7367 | AmitAps/python | /thinkpy/checktriangle.py | 406 | 4.3125 | 4 | first_side = int(input('Enter an integer as a side of tringle: '))
second_side = int(input('Enter an integer as a side of tringle: '))
third_side = int(input('Enter an integer as a side of tringle: '))
def is_triangle(a, b, c):
if ((a > (b + c)) or (b > (a +c)) or (c > (a +b))):
print("No")
... |
d88e32dc9f105c5275ca8ac1c8b1f37cddb630ea | nicoleorfali/Primeiros-Passos-com-Python | /p33.py | 517 | 3.890625 | 4 | # Alistamento Militar
from datetime import date
ano = int(input('Informe o ano em que você nasceu: '))
ano_corrente = date.today().year # pega o ano da data de hoje
mes_corrente = date.today().month
idade = ano_corrente - ano
if idade < 18:
print(f'Você tem {idade} anos. Faltam {18 - idade} ano(s) par... |
1840e1399a0d49a6cb2d153829856b8bdaf72387 | ffarhour/AlmostThere | /Backend/AlmostThere/Tests/UserTest.py | 1,895 | 3.5625 | 4 | import unittest
from User import User
from Stop import Stop
class Test_UserTest(unittest.TestCase):
def setUp(self):
self.user = User(-36.854134, 174.767841)
self.stop = Stop(-36.843574, 174.766931)
def test_Position(self):
position = self.user.position
# Tests t... |
ac64d34e09543f173ac5f4da8fb5494937aadfc3 | Sandeep-Joshi/python_analytics | /Regression.py | 1,611 | 3.84375 | 4 | """
Using Logistic Regression to classify sentences into positive / negative
This script solves the assignment for Week 9 "Improving classification accuracy".
THERE ARE SEVERAL OTHER MODELS (i.e., CLASSIFIERS) THAT ACHIEVE AN ACCURACY SCORE OF > 60%
@author: george valkanas (gvalkana)
"""
from sklearn.feature_extract... |
347dec8c1da84bfab6d2e16f67058b473e54c9a1 | Parz3val83/CSC-111 | /CSCI_2020/assignments/assignment2_pt1.py | 97 | 3.59375 | 4 | # solution 1
a = 2
b = 1
while a <= 102:
print(a, end=' ')
a += b
b = b + 2
|
5c1d425069eb32869f8093d34feb19d457b638f1 | srikarmee7/python-beginner-projects | /acronym.py | 393 | 4.40625 | 4 | #take the input from the user
user_input = input("Enter the value: ")
#split the input value using split funciton
phrase = user_input.split()
#create a empty variable
x = ''
#iterate through the below condition
for word in phrase:
x = x + word[0].upper() #converting the value to uppercase
#print the above output v... |
36abbadd95cc5e37fa2c0dc5ceb528a78447ea2e | trac-hacks/ebs-trac | /py/ebstrac/ebs.py | 10,987 | 4.25 | 4 | '''
Evidence-based scheduling routines.
'''
from datetime import timedelta, date
import random
def count_workdays(dt0, dt1, daysoff=(5,6)):
'''
Return the all weekdays between and including the two dates.
>>> from datetime import date
>>> dt0 = date(2010, 9, 3) # Friday
>>> dt1 = date(2010, 9, 6) # Monday
... |
ae767efb61ea884ad79d0c5cae59de2e2ca4fb7d | maxwellpettit/PythonRobot | /src/pursuit/path.py | 2,784 | 3.578125 | 4 | #!/usr/bin/python3
from pursuit import PathSegment
class Path():
COMPLETION_TOLERANCE = 0.98
segments = []
def addSegment(self, segment):
self.segments.append(segment)
def findGoalPoint(self, xv, yv, lookahead):
"""
Find the goal point on the path for the current vehicle p... |
f7439d604c234e0aa26d3979cd35248726b9b717 | isabella232/sheet2docs | /sheet2docs | 1,906 | 3.65625 | 4 | #! /usr/bin/env python
import csv
import sys
import re
import argparse
parser = argparse.ArgumentParser(description='Convert a CSV of form responses into individual narrative documents.')
parser.add_argument('filename', help='the filename of the CSV to convert')
parser.add_argument('--title', help='the field, if any,... |
47dcfe3237ad7c65149a28c84e680d7cca53efa7 | diolaoyeyele/virtual-learner | /rp.py | 670 | 3.65625 | 4 | class Employee:
empCount = 0
def __init__(self,name,salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def __repr__(self):
return self.name
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
... |
372093f9d5abcae4468f51b5dbc53cd3f86ade51 | Maxclayton/cs1400 | /main2.py | 532 | 3.859375 | 4 | name = input("What is your name? ")
flavor = input("What is your favorite flavor of ice cream? ")
th = int(input("What is the tub Height? "))
td = float(input("What is the tub Diamater? "))
sd = int(input("What is the scoop Diameter? "))
tr = (td/2) #tubRadius
tv = (th*(tr*tr)*3.14159265359) #tubVolume
sr = (sd/2)... |
7d258ed58547ce8fee962e7cfe8caa5663b903be | py-study-group/challenges | /February/amar771.py | 5,399 | 4.1875 | 4 | '''
Caesar cipher
'''
import argparse
import sys
from random import randint
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
def encode(string, key=None):
'''Encodes the string with the key of choice.'''
randomized_key = False
if not key:
key = randint(1, 25)
randomized_key = True
try:
... |
bf2412b4b32dcc5a6f3ca5ab9e8e42e028ac3a21 | pravsingh/Algorithm-Implementations | /Binary_Search_Tree/Python/dalleng/bst_test.py | 2,451 | 3.71875 | 4 | import unittest
from bst import BinarySearchTree
class BinarySearchTreeTest(unittest.TestCase):
def test_insertion(self):
tree = BinarySearchTree()
tree.insert(8)
tree.insert(3)
tree.insert(10)
tree.insert(1)
tree.insert(6)
tree.insert(4)
tree.insert(... |
1d425b99503137eb3d2b8bd9bf313db5c4298a3e | arbwasisi/CSC110 | /decrypter.py | 1,969 | 4.3125 | 4 | # Author: Arsene Bwasisi
# Description: decrypter.py will take in an encrypted file as input along
# with a key file containing the index of the file, and it will
# organize the file into its original order and write it to
# decrypter.txt.
def read_file(text_file, index_file):
... |
ff354fc4527c17fb0752e53493167faf473dd9bc | betty29/code-1 | /recipes/Python/189745_Symmetric_datobfuscatiusing/recipe-189745.py | 1,786 | 3.84375 | 4 | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data... |
4cb4d424f23f64797b8f8754a593bacf61d1ef94 | AdamMC-GL/P3ML | /neuronnetwork.py | 3,863 | 4.5 | 4 | import neuronlayer
class Neuronnetwork:
"""A network of neurons, consists of multiple layers of neurons.
A layer consists out of a set of neurons. """
def __init__(self, layers):
"""Initializes all variables when the class is made.
Contains the list of layers (a set of neurons) w... |
2ffe1b04a53c574fa71264bfe5d66bee1d80299b | drkndl/PH354-IISc | /Week 1/HW1_7_Catalan.py | 497 | 3.734375 | 4 | """
Author: Drishika Nadella
Date: 20th April 2021
Time: 16:09PM
Email: drishikanadella@gmail.com
"""
import numpy as np
import matplotlib.pyplot as plt
# Creating a list with the zeroth Catalan number
C = [1]
# Creating the counter
i = 0
# Calculating and printing Catalan numbers upto 1 billion
while C[-1] <= 10**9... |
78f13b5c52c7f372091de631891b5c16afe1ae6e | shiv-konar/Python-GUI-Development | /1.BlankWindow.py | 192 | 3.859375 | 4 | import tkinter as tk
win = tk.Tk() #Create an instance of the Tk class
win.title("Python GUI") #Set the title of the window
win.mainloop() #The event which makes the window appear on screen |
fd5a37c63b819498b33c0d7f336682848477f599 | owenvvv/recommend_system_anime | /Data Processing/Category.py | 1,506 | 3.65625 | 4 | import pandas as pd
import numpy as np
import scipy as sp
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
anime = pd.read_excel("C:/Users/WU Shijun DD/Desktop/anime_common.xlsx")
anime = anime[:1000]
features = ['Genre','Studio']
def combination(row)... |
f5f63a27adb1d446d01d8f2c323ed68e5e1119d9 | lucaslracz/ContadorPythonIniciante | /variaveis.py | 104 | 3.84375 | 4 | num=int(input("informe um numero: "))
while num<100:
print("\t"+str(num))
num=num+1
print("FIM") |
a62e361073d741582b8caa7358d31dfa23264a34 | cody9898/CS506-Spring2021 | /02-library/cs506/read.py | 673 | 3.9375 | 4 | def read_csv(csv_file_path):
"""
Given a path to a csv file, return a matrix (list of lists)
in row major.
"""
matrix = []
with open(csv_file_path, "r") as f:
lines = f.readlines()
for line in lines:
strings = line.strip('\n').split(",")
row =... |
fc5f676c32d73828d5293ce27ae89ab815c24f62 | Chencx901/leetcode | /problems/twosum_sorted.py | 783 | 4.03125 | 4 | # Given an array of integers that is already sorted in ascending order, find two
# numbers such that they add up to a specific target number.
# The function twoSum should return indices of the two numbers
# such that they add up to
# the target, where index1 must be less than index2.
# Example:
# Input: numbers = [2,... |
38003e97dbef3959893767a7344036e8216b0c75 | j-scull/Python_Data_Structures | /array_stack.py | 1,072 | 4.1875 | 4 | from empty import Empty
class ArrayStack:
"""A python list based implementation of a Stack ADT"""
def __init__(self):
"""creates an empty stack"""
self._data = []
def __len__(self):
"""returns: the number of elements in the stack"""
return len(self._data)
def isEmpty(... |
cf8b38c0ba473254f2c6a7b62e6bc3d29fef235c | tannerbliss/Udacity | /fill-in-the-blanks.py | 6,073 | 4.25 | 4 | # IPND Stage 2 Final Project
# You've built a Mad-Libs game with some help from Sean.
# Now you'll work on your own game to practice your skills and demonstrate what you've learned.
# For this project, you'll be building a Fill-in-the-Blanks quiz.
# Your quiz will prompt a user with a paragraph containing several bla... |
438fd1cc67ae5bc6e5d157c257672ebc34f23f91 | IuryBRIGNOLI/tarefas130921 | /1.py | 210 | 4.09375 | 4 | x = int(input("Digite um número"))
y = int(input("Digite outro número"))
if(x>y):
print("Seu primeiro número é maior que o segundo ")
else:
print("Seu segundo número é maior que o primeiro ") |
5c3c648325b2fcf351679a108b5b5c08737e165c | NustaCoder/DailyCodingProblems_solutions | /prb360.py | 184 | 3.671875 | 4 | lst1 = [1, 7, 3]
lst2 = [2, 1, 6, 7, 9]
lst3 = [3, 9, 5]
lst = [0 for i in range(1, 10)]
lst_or = [lst1, lst2, lst3]
for i in lst_or:
for j in i:
lst[j-1] += 1
print(lst)
|
62ea03a0bb5055985ba0d443d47f764a33f5ea32 | SaveTheRbtz/algo-class | /ex1/brute_force_itertools.py | 666 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from common import parse_file
import itertools
def brute_force(data):
"""
This function should return number of inversions of input stream
>>> brute_force([1,2,3,4,5,6])
0
>>> brute_force([1,3,5,2,4,6])
3
>>> brute_force([6,5,4,3,2,1])
15
... |
371a737fe6bff80e7f91cb40d86cdf8f9caa9ece | SathvikPN/Joy-of-computing-using-Python-NPTEL | /interactive-calculator.py | 1,848 | 3.859375 | 4 | '''
Interactive Calculator
author: Sathvik PN
'''
#Print Instructions about Input
print('''I'm "Calculator"
I perform these operations:
Add[+] Subtract[-] Multiply[*] Divide[/]
Sample Expression input format:
a+b
[only two operands a,b which are real positive numbers]
''')
def feedCalculator(operator,a,b):
... |
1ba9c3805f64c2ee58662c816d4ae072c9d929cd | sailusm/LuminarPython | /flowcotrol/file/covid.py | 482 | 3.5625 | 4 | f=open("C:/Users/USER/PycharmProjects/project1/flowcotrol/file/complete.csv","r")
dict={}
for line in f:
word=line.rstrip("\n").split(",")
# print(word)
country=word[1]
state=int(word[4])
if state not in dict:
dict[state]= country
else:
dict[state]= country
# print(dict)
sortedli... |
239bbe36fc31c91ae8190345151513073275b518 | Prometheus1969/Freshman-Year2-Python | /list1.py | 1,103 | 3.796875 | 4 | #list.py
import random
list1 = list(range(10))
#建立数字列表
print(list1)
list2 = ["Jerry", "Jack111", "Peter"]
#建立字符串列表
print(list2)
list3 = list1
print(list3)
list4 = [ x for x in list2 ]
#利用遍历建立列表
print(list4)
list5 = [1, 2, 3, "a", "b", "c"]
if 10 in list5 :
print("10存在于list5中")
if "d" in list5 :
... |
2604115e10aba3762f712ccbd5bfbf72cae40791 | javierllaca/strange-loops | /challenges/math/euler/44/main.py | 371 | 3.796875 | 4 | from math import sqrt
def is_pentagonal(n):
p = (sqrt(1 + 24 * n) + 1) / 6
return p == int(p)
def find():
i = 1
while True:
i += 1
n = i * (3 * i - 1) / 2
for j in range(i - 1, 0, -1):
m = j * (3 * j - 1) / 2
if is_pentagonal(n - m) and is_pentagonal(n... |
a535274ecb9b063b7785d91267840528afaf01ee | jaalorsa517/ADSI-SENA | /data/get_ciudades.py | 815 | 3.65625 | 4 | # -*- coding:utf-8 -*-
import sqlite3
from sqlite3 import Error
def load():
_CIUDADES = ('ANDES', 'BETANIA', 'HISPANIA', 'JARDIN', 'SANTA INES',
'SANTA RITA', 'TAPARTO')
_PATH_DB = '/home/jaalorsa/Proyectos/flutter/ventas/data/pedidoDB.db'
_ID = 1
print('INICIÓ PROCESO DE CIUDADES'... |
a74b57cfc00b45b578457560e4f544520702ad4a | lradebe/Practice-Python | /duplicate_char.py | 745 | 4.25 | 4 | def duplicate_char(input):
"""This function takes characters as input then displays its duplicates
and doesn't remove the first occurance while it removes the duplicated characters
into a new variable"""
input = str(input)
counter = 0
duplicate_char = ""
characters = ""
for char in inp... |
5da913420374dfdc708cd9f12a9619ceaf08df99 | Talk-To-Code/TalkToCode | /AST/output/program expected outputs/P Progs/BinarySearch.py | 573 | 4.09375 | 4 | def binarySearch(searchList, start, end, num):
if(length >= start):
mid = start + (end - start) / 2
if(searchList[mid] == num):
return mid
elif(searchList[mid] > num):
return binarySearch(searchList, start, mid - 1, num)
else:
return binarySearch(searchList, mid + 1, end, num)
else:
return -1
... |
f4fafdb4f708ad160e1c09075cbf4ac7859b04da | nk900600/Python | /week_1/Algorithm/FindYourNumber/YourNumberBL.py | 875 | 4.0625 | 4 | # ---------------------------------- prg-----------------------------------------------
# My_Number.py
# date : 26/08/2019
# find a number using binary search
def check(N):
i = 0
j = N - 1
while i <= j:
# take a middle number
m = i + (j - i) // 2
# Ask the user is this his numbe... |
2fbe670913a630c49f3ff1fe556bf55065552bcf | anmolparida/selenium_python | /zMiscellaneous/GeeksForGeeks_VMware/LongestCommonSubsequence.py | 1,340 | 4.0625 | 4 | # https://www.geeksforgeeks.org/printing-longest-common-subsequence/
# Dynamic programming implementation of LCS problem
# Returns length of LCS for X[0..m-1], Y[0..n-1]
def lcs(X, Y, m, n):
L = [[0 for x in range(n+1)] for x in range(m+1)]
# Following steps build L[m+1][n+1] in bottom up fashion. Note
# that L[i]... |
5932d8103dfdc0b5bce26a51e5d5bf1b6f18a27e | catboost/catboost | /contrib/python/scipy/py3/scipy/sparse/linalg/_norm.py | 5,662 | 3.671875 | 4 | """Sparse matrix norms.
"""
import numpy as np
from scipy.sparse import issparse
from numpy import Inf, sqrt, abs
__all__ = ['norm']
def _sparse_frobenius_norm(x):
if np.issubdtype(x.dtype, np.complexfloating):
sqnorm = abs(x).power(2).sum()
else:
sqnorm = x.power(2).sum()
return sqrt(s... |
aa7080fed277cfa8b403d5f5981ca6da1db92cda | Coder47890/102 | /imageCapture.py | 958 | 3.6875 | 4 | import shutil
import os
source_path = input("Pls give the path of a Folder you want to take Backup : ")
back_path = input(
"Pls give the path of a Folder where you want to store the Backup : ")
listOfItems = os.listdir(source_path)
for i in listOfItems:
FileName, Extension = os.path.splitext(i)
... |
b6a7eb93aeaecd64116880f2918e6c69a809f217 | amod26/DataStructuresPython | /Check if N and its double exists.py | 372 | 3.890625 | 4 | arr = [7, 1, 14, 11]
# Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
def checkIfExist(arr):
tmp = set(arr)
if 0 in tmp and arr.count(0) > 1:
return True
for num in arr:
if num != 0 and 2 * num in tmp:
... |
3879dd42f57cb17ecefae227dac18d939e8a589b | charles9li/simulate-openmm | /simulate/utils/nested_parser.py | 3,535 | 3.546875 | 4 | from simulate.utils.line_deque import LineDeque
class NestedParser(object):
""" This class takes in a LineDeque instance and creates a new LineDeque
instance that is nested to reflect the nesting based on the specified
bounding characters. The input LineDeque instance should be already created
from th... |
6dfef00b519bf98d5782f4cac0bea939c39bfe95 | sam1208318697/Leetcode | /Leetcode_env/2019/6_21/Spiral_Matrix.py | 1,512 | 3.625 | 4 | # 54. 螺旋矩阵
# 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
# 示例 1:
# 输入:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# 输出: [1,2,3,6,9,8,7,4,5]
# 示例 2:
# 输入:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution:
def spiralOrder(self, mat... |
c57f8c15480e748dc1690118ef81df4b858f0466 | teamclouday/Mooner | /DataProcess/json_to_csv.py | 519 | 3.5 | 4 | # Just found that the json file is difficult to view in vscode
# so convert it to a CSV
import os
import json
import pandas as pd
if __name__ == "__main__":
name = "tweets_200"
with open(name+".json", "r") as inFile:
data = json.load(inFile)
df = []
for userid in data.keys():
tweets = ... |
05845337937003b283a8f7a918a372916b8d9f63 | emilypng/python-exercises | /Packt/act2.py | 131 | 3.828125 | 4 | """
Determining the pythagorean distance between 3 points.
"""
x, y, z = 2, 3, 4
result = (x**2 + y**2 + z**2)**0.5
print(result)
|
04517b8c252eac09be50353b3b2f111278b836d5 | jovit/mc906 | /project_2/genetic_algorithm.py | 3,597 | 3.65625 | 4 | import random
class Individual(object):
def __init__(self, chromossome_mutation_rate=0.):
"""
Generate a new individual
"""
self.chromossome_mutation_rate = chromossome_mutation_rate
pass
def fitness(self):
"""
Calculate self fitness value
:retu... |
d1b470a9bfe00fe8d695a1f97f7d15c89d7635fc | vqpv/stepik-course-58852 | /7 Циклы for и while/7.4 Цикл while/5.py | 101 | 3.90625 | 4 | num = int(input())
summa = 0
while num >= 0:
summa += num
num = int(input())
print(summa)
|
6cc04c765b5398cbc42805cad38252ccd2e64b40 | Alexander8807/Reposit | /Списки.py | 3,233 | 4.0625 | 4 | a_list = []
print(type(a_list))
a_tuple =()
print(type(a_tuple))
a_set = set()
print(type(a_set)) #типы список, кортеж#
some_list = [1243464, 123.00023, "Some string", True, None, [1234, "New string", False]]
print(some_list) #список внутри списка#
print(some_list[0:3]) ... |
539154f81534eb8e88423b8795f604b9ab28cea8 | pymft/mft-01 | /S05/files_and_with_block/read_lines_file.py | 195 | 3.765625 | 4 | f = open("input.txt", mode='r')
line = f.readline()
print(line)
# print("hello")
# print("salam\n")
# print("salut")
# EOF
while line != '':
line = f.readline()
print(line)
f.close() |
6c439d669bd1a90bc2f2355657931bad72dc03ec | SardulDhyani/MCA3_lab_practicals | /MCA3HLD/20711136 - Himanshu Chandola/Codes/Statistical_Concepts_and_Linear_Algebra/standard_deviation.py | 465 | 3.734375 | 4 | # Himanshu Chandola MCA 3 - HLD Campus STD ID-20711136
observation = [11,15,14,12,10]
sum=0
for i in range(len(observation)):
sum+=observation[i]
mean_of_observations = sum/len(observation)
sum_of_squared_deviation = 0
for i in range(len(observation)):
sum_of_squared_deviation+=(observation[i]- mean_of_ob... |
c75c99ab983b2bffb8f1840a6f949e0c08053c00 | AntonOni/interview | /Solutions_P1_P2/String/S-P1_929_Unique_Email_Addresses.py | 474 | 3.546875 | 4 | emails = ["test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"]
def solve():
result = []
for i in emails:
email = i.split("@")
left = email[0]
right = email[1]
if "." in left:
left = left.replace("."... |
8fd95469f1d0dddaebbbaf9903ff4ba8db6101c8 | maarten1001/advent-of-code-2020 | /day08/part2.py | 1,160 | 3.59375 | 4 | # get the input file
f = open("input.txt")
entries = f.read().splitlines()
f.close()
for fix in range(len(entries)):
acc = 0
i = 0
executed = [False for x in range(len(entries))]
print("Fixing line " + str(fix + 1))
while True:
if i == len(entries):
print("Achieved termination b... |
830802e627fe7aaed1057d4ed66ccadf532bf357 | tanpv/awesome-blockchain | /algorithm_python/move_zeros_to_end.py | 378 | 4.25 | 4 | """
Write an algorithm that takes an array and moves all of the zeros to the end,
preserving the order of the other elements.
move_zeros([false, 1, 0, 1, 2, 0, 1, 3, "a"])
returns => [false, 1, 1, 2, 1, 3, "a", 0, 0]
The time complexity of the below algorithm is O(n).
"""
input_list = [false, 1, 0, 1, 2, 0... |
07b76072b8d00f6f251c3f286ece31f522abe5d7 | rgj7/coding_challenges | /codeabb/Python/p28_body_mass_index.py | 497 | 3.75 | 4 | """
CodeAbbey, Problem 28
Coded by Raul Gonzalez
"""
def body_constitution(weight, height):
bmi = weight / (height**2)
if bmi < 25:
return "under" if bmi < 18.5 else "normal"
else:
return "over" if bmi < 30 else "obese"
def main():
n = int(input())
results = []
for _ in range... |
c9586a188539e51edd49dd9f38e05a15d1982dad | jsebastianrincon/curso_python | /Fundamentos/operadores_logicos.py | 558 | 4.1875 | 4 | # Variables
#a = int(input("Ingrese un valor: "))
a = 3
valorMinimo = 0
valorMaximo = 5
dentroRango = (a >= valorMinimo and a <= valorMaximo)
# Condicional If
if(dentroRango):
print("Esta en el rango")
else:
print("Esta fuera del rango")
vacaciones = True
diaDescanso = False
if(vacaciones or diaDescanso):
... |
70599342ebfa288044941ee9ff5afab7eb59ee3c | MiyabiTane/myLeetCode_ | /30-Day_Challenge/25_Jump_Game.py | 337 | 3.6875 | 4 | def canJump(nums):
#その位置から最後のマスにたどり着けるのがGoodマス
Good_left = len(nums) - 1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= Good_left:
Good_left = i
if Good_left == 0:
return True
return False
ans = canJump([3, 2, 1, 0, 4])
print(ans)
|
3953086c2492ace42a368e8a026935f2a7605621 | Airedyver/mars_data_scraping | /scrape_mars.py | 6,845 | 3.78125 | 4 | #NASA Mars News
#Scrape the NASA Mars News Site and collect the latest News https://mars.nasa.gov/news/
#Title and Paragragh Text. Assign the text to variables that you can reference later.
# import dependencies
# Dependencies
from os import getcwd
from os.path import join
from bs4 import BeautifulSoup as bs
import re... |
67ed844d101704d3872310eb55ef5019de88e339 | CateGitau/Python_programming | /Packt_Python_programming/Chapter_3/exercise41.py | 371 | 3.5625 | 4 | l = [2, 3, 5, 8, 11, 12, 18]
search_for = 11
slice_start = 0
slice_end = len(l) - 1
found = False
while slice_start <= slice_end and not found:
mid = (slice_start + slice_end)// 2
if l[mid] == search_for:
found = True
else:
if search_for > l[mid]:
slice_start = mid + 1
... |
deda61c674e0451af9837ea78a24d242249ac8f7 | jareiter/PHYS202-S14 | /SciPy/Differentiators.py | 1,113 | 3.796875 | 4 |
import numpy as np
def twoPtForwardDiff(x,y):
"""
Returns the derivative of y with respect to x using the forward
differentiation method
"""
dydx = np.zeros(y.shape,float)
dydx[0:-1] = np.diff(y)/np.diff(x)
dydx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2])
return dydx
def twoPtCentered... |
518d99a7efacd05e3ca56b246236bb400400a76a | brockryan2/Python_practice | /trying_out_classes.py | 1,593 | 3.515625 | 4 | # trying_out_classes
from pprint import pprint as pp
class Flight:
def __init__(self, number, aircraft):
if not number[:2].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:2].isupper():
raise ValueError("Invalid airline code '{}'".format(number))
if not... |
8bdb89ee4cbd9a9038324697c3218efad8029dd5 | Lovely-Professional-University-CSE/int247-machine-learning-project-2020-kem031-sumant_42 | /work.py | 1,165 | 3.578125 | 4 | from sklearn import datasets
import pandas as pd
import numpy as np
context="""This dataset contains complete information about
various aspects of crimes happened in India from 2001.
There are many factors that can be analysed from this dataset. Over all,
I hope this dataset helps us to understand better abou... |
70a4d0b0dc91e124d7bbf5add67c2f243576c86b | bssrdf/pyleet | /B/BullsandCows.py | 2,255 | 4.34375 | 4 | '''
-Medium-
*Hash Table*
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes
a guess, you provide a hint with the following info:
The number of "bulls", which are digits in the guess that are in the correct... |
ad65f94b48ed9de2763e68d73e2efb5d5e886410 | seanchen513/dcp | /linked_list/dcp078_merge_k_sorted_LLs.py | 6,271 | 3.984375 | 4 | """
dcp078
This problem was asked recently by Google.
Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list.
"""
import heapq
class Node():
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def __repr__(self):
... |
e2f9621ffb1ae2a2e8f839c97645812677e7d698 | czh4/Python-Learning | /exercise/exercise2-1.py | 313 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 12 16:13:19 2018
@author: andychen
"""
y=int(input("Year:"))
if y%4==0:
print(y," is a leap year")
elif y%100==0:
print(y," is not a leap year")
elif y%400==0:
print(y," is a leap year")
else:
print(y," is not a leap year")
|
25cc8d1666af74edfa2b9ee471efc1ded8c2fb3f | prathamdesai13/SortsNsuch | /RandyDandyProblems.py | 19,093 | 3.796875 | 4 | import math
from collections import Counter, OrderedDict
from operator import itemgetter
from DataStructs import *
def minimumBribes(q):
n = len(q)
num_bribes = 0
bribes = [0] * n
i = 0
while i < n - 1:
if q[i] > q[i + 1]:
bribes[q[i] - 1] += 1
num_bribes += 1
... |
6461becb3ef2198b34feba0797459c22ec886e4c | OrSGar/Learning-Python | /FileIO/FileIO.py | 2,953 | 4.40625 | 4 | # Exercise 95
# In colts solution, he first read the contents of the first file with a with
# He the used another with and wrote to the new file
def copy(file1, file2):
"""
Copy contents of one file to another
:param file1: Path of file to be copied
:param file2: Path of destination file
"""
des... |
48918109e3172f1dd5dfbd4bdc45fac38a5be7d8 | Aasthaengg/IBMdataset | /Python_codes/p04011/s047238137.py | 122 | 3.734375 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a<= b:
print(a*c)
else:
print(c*b +(a-b)*d) |
180fb10c4fd193dbcd5b390d43061c1c2addf494 | srmchem/python-samples | /Python-code-snippets-201-300/216-Base64 encode and decode.py | 804 | 3.640625 | 4 | """Code snippets vol-44-snip-216
Base64 encode and decode a file.
By Steve Shambles
Feb 2020
stevepython.wordpress.com
Download all snippets so far:
https://wp.me/Pa5TU8-1yg
Requirements:
A text file called test.txt in current directory.
Base64 is part of the standard library.
"""
import base64
with... |
50c7142cd513045f7dd6014b2df48fbbee3226b4 | SinghGauravKumar/Project-Euler-Python-Solutions | /euler_problem_092.py | 507 | 3.6875 | 4 |
import sys
if sys.version_info.major == 2:
range = xrange
def compute():
ans = 0
terminals = (1, 89)
for i in range(1, 10000000):
while i not in terminals:
i = square_digit_sum(i)
if i == 89:
ans += 1
return str(ans)
def square_digit_sum(n):
result = 0
while n > 0:
result += ... |
108fa1ed16d993bcec202d8923fc1a15afcf0ef1 | guoyuMao/python_study | /Function.py | 1,408 | 4.03125 | 4 | # def area(width,heigh):
# return heigh * width
#
# print("please input width:")
# w = int(input())
# print("please input height:")
# h = int(input())
# print("this area is : %d" %area(w,h))
'''不可变对象与可变对象'''
#不可变对象
# def changeInt(a):
# a = 10
# b = 2
# changeInt(b)
# print(b)
# #可变对象
# def changeme(list):
# ... |
3048d4dcc2111ea420cdf6d6ab6df488a9060eb6 | Rafaellinos/learning_python | /projects/email/email_test.py | 907 | 3.578125 | 4 | import smtplib
# smtp = simple mail transfer protocol
from email.message import EmailMessage
from string import Template # uses to substitute the $ in html file
from pathlib import Path # os.path
html = Template(Path('email.html').read_text())
print(html)
with open("mail_inform.txt", "r") as f:
user = f.readlin... |
043ffadcf4968b4e2c6612c9c46216bed3dccdfb | wangzhaozhao1028/Only-Al | /python_Matplotlib/Figure_1.py | 799 | 3.53125 | 4 | #coding=utf-8
import matplotlib.pyplot as plt
import numpy as np
"""
数据可视话 教程
http://study.163.com/course/courseLearn.htm?courseId=1003240004#/learn/video?lessonId=1003683066&courseId=1003240004
设置坐标轴
"""
x = np.linspace(-3,3,50)
y1 = 2*x+1
y2 = x**2
# plt.figure()
# plt.plot(x,y1)
plt.figure(num=3,figsize=(8,5))
p... |
40eb6136b39079f56f57f47ba86c5fc48ceed7eb | jmak24/CS50-2017 | /pset6/credit.py | 2,608 | 4.21875 | 4 | import cs50
# Initialize variables
digit_shifter = 10
even_digit_sum = 0
odd_digit_sum = 0
total_sum = 0
last_digit = 0
first_digit_is_even = False
even_final_digit = 0
odd_final_digit = 0
# Prompt user for Credit card Number
print("Number:", end="")
credit = cs50.get_float()
# Initialize digit shifter
i = 0
while... |
f79c479f3863f4e14fa164dd18f862c012eae6fb | menghaoshen/python | /99.练习题/hello.py | 154 | 3.921875 | 4 | i='hello world'
print(i)
#利用循环依次对应list中的每个名字打印出hello,xxx
L = ['bart','Lisa','Adam']
for i in L:
print('hello',i)
|
cc9793102b4f0f9c6088622de6dd4a6a557d1a89 | sgriffin10/ProblemSolving | /Classwork/Sessions 1-10/Session 6/conditional-demo.py | 1,225 | 4.09375 | 4 | # 1.0
# age = int(input("Please enter ur age: "))
# print(f"Your age is {age}.")
# if age>=18:
# print(f'Your age is {age}.')
# print("You are an adult.")
# elif age>= 10:
# print("You are a teenager.")
# else:
# print("yung boi")
#2.0
# age = 20
# if age >= 6:
# print('teenager')
# elif age >= 1... |
2f721ea00749373444d7a40a36e57ec4bad83e0a | a01375832/Actividad_06 | /actividad06_1.py | 1,526 | 3.9375 | 4 | #Encoding: UTF-8
#Autor: Manuel Zavala Gmez
#Actividad 6
def encontrarMayor(num,lista):
print("El numero ms alto es: ", max(lista))
def recolectarInsectos(dia,insectos,acumlador):
while acumlador<30:
insectos=int(input("Numero de insectos recolectados de hoy"))
if insectos<=30:
... |
52887cedfd203834bd9da717ed73144bbbdfeb16 | HorusDjer/gitty | /find_unique_int.py | 466 | 3.609375 | 4 |
# fast attempt O(N)
def find_uniq(arr):
counts = {}
for num in arr:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
for num in arr:
if counts[num] == 1:
return num
# bad attempt O(n^2)
def find_uniq_(arr):
for num in arr:
if... |
640cc2582708584403f166c48d37c962df807b66 | daniel-reich/ubiquitous-fiesta | /pn7QpvW2fW9grvYYE_21.py | 308 | 3.671875 | 4 |
def find_fulcrum(lst):
for i in range(len(lst)):
sum_left = 0
sum_right = 0
for j in range(0, i):
sum_left += lst[j]
for j in range(i+1, len(lst)):
sum_right += lst[j]
if sum_left == sum_right:
return lst[i]
return -1
|
ce9ec1bcf55a61474cc31f04c8b32d2dbcf5d57d | SierraSike20/SuvatSorter | /suvat.py | 9,070 | 3.90625 | 4 | def one(v, u, a, t):
print(str(v + " = " + u + " + " + a + " * " + t))
def two(s, u, v, t):
print(str(s + " = " + " ( " + u + " + " + v + " ) " + " * " + " 1/2 " + " * " + t))
def three(v, u, a, s):
print(str(v + "^2 " + " = " + u + "^2 " + " + " + " 2 " + "*" + a + " * " + s))
def four(s, u, t,... |
84f2d8cf92d946aedba18b21ae6bc00e49018e30 | tymscar/Advent-Of-Code | /2020/Python/day10/part1.py | 511 | 3.671875 | 4 | def part_1():
file = open('input.txt', 'r')
jolts = [0]
highest = 0
one_jumps = 0
three_jumps = 0
for line in file:
line = line.strip("\n")
jolts.append(int(line))
highest = max(highest, int(line))
jolts.append(highest + 3)
jolts = sorted(jolts)
f... |
d4a08e2ce6357d3904c0bf269f6b918526f6849d | afcarl/notebooks-1 | /dataset_specific/housing/preprocess.py | 8,027 | 3.515625 | 4 | import math
import pandas as pd
def combine_categories(df, col1, col2, name):
"""Combine categories if a row can have multiple categories of a certain type."""
# Find unique categories
uniques = set(pd.unique(df[col1])) | set(pd.unique(df[col2]))
# Merge different columns
all_dummies = pd.get_dumm... |
288cd72507d3fab705319d939a851441342e5bc0 | melvinzhang/counter-machine | /mult.py | 1,984 | 3.75 | 4 | # Correctness verified by testing all tuples (i,j) where 0 <= i,j < 100
def odd(n):
return n % 2 == 1
def even(n):
return n % 2 == 0
def div3(n):
return n % 3 == 0
def div5(n):
return n % 5 == 0
# Implemention of Schroeppel's algorithm for multipling two numbers using a 3 counter machine
# Trick to... |
62cf1a278e484a7a71633036d652d468c8491eaa | dmaynard24/hackerrank | /python/algorithms/implementation/grid_search/grid_search.py | 368 | 3.5625 | 4 | def grid_search(g, p):
for i in range(len(g) - len(p) + 1):
index = g[i].find(p[0], 0)
while index > -1:
for j in range(1, len(p)):
if g[i + j][index:index + len(p[j])] != p[j]:
break
elif j == len(p) - 1:
return 'YES'
# look for next index in same string
... |
e779b88346043b39d7664abd59393a27b6e13926 | ArroyoBernilla/t07_Arroyo.Aguilar_ | /arroyo/iteracion_en_rango4.py | 407 | 3.703125 | 4 | import os
#declaracion de variables
m,n=0,0
#imprimir los numeros que se encuentran en cierto intervalo
#input
m=int(os.sys.argv[1])
n=int(os.sys.argv[2])
#ouput
print ("Despues de resolver la inecuacion racional ")
print("Dar como respuesta los numeros que hacen que la solucion exista")
print("Rpta: ")
#iterador_r... |
2df665c759713eac344cc875d1fad930cd149693 | splice415/Python-stuff | /Python Scripts/List Comprehensions.py | 1,986 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 27 01:39:35 2015
@author: Tommy Guan
"""
"""Print even numbers
"""
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print(evens_to_50)
"""Doubled numbers evenly divible by two, three, four
"""
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0] ... |
51455bdc12e92ef8e4fb604c3a60886b122d3cc6 | highing666/leaving | /src/leetcode/91lalg/implement_queue_using_stacks.py | 782 | 3.546875 | 4 | # -*- coding: utf-8 -*-
class MyQueue:
def __init__(self):
self.stk_a = []
self.stk_b = []
def push(self, x: int) -> None:
for i in range(len(self.stk_a)):
tmp = self.stk_a.pop()
self.stk_b.append(tmp)
i += 1
self.stk_a.append(x)
fo... |
26700ad634b2198e29456141802f32f9f8dd1e49 | mahmudandme/project | /get_feed.py | 2,904 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# the purpose of this file is to extract the text contents from blogs that are given in a list
# (either feedlist.txt or one supplied as an argument)
import os
import sys
import re
from datetime import datetime as dt
import json
import feedparser
from BeautifulSoup import BeautifulStoneSoup
fr... |
d54cdca07bf6a7587f476ad03cb5f78e63219440 | CruzJeff/CS3612017 | /Python/Exercise11.py | 833 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 30 16:52:43 2017
@author: User
"""
'''Write two functions, one that uses iteration, and the other using recursion
that achieve the following:
The input of the function is a list with numbers.
The function returns the product of the numbers in the lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.