blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c474f8efdf62cc2cc953c02506363761cba351d8 | GustavoBuosi/PythonWeeklyFuelAnalysis | /contas_semanal/math_logic.py | 2,146 | 3.53125 | 4 | from pyspark.sql import DataFrame
from pyspark.sql.types import StringType, DoubleType
from pyspark.sql.functions import *
from rows.row_rules import *
# Função criada para adicionar uma coluna com a última data de um mês
# e um número inteiro com o número de dias do mesmo.
def getLastDateFromMonth(df: DataFrame):
... |
631cce401610ba3cfac28e22e2cabf1018e30ec8 | BoogalooLi/python_spiders | /combats/process&thread_basics.py | 1,084 | 3.65625 | 4 | from multiprocessing import Process
import time, os, threading
from threading import Thread
def learn(s):
print(f'学习{s}中,进程号:{os.getpid()},线程号:{threading.current_thread()}')
time.sleep(5)
print(f'学习{s}完毕,进程号:{os.getpid()},线程号:{threading.current_thread()}')
class_list = ['Optimization', 'Stochastic Model... |
206dbdc1321b0042ee2803e6b294b4e9ef077aee | Minal11/Python-Programming | /BubbleSort.py | 378 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
if __name__=="__main__":
print("Bubble Sort")
a=[1,3,12,4,13]
print("Before",a)
for i in range(0,len(a)):
for j in range(i+1,len(a)):
if a[i]>a[j]:
temp=a[i]
a[i]=a[j]
... |
f5baabf7f77d3dcc31480db4356a34de4ee480aa | lucyach/babyMakerBasedOnGenetics | /main.py | 3,459 | 3.78125 | 4 | import random
# Class Gene holds all the genes we will apply to Person
class Genotype:
def __init__(self, name, allelle1, allelle2):
self.name = name
self.allelle1 = allelle1
self.allelle2 = allelle2
def getChildAllelle(self):
allelle = random.randint(1, 2)
if allelle == 1:
return self.... |
d10d4b2125439722fb8912bb539a878fa240670d | vishrutkmr7/DailyPracticeProblemsDIP | /2022/06 June/db06032022.py | 1,158 | 4.15625 | 4 | """
This question is asked by Google. Given an array of integers,
return whether or not two numbers sum to a given target, k.
Note: you may not sum a number with itself.
Ex: Given the following...
[1, 3, 8, 2], k = 10, return true (8 + 2)
[3, 9, 13, 7], k = 8, return false
[4, 2, 6, 5, 2], k = 4, return true (2 + 2)
... |
6e53675fb8d1bc438e58ce7ee249ddd8491d53a9 | lrrimulo/IvSPythonRepository | /aux/termtools.py | 5,333 | 3.90625 | 4 | """
Tools for cursor and color control in the terminal
Example usage (this does not work in the documentation):
>>> print green('this text is green')
this text is green
>>> print blink('this text blinks')+' this text does not blink'
this text blinks this text does not blink
You can combine all the possibilities, as ... |
f2f9c5ee2b3a66c00e6a24c77c90682260846400 | joao-vitorg-zz/PythonBR | /7 - Arquivos/ex01/main.py | 778 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# Faça um programa que leia um arquivo texto contendo uma lista de endereços IP e gere um outro arquivo,
# contendo um relatório dos endereços IP válidos e inválidos.
def read_entrada():
valido, invalido = '[Endereços válidos:]\n', '[Endereços inválidos:]\n'
with open('entrada.txt') a... |
63cd100183c6bc7b7906a19c50417c6d5942420c | mkeo2524/jnrdevtask | /circle-detection-py/run.py | 2,529 | 4.03125 | 4 | """
This file is used to solve each problem
given in the task.
"""
import sys
import runTask as rt
import getopt
def validate_arguments(opts):
'''
This function runs a simple validation on the script inputs
'''
problem_num = None
pair = None
image_num = None
T3_test = None
# ... |
909c8d0564293666587357cf17f3a4a387c16af4 | hsantos97/codes-in-python | /exe4.py | 399 | 3.640625 | 4 | segundoStr = input("Por favor, entre com o número de segundos que deseja converter: ")
totalsegundos = int(segundoStr)
dias = totalsegundos // 86400
segundosRes = totalsegundos % 86400
horas = segundosRes // 3600
segundosRes2 = segundosRes % 3600
minutos = segundosRes2 // 60
segundosFinais = segundosRes2 % 60
print... |
11c53adb00dd9eb69a86639896726bc8a5543af9 | jesuarezt/datacamp_learning | /python_career_machine_learning_scientist/05_XGBoots/02_regression/02_regularization_in_xgboots.py | 3,307 | 3.953125 | 4 | #Using regularization in XGBoost
#
#Having seen an example of l1 regularization in the video, you'll now vary the l2 regularization penalty - also known as "lambda" - and see its effect on overall model performance on the Ames housing dataset.
# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(da... |
96493c0b3532058915c2907cbc894a1296dbea79 | dante-signal31/test_common_python | /test_common/fs/ops.py | 1,996 | 4.09375 | 4 | """
Functions for file operations (copy, delete, etc).
"""
import os
import shutil
import typing
def delete_file(file_path: str) -> None:
""" Delete an specific file.
:param file_path: string with the absolute path to file.
:raise: FileNotFoundError if given file is not found.
"""
os.remove(file_... |
36b8201a12f218705b9eada6c5f308172c9d1b41 | purisunil/Sunil | /armstrong.py | 294 | 4.09375 | 4 | #wap to find armstrong or not
def arm(n):
sum = 0
while n > 0:
num = n%10
sum = sum+num**3
n//=10
return sum
num=int(input("enter the number\t"))
sum1=arm(num)
if sum1 ==num:
print("it is armstrong num")
else:
print("sorry,it is not armstrong num")
|
4e96d8619dc377b066dba801e319d0be5a3b1b5e | akshatmawasthi/python | /func.py | 822 | 4.09375 | 4 | # 1. Make a function that sums the list mylist = [1,2,3,4,5]
# 2. Can functions be called inside a function?
# 3. Can a function call itself? (hint: recursion)
# 4. Can variables defined in a function be used in another function? (hint: scope)
mylist = [1,2,3,4,5]
def sumlist():
for i in mylist:
while i in... |
5bec8d851de65b0335e9e237fd42f58b0b7fa268 | govindKAG/my-tcs-codevita-solutions- | /cards.py | 865 | 3.59375 | 4 | def answer(cards , n):
operations = []
#ccopy = cards[:]
ans = 0
j = n-1
i = 0
while(i<=j):
#print(i,j)
if cards[i] == cards[j]:
i = i+1
j = j-1
elif (cards[i]>cards[j]):
j= j -1
cards[j] = cards[j]+ cards[j+1]
o... |
78a9f6a894c905cab446e51d4f55bea8c7d45d35 | Pelhans/leetcode | /jingsai/1272.py | 434 | 3.671875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Solution(object):
def clumsy(self, N):
"""
:type N: int
:rtype: int
"""
num = str(N)
oper = ["*", "/", "+", "-"]
idxo = 0
while N-1 > 0:
num = num + oper[idxo] + str(N-1)
if idxo == 3:... |
35a6bda88e9dbc07641b526bdcd2e66f216c6f5f | Dawad81/IS211_Assignment9 | /apple_stock.py | 857 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module parses the NASDAQ.com site for apples historical closing
stock prices, for last 3 months. """
import urllib2
from bs4 import BeautifulSoup
URL = 'https://www.nasdaq.com/symbol/aapl/historical'
PAGE = urllib2.urlopen(URL)
SOUP = BeautifulSoup(PAGE.read(), ... |
f8f78025c18ba676208de7bdbbe393f975eda94d | meganthoang/Megan-Hoang-ECP3004S21 | /assignment_07/my_A7_module.py | 2,305 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
##################################################
#
# ECP 3004: Python for Business Analytics
#
# Name: Megan Hoang
#
# Date: 4/14/2021
#
##################################################
#
# Sample Script for Assignment 7:
# Function Definitions
#
########################... |
5aed80c987db2ef7124b0149902c0e64c03eff43 | poojamalviya/ds-algo | /180_que/nQueen.py | 811 | 3.5625 | 4 | def isSafe(board, r, c):
for i in range(c): # check left side of row
if board[r][i]:
return False
i = r # check upper left diagonal
j= c
while(i>= 0 and j>=0):
if board[i][j]:
return False
i = i-1
j = j-1
i = r # check lower left diagonal
... |
279284e566670d0b1dfce473aeda56b6242f1d4a | fujunguo/learning_python | /modules_built_in/_collections.py | 841 | 3.796875 | 4 | from collections import namedtuple, deque, defaultdict, OrderedDict, Counter
# namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
print()
Circle = namedtuple('Circle', ['x', 'y', 'r'])
c = Circle(1, 2, 3)
print(c.x, c.y, c.r)
print()
# deque是为了高效实现插入和删除操作的双向列表,适用于队列和栈
# list插入和删除效率很低
... |
4563170dded9382866f21b4ee8b59e3793f36e3d | fandiandian/python_learning_excerise | /part1.4习题/hadamark_metrix(哈达玛矩阵).py | 3,848 | 3.625 | 4 | # 哈达玛矩阵
# Hadamard matrix
'''
概述如下:
在数学中,哈达马矩阵是一个方阵,每个元素都是 +1 或 −1,每行都是互相正交的。阿达马矩阵常用于纠错码,如Reed-Muller码
n x n 阶的哈达玛矩阵 H(n) 定义为一个布尔矩阵,满足下列特点:
n 为 2 的乘幂,阶数有:1,2,4,8...(2^0,2^1,2^2,2^3....)
我觉得这样定义会比较好:
以2的乘幂来定义哈达玛矩阵的阶数比较好:
H(1) 即:2^0 ==> 0 阶
H(2) 即:2^1 ==> 1 阶
依次类推
... |
6f55bab9e6563602bcbb5beedaa4c041acbd60f9 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2485/60699/238234.py | 461 | 3.53125 | 4 | cnt=int(input())
for i in range(0,cnt):
k=input()
list1=[str(e) for e in input().split(' ')]
dict={}
for temp in list1:
list2=list(temp)
list2.sort()
dict["".join(list2)]=dict.get("".join(list2),0)+1
list3=[]
for j in dict.values():
list3.append(j)
list3.sort(... |
f7544e6de65527500320f09a88e6a9e7495e46dd | Tulip2MF/100_Days_Challenge | /Band Name Generator.py | 281 | 4.3125 | 4 | #This is to generate the band name from input of city and pen name form user
print('Welcome to band name generator')
cityName = input("What is the name of your city you grew up in?\n")
petName = input("What is your pet's name?\n")
print(f"Your band could be {cityName} {petName} ") |
619b22898c8b4c21682eba0b95c86f67e456c99f | Software05/Github | /Modulo-for/app1.py | 456 | 4.3125 | 4 | # break - ejemplo
print("La instrucción de ruptura:")
for i in range(1,6):
if i == 3:
break
print("Dentro del ciclo.", i)
print("Fuera del ciclo.")
# continua - ejemplo
print("\nLa instrucción continue:")
for i in range(1,6):
if i == 3:
continue
print("Dentro del ciclo.", i)
print("Fu... |
f922f983e5213043555b5233b1b5ba4ff0c0ea5a | tawanchaiii/01204111_63 | /ELAB01/01-03.py | 138 | 4.03125 | 4 | import math
x = float(input("x: "))
y = float(input("y: "))
r = (x*x+y*y-1)**3-x*x*y*y*y
print("Result is {:.2f}".format(round(r, 2))) |
4fe904f7106d4722beb543f7fddfb59774912910 | andrewlehmann/hackerrank-challenges | /Python Regex/using_split.py | 127 | 3.875 | 4 | import re
num = input()
num_list = re.split(r'[.,]?', num)
for entry in num_list:
if entry:
print(entry)
|
3e24610dc6331431a6f378fe5e78047028ff7ec9 | mitokohaku/Algorithm | /BlueBridgeCup/Subject/2019-/Province_C_C++_B/5/code.py | 1,815 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/19 10:13
# @File : code.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex 007
# >>> QQ : 2426671397
# >>> WeChat : Alex-Paddle
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://... |
1230501ae99b0efd11dde4c07c8a7ce219f50df5 | TroyJJeffery/troyjjeffery.github.io | /Computer Science/Data Structures/Week 4/CH5_EX2.py | 537 | 4.125 | 4 | """
Write a recursive function to reverse a list.
"""
def fillList(myList):
for i in range(10):
myList.append(i)
return myList
def swap(myList, i):
myList = myList
myList.insert(i, myList[len(myList)-1])
del myList[len(myList)-1]
return myList
def revList(myList):
... |
ef559a9751826343cc37822c8eb65ef1c2aa1d01 | pavanghai/Python_Task | /t2_6_output.py | 633 | 4.34375 | 4 | # What is the output of the following code examples?
'''
# TypeError: 'int' object is not iterable
x = 123
for i in x: # x has to be list or range to get it iterable
print(i)
'''
'''
# in this code i value is 0, loop till i is 5 or breaking of loop prints i, add 1 to i, break a loop once i = 3
# output: 0, error... |
a0b95959ae52c7e2f8f3c0ab28e5da47d53950c9 | nicolevegai/Session-7-8 | /FilesBasicoperations.py | 125 | 3.609375 | 4 | fp= open("text.txt", "a")
print(fp)
line=input ("Give me some text, don't be shy: ")
fp.write(line)
fp.write("\n")
fp.close() |
5436df1c98aa5824b0045d6c9beb6bf710874db0 | nath7098/Tp_Python_S9 | /scripts/TP1/TP_1.py | 2,758 | 3.640625 | 4 | def choixFichier():
fichier_verifier = True
while fichier_verifier:
try:
nom_fic = input("Choisir le nom du fichier : \n")
if nom_fic == "":
assert False
else:
fichier_verifier = False
except AssertionError:
print("... |
04d6fb5709a213b4f59e564e4d261f068515fb81 | Chenyouchao/LeetCode | /1_Array/3_80_Remove Duplicates from Sorted Array II.py | 440 | 3.625 | 4 | def removeDuplicates(nums):
i = 0
count = 1
for j in range(1, len(nums)):
if nums[j] == nums[j-1]:
count = count + 1
else:
count = 1
# [1,2,3,4]
# [1,1,2,3,4,5]
# [1,1,1,1,2,3]
if count <= 2:
i = i + 1
nums[i] ... |
f831bb9513ff18bceeeda946ba2677dbde06cea4 | cnegiar/e40n | /common_srcsink.py | 661 | 3.8125 | 4 | import numpy
import math
import operator
# Methods common to both the transmitter and receiver.
def hamming(s1,s2):
# Given two binary vectors s1 and s2 (possibly of different
# lengths), first truncate the longer vector (to equalize
# the vector lengths) and then find the hamming distance
#... |
4650d405de0d37653178157879b4e6eb1eb42efa | rotuloveio/CursoEmVideoPython | /Mundo3/Aula23/ex115.py | 772 | 4.0625 | 4 | # Crie um pequeno sistema modularizado para cadastrar pessoas pelo seu nome e idade em um arquivo de texto simples.
# O sistema só vai ter 2 opções: cadastrar uma nova pessoa e listar todas as pessoas cadastradas
from mod115 import *
arquivo = ''
try:
arquivo = open('cadastro.txt')
except FileNotFoundError:... |
010f53ddb03b0b2daf5ee2157a60897861f60c98 | tomgtqq/Data-Structures-Algorithms-Project3 | /4_dutch_national_flag_problem.py | 1,426 | 4.1875 | 4 | def sort_012(input_list=None):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if type(input_list) is not list or input_list is None or len(input_list) == 0:
print("Please check input")
... |
c8c8ee47781b94c7654fa4f819da139e8c80f51c | cx1802/hello_world | /assignments/XiePeidi_assign2_problem4.py | 2,401 | 4.28125 | 4 | """
Peidi Xie
February 12th, 2019
Introduction to Programming, Section 03
Problem 4: Data Size Converter
"""
# ask the user for the file size in Kilobytes (KB)
_kilobytes = float(input("Enter a file size, in kilobytes (KB): "))
print()
# print out the file size in Kilobytes
# print in integer if the integer value is e... |
fb25f0e80f45a42a4130bd0d3b7dd2c04820891a | Heenawter/Unicorns-and-Gargoyles-Simulation | /Player.py | 3,456 | 3.515625 | 4 | import GameMechanics
import Decks
from difflib import SequenceMatcher
class Player:
action_cards = []
current_hand = []
all_hands = []
all_strings = []
def draw_card(self, deck):
card = deck.draw_card()
if("comment" in card or "action" in card):
self.action_cards.appen... |
fe54cbd37c6f010adb14bcc54ca1541463684bc8 | bharat34/Programs_Repository | /Python/geometric_figures.py | 2,142 | 4.40625 | 4 | """
This file contains the code to implement a variety of geometric
figures including circles, rectangles and squares. Methods
available for each include computing the area. The
point class is provided to be used by the other classes.
"""
from math import *
#Class point implements a point on the Cartesian plane (x,... |
9f6dfc43bad54aa58c533ae8f6c94d6c15ce5ddf | Transi-ent/LeetcodeSolver | /iv41.py | 1,401 | 3.78125 | 4 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
# 维护一个有序数组,这样中位数更好求
def addNum(self, num: int) -> None:
n = len(self.data)
if n==0:
self.data.append(num)
return
elif num<self... |
08c5638aceaedea40f8e9d2e8fc0b409d7e68989 | spu-python-203/assignment-3 | /passwords.py | 956 | 3.75 | 4 | import random
import string
def create_password():
"""
Create a random password.
"""
line = []
for i in range(random.randint(1, 10)):
line.append(random.choice(string.digits))
for i in range(random.randint(5, 10)):
character = random.choice(string.printable)
if charact... |
abff9650cc678f87d91f5bc12d60632dcdf95b60 | BeBlockTech/Challenge | /Python/Py4e/ForLoops/test.py | 105 | 4.09375 | 4 | # For loops
print('Before')
for i in [1,2,3,4,5,6,7,8,9] :
print('Hello')
print i
print('After')
|
f1b466255dfcbbc604e8a8153bfccbf005ad7175 | AdamBorg/PracCP1404 | /Prac04/numbers.py | 684 | 4.03125 | 4 | numbers = [3,1,4,1,5,9,2]
"""numbers[0] = 3
numbers[-1] = 2
numbers[3] = 1
numbers[:-1] = [3, 1, 4, 1, 5, 9]
numbers[3:4] = 1
5 in numbers = True
7 in numbers = False
"3" in numbers = False
numbers + [6, 5, 3] = [3,1,4,1,5,9,2,6,5,3]"""
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(... |
2a4c6938a1416dfb0f616414943cb4a62c920e9c | divir94/Python-Projects | /Games/N-Puzzle.py | 1,594 | 3.625 | 4 | from Tkinter import *
import random
def swap(bx, by, x, y):
num = app.numbers[x][y]['text']
app.numbers[x][y].config(bg='grey', text='')
app.numbers[bx][by].config(bg='SteelBlue', text=num)
app.blankX, app.blankY = x, y
def key(event):
bx, by = app.blankX, app.blankY
if event.keysym=='Up' and ... |
2aff71fd9ebdd476236174ecbc3c828bf7e963fe | vyong1/random-scripts | /algorithms/selectionsort.py | 612 | 3.890625 | 4 | import dataset
def selectionsort(arr):
iterations = 0
# For each number...
for i in range(0, len(arr)):
iterations += 1
minInd = i
min = arr[i]
# Find the minimum...
for j in range(i, len(arr)):
iterations += 1
if arr[j] < min:
... |
f86b71ecfff7440fc417ca0bd50ab03710be1ab3 | creep1g/Datastructures-RU | /practice-tests/FinalExamSpring2020_solutions/P4/wait_list.py | 4,099 | 3.703125 | 4 |
class Student:
def __init__(self, id, name, phone, address):
self.id = id
self.name = name
self.phone = phone
self.address = address
def __str__(self):
return str(self.id) + " " + str(self.name) + " " + str(self.phone) + " " + str(self.address)
def _... |
edc4e1e3c2e051751fcd0d18dbd6722dc52f3753 | mattpmartin/DataStructuresSeries | /Shell Sort/Final.py | 830 | 4 | 4 | import random
# creating array of random ints
numbers = [int(random.random() * 20) for _ in range(100)]
# printing array so we know what were looking at
print(numbers)
# Shell sort
def shellSort(numbers):
increment = len(numbers) // 2
while increment >0:
for start in range(increment):
s... |
9bbdb6fe1f084a42cb4aee72a016016c9f3cfa57 | manojs95/python | /maxvalue.py | 282 | 4.03125 | 4 |
def mano1():
num = int(input('how many nos '))
max_num = 0
for n in range(num):
number = int(input('Enter the no '))
if max_num < number:
max_num = number
print('the max value is ',max_num)
mano1()
#print(list(range(10)))
|
83d84b79984b5507e7c8d0172f95df39524c53e6 | Vagacoder/Python_for_everyone | /Ch08/R8-16.py | 721 | 3.984375 | 4 | ## Ch08 R8.16
ALL_LETTERS = 'abcdefghijklmnopqrestuvwxyz'
str1 = 'Think of me, when you see the sun or feel the wind!'
letterCount = {}
for char in str1:
if char.isalpha():
char = char.lower()
if char in letterCount:
letterCount[char] += 1
else:
letterCoun... |
d25a4d6afca624be0c6c772aaf1bbdf6a236e34c | andrefcordeiro/Aprendendo-Python | /Uri/strings/2242.py | 415 | 3.5625 | 4 | # Huaauhahhuahau
def isPalindrome(string):
i = 0
tam = len(string)
while i < tam/2:
if string[i] != string[tam-i-1]:
return 0
i += 1
return 1
vogais = "aeiou"
v = [] #vetor de vogais presentes a risada
s = input()
for i in range(0, len(s)):
if s[i] in vogais:# se é v... |
51fcc5c21000456f08d6a5481894fb3ddf6cf02c | frankieliu/problems | /leetcode/python/516/original/516.longest-palindromic-subsequence.0.py | 797 | 3.640625 | 4 | #
# @lc app=leetcode id=516 lang=python3
#
# [516] Longest Palindromic Subsequence
#
# https://leetcode.com/problems/longest-palindromic-subsequence/description/
#
# algorithms
# Medium (44.97%)
# Total Accepted: 50.1K
# Total Submissions: 111.3K
# Testcase Example: '"bbbab"'
#
#
# Given a string s, find the longe... |
2c8da86648213b7ecab064286040d3d5c6a8ab83 | MrMace/PythonProjects | /guessing_game.py | 701 | 4.1875 | 4 | from random import randrange
def getGuess():
return int(input("Enter your guess from 1 to 100: "))
def main():
print("Welcome to the guessing game!")
print("I have chosen a number from 1 to 100.")
print("You have seven guesses to find it. Good luck!")
print()
#computer picks th... |
aa58459ca17932e371351987ad8308b008e60939 | cor/automate-the-boring-stuff | /chapter-7/is_phone_number.py | 281 | 4.0625 | 4 | import re
phone_number_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phone_number_regex.search('My phone number is 415-555-4242')
print(f'Phone number found: {mo.group()}')
area_code, main_number = mo.groups()
print(f'Area: {area_code}, Main number: {main_number}')
|
372a69fec12ea038b69399627e73f6752c0b6dea | daniyalkabir/CSE-231-Python-Projects- | /proj03das.py | 19,712 | 4.1875 | 4 | ###############################################################################
# Computer Project # for CSE231 #
# Algorithm ... |
f5ce93ff9a57c9970197b96e00b179d1b9382d8f | patidarjp87/python_core_basic_in_one_Repository | /99.ourraiseourexcept.py | 395 | 3.90625 | 4 |
print('script of Exception handling our raise default except but our message')
x=int(input('enter first no'))
y=int(input('enter second no'))
try:
if y==0:
raise ZeroDivisionError('Denominator can not be zero')
z=x/y
except ZeroDivisionError:
print("Exception :Denominator can not be zero")
else:
... |
ca737bbda3ae82e491bac93c95db346203306526 | Alex-HJY/shumo2018- | /a4_rishouyilv.py | 479 | 3.578125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('./data/test.csv', encoding='utf-8-sig',index_col='DateTime')
df.index=pd.DatetimeIndex(df.index)
def rate_day(df=pd.DataFrame(), x_name='PB_money'):
d = (df[x_name] - df[x_name].shift(1)) / df[x_name].shift(1)
b = (df['C... |
6dc20344ba2e3f2129c5767ad69b3c3806fe383b | ShineCxy10/CS229-Auto-Paper-Review | /src/data_parser/naive_bayes.py | 3,469 | 3.671875 | 4 | import numpy as np
def fit_naive_bayes_model(matrix, labels):
"""Fit a naive bayes model.
This function should fit a Naive Bayes model given a training matrix and labels.
The function should return the state of the fitted model, consisting of the
learned model parameters.
Feel free to use whate... |
ba322ca4174f0204fa25deccfe0f23a4626245ef | asaiapalacios/holbertonschool-higher_level_programming | /basic_oop_with_python/h_fibonacci.py | 315 | 4.21875 | 4 | '''
Write a function fibonacci(x): computes fibonacci number of the parameter
'''
#Using loop technique
def fibonacci(x):
a, b = 1, 1
for i in range (x-1):
a, b = b, a+b
return a
'''
Version 2
def fibonacce(x):
if x < 2:
return x
return fibonacci(x-2) + fibonacci(x-1)
'''
|
d0a53a4ca42e65bb86f1e4453bdfe747ea8227ee | AmineNeifer/holbertonschool-interview | /0x19-making_change/0-making_change.py | 578 | 4.25 | 4 | #!/usr/bin/python3
""" Contains makeChange function"""
def makeChange(coins, total):
"""
Returns: fewest number of coins needed to meet total
If total is 0 or less, return 0
If total cannot be met by any number of coins you have, return -1
"""
if not coins or coins is None:
re... |
185cb31598b3a109ef0d68a003e3aad1cc0e3a9f | KatieRGors/7S-Str-Calc | /string_calculator.py | 3,056 | 3.90625 | 4 | import re
import logging
import sys
MAX_ADDITION_PARAM = 1000
DEFAULT_DELIMITER = ','
DELIMITER_DEFINITION_BEGINNING = '//'
DELIMITER_DEFINITION_ENDING = '\n'
DELIMITER_REGEX = r'^//[^\d\n/]+\n'
def get_delimiter(text):
"""
Returns the delimiter parsed from given text. Delimiter is in the form
//[delimi... |
1da8df7a01884a60e3f4e8a1a08bc9c6f964679d | oskar-zhang/Python-Crash-Course | /Chapter 4 Working With Lists/buffet.py | 709 | 4.5 | 4 | """
4-13. Buffet: A buffet-style restaurant offers only five basic foods. Think of five
simple foods, and store them in a tuple.
• Use a for loop to print each food the restaurant offers.
• Try to modify one of the items, and make sure that Python rejects the
change.
• The restaurant changes its menu, replacing two of ... |
424a8c62294103cd25b2aae013b267e4ad1b6f05 | teleamigos/Proyecto_3_redes | /Mapa_CU.py | 454 | 3.53125 | 4 | from tkinter import *
#window init
window=Tk()
#window settings
window.title("CU waze")
window.resizable(True,False)
window.geometry("1020x1020")
window.configure(background = 'black')
#Get the image
mapa=PhotoImage(file="mapacu.gif")
mapa_window = Label(window, image=mapa).place(x=150,y=50)
#mapa_window = Label(windo... |
66c3c77cb320027254edcf495f26639704447eb3 | montapo/ma_simulator | /simulator_orig/CA/schelling/schelling.py | 5,792 | 3.75 | 4 | #coding:utf-8
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import itertools
import random
import copy
class Schelling(object):
#constructor
def __init__(self,width,height,empty_ratio,
similarity_threshold,n_iterations,races = 2):
self.width = width
... |
e7f6cafaa6c4c3b884d4e48b95c79bc2a0156e45 | jlundholm/RaspPi | /ESP4T-2021/Templates/Day 4/Python/Security System/SecurityModule_Template.py | 2,424 | 3.75 | 4 | #Code for Security System Module
#Componenets of system include:
#KeyeStudio Ultrasonic Ranger
#KeyeStudio PushButton
#KeyeStudio Active Buzzer
#KeyeStudio White LED
#Lines 10-14 import content from the GPIOzero library
from gpiozero import Button
from gpiozero import DistanceSensor
from gpiozero import Buzzer
from t... |
97587cfaf5d6e93f62d57d6658c8f434cd5ac681 | nicob825/Bruno_Nico | /Lesson_06/righttriangle.py | 130 | 4.0625 | 4 | word=input("Enter the word:")
def printRTri():
for i in range(len(word),-1,-1):
print(word[i:len(word)])
printRTri()
|
2eaa1ed2e9d93eedfabd5d6cb724c69094905fdd | heemokyim/Machine-learning | /part1/project.py | 4,740 | 3.625 | 4 | person=[]
import json
import sqlite3 # SQLite3 탑재
class start:
def create_table(self):
conn = sqlite3.connect('my_project.db') # 데이터베이스 커넥션 생성
cur = conn.cursor() # 커서 확보
# 테이블 생성
cur.execute('''CREATE TABLE my_project (
name text,
... |
df6268b922d0ccbdf3a825038e3116ca9f88595e | quangdbui9999/CS-171 | /FinalExam-Python-CS171/Final Exam/15.countVowels.py | 281 | 3.78125 | 4 |
def counterVowels(what_string):
counter = 0
vowels = ('a', 'e', 'i', 'o', 'y', 'u')
for i in what_string:
print(i)
if i.lower() in vowels:
counter += 1
return counter
str = "Quang Bui"
print(f"Number of vowels are: {counterVowels(str)}")o |
b66c1d038365065678da4a0bd2f2deb9d8be2b7d | cami-la/python_curso_em_video | /Mundo03:estruturas-compostas/exercicio-python#097-um-print-especial.py | 586 | 3.828125 | 4 | from termcolor import cprint
'''
Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável.
'''
def play():
exercise()
message = str(input("Type a message: "))
specialprint(message)
def exercise():
cprint("Make a program ... |
837ed9b8d09ea2cd551f60684801de0626d3acc6 | jackmanwu/python-learning | /pythontest3.py | 2,025 | 3.9375 | 4 | def fib(n):
a,b = 0,1
while b<n:
print(b,end=" ")
a,b = b,a+b
print()
def fib2(n):
result = []
a,b = 0,1
while b<n:
result.append(b)
a,b = b,a+b
return result
# if __name__=='__main__':
# import sys
# fib(int(sys.argv[1]))
s = 'Hello,world.'
print(str(s))
print(repr(s))
print(str(1/7))
x = 10*3.25
y ... |
fc2c9848c1ba49276321f9c0ca0bc76d3b514523 | justinglobal/codeguild | /8-piglatin3.py | 1,033 | 4.1875 | 4 | #pig latin translator 2 works on string of words
#this is the pre refactored code
print('This is a pig latin translator.')
print('Type a word and hit enter to see the translation')
initial_input = input()
#receives word or sequence of words
word_list = initial_input.split()
#splits string into list of each word in se... |
eaf6fbf304845f476c466c2be107e0d0e003ee75 | choib1ack/Data_Science | /Lab#4/regression.py | 1,070 | 3.703125 | 4 | import warnings
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def scaling(df):
sc = StandardScaler()
ndf = pd.DataFrame(sc.fit_transform(df))
ndf.columns = df.c... |
8105c553f711444a84628057c81b115339e7fe1d | anuraga2/Coding-Problem-Solving | /Lists General/rotate array by 1.py | 333 | 3.609375 | 4 | # Rotate array
lst = [1,2,3,4,5,6,78,32,4,5]
def rotate1(lst):
if len(lst) <= 1:
return(lst)
else:
start = lst[0]
i = 1
while(i < len(lst)):
lst[i-1] = lst[i]
i = i+1
lst[len(lst)-1] = start
return(lst)
print(... |
b32628a17abd75b94523f8f8dcb86423291a17fe | ronnix/jeux-de-programmation | /03-advent-of-code-2018/day-10/day-10.py | 4,823 | 3.609375 | 4 | #!/usr/bin/env python
import re
from textwrap import dedent
from typing import NamedTuple
def main():
with open("input.txt") as stream:
points = list(read_input(stream))
min_surface, min_surface_time = minimize_surface(Grid(points))
print(f"Point configuration has minimal surface {min_surface} af... |
eba502e31bb524999b8134f9d148011c8d74bdab | xxiang13/leetcode | /Algorithms/nim_game.py | 1,654 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 20
@author: Xiang Li
"""
'''
You are playing the following Nim Game with your friend:
There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones.
The one who removes the last stone will be the winner. You will take the first turn to... |
f7d340141d339d183a4565dfce0c4a268d797986 | reichaves/Python_Coursera_USP | /compara_numeros.py | 256 | 3.9375 | 4 | def compara_num(a, b):
if a > b:
return a
else:
return b
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
maior = compara_num(a,b)
print ("O número maior é", maior)
|
57138771cee6c31f1f18af464e5d89f43d2db749 | abir-taheer/learnination-fruition | /hw23.py | 2,745 | 4.21875 | 4 | #Team Wilde Loops -- Patrick Ren, Abir Taheer, Derrick Chen
#IntroCS pd1
#HW23 -- Stringy Loops
#2019-03-13
#add_mult_print(a,b) takes 2 numeric inputs and prints a message like that shown below.
def add_mult_print(a,b):
print("\"the sum of " + str(a) + " and " + str(b) + " is " + str(a+b) + "\ntheir product is " ... |
da8317f7b252747859e8779c126c87a03fa145aa | zs121016024/python | /函数/全局变量、nonlocal关键字.py | 1,042 | 4.03125 | 4 | #!/usr/bin/env python
# coding:utf-8
"""global"""
xx = 1
def fn():
global xx ### global可以提升变量作用域为全局变量,并且只对本作用域起作用,如果在其他作用域都需要生效,则需要在其他作用域也提升
global yy ### 不管有没有定义这个变量,global都可以提升为全局变量
yy = 3
xx += 1
print(fn()) ###打印出None
print(xx) ### xx=2
print(yy) ### yy=3
"""nonlocal关键字"""
def cou... |
634a5e6a934b9ab276d7028139ec39ce749691c3 | gngoncalves/cursoemvideo_python_pt1 | /desafio59.py | 1,346 | 4.0625 | 4 | n1 = 0
n2 = 0
menu = -1
while menu != 5:
n1 = int(input('Insira o primeiro número: '))
n2 = int(input('Insira o segundo número: '))
print('='*20)
print('''Menu:
[1] - Somar os dois números
[2] - Multiplicar os dois números
[3] - Identificar o maior dos dois números
[4] - Digitar novos números
[5] - Sair... |
fb26f6302e48bc500a3ee10b3769658bf0448080 | RIMPOFUNK/FirstLyceumCourse | /Lesson 11(Строки. Срезы)/Classwork/1. Слова и буквы.py | 727 | 3.71875 | 4 | def find_min(lst: list):
value = lst[0]
lenght = len(value)
for i in range(len(lst)):
value = lst[i] if len(lst[i]) < lenght else value
lenght = len(value)
return value
def find_max(lst: list):
value = lst[-1]
lenght = len(value)
for i in range(len(lst)):
value = ls... |
3eabb7118d4e7702c9b1d62e3282fb6936d98207 | kaushik12048/Coding | /python/lab4.py | 2,630 | 3.578125 | 4 | def fibonnaci_q1a(n):
if n==1:
return 0
if n==2:
return 1
else :
return fibonnaci_q1a(n-1)+fibonnaci_q1a(n-2)
dictionary_q1={}
def fibonnaci_q1b(n):
if n in dictionary_q1:
dictionary_q1[n]+=1
else:
dictionary_q1[n]=1
if n==1:
... |
3a27ca78747d3409bf66cfe59ab592d69874c0c4 | LS80/sequence-times-table | /sequence/fib.py | 163 | 3.890625 | 4 | def gen(n):
''' Generate n number of fibonacci numbers '''
n = int(n)
a, b, c = 1, 1, 0
while c < n:
yield a
a, b, c = b, a+b, c+1
|
bf97ebe6f613f62f2bc96a9b347755a435b23df2 | gabriellaec/desoft-analise-exercicios | /backup/user_309/ch149_2020_04_13_20_14_58_335347.py | 1,112 | 3.765625 | 4 | salario_bruto = float(input('qual o seu salario: '))
n_dependentes = float(input('quantos dependentes voce tem? '))
contri_INSS = 0
aliquota = 0
deduçao = 0
if salario_bruto <= 1045:
contri_INSS = (salario_bruto/100)*7.5
elif salario_bruto <= 2089.60:
contri_INSS = (salario_bruto/100)*9
elif salario_bruto <= ... |
36f4884cbca3db2ca45b73db38687d2a94c6f283 | mayank181994/flightsddelay | /python1.py | 168 | 3.546875 | 4 | #!/usr/bin/env python
import pandas as pd
df=pd.read_csv('flightdelays.csv')
print(df[df['Origin']=='SFO'][['ArrDelay','Origin']].head(3))
print("My name is mayank")
|
8d4fb9099385897276a1b40f9d1b561ea4701360 | riteshsharma29/Pandas_tips | /set2.py | 655 | 3.71875 | 4 | import pandas as pd
'''
Splitting delimeter(, ; | etc) separated values into multiple rows with multiple columns data
'''
df = pd.read_excel("data.xlsx",sheet_name='setII')
# split 'Annual Budget' column into multiple rows with multi index
df_new = (df.set_index(['Department','Mananger','Senior Manager'])
... |
f954dde82105e7f9e20d63d355e2949ef155db7e | winklerm6716/CTI110 | /M5T2_FeetToInches_MichaelWinkler.py | 320 | 4.09375 | 4 | def feetToInches( userFeet ):
inches = ( userFeet / 1 ) * 12
return inches
def main():
userFeet = float( input('Please enter the number of feet: '))
print()
inches = feetToInches( userFeet )
print(userFeet, 'Feet converted to inches is', format( inches, '.2f'), 'inches')
main()
|
2963e484cccebfee6d209c95f2ce08e22df3e47a | lucasmsa/python-learning | /try-except/try-except-ex.py | 1,066 | 4.0625 | 4 | # a way of treating errors
# file doesn't exist, will throw an error
# antecipate parts of code that are prone to errors
try:
t = open('text.txt')
o = open('corrupt.txt')
if o.name == 'corrupt.txt':
raise Exception
#var = non_var
# specific file not found case
# more specific at the top
# mo... |
aa8cef8f43851502a0ab04a2c3d61cdc6dc8a400 | ZMXQQ/python_learn | /GUI_Tkinter.py | 810 | 3.5 | 4 | #!/user/bin/env python3
# coding:utf-8
'a GUI program by Tkinter'
__author__ = 'zmxqq'
from tkinter import *
import tkinter.messagebox as messagetbox
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWi... |
d0e0ca2994b076acd7b39090e98db0e8bcb9a5ee | satyamsingh2/developers-suitcase | /intro to test/demo.py | 196 | 3.890625 | 4 |
def area_of_rect(l,b):
a=l*b
return a
def area_of_square(a):
if type(a) is int or type(a) is float:
return a*a
else:
raise TypeError("only int and float allowed") |
27f116d0a0d7ef23b7a034e85e85c6cdd7fe7402 | VeriSandy/LEETCODE | /219_nextGreaterElement.py | 1,443 | 3.53125 | 4 | '''
Find next greater element for each element in second array and put it in hashmap(as we are given distinct element array).
Now for first array, find the value of correspoding element in hashmap.
Find Next Greater element ==?
1.
Start from the last element and push it into stack.
Now if ith element of arra... |
7974505ffb8beff84288a3940ab7e5915bace380 | matiaslee/eulersproblems | /eulersp012_highly_divisible_triangular_number.py | 4,532 | 3.96875 | 4 | #!/usr/bin/env python3
#
# Problem 12: Highly divisible triangular number - https://projecteuler.net/problem=12
# by Matias D. Lee
#
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be:
#
... |
805734b95f6ea5d462f4e8f2594623278c17f18c | simonzg/leetcode-solutions | /199.Binary_Tree_Right_Size_View.py | 742 | 3.6875 | 4 | # layerd bfs solution
# time complexity: O(N)
# space complexity: O(N)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
... |
2ed7afb3ad7e919472437960337d7e84f281cd1f | rajatgupta-26/Interview-Bit | /trees/bst_iterator.py | 969 | 4.1875 | 4 | class BSTIterator:
# @param root, a binary search tree's root node
def __init__(self, root):
self.root = root
self.path = []
A = root
while A:
self.path.append(A)
A = A.left
# @return a boolean, whether we have a next smallest number
def hasNext(self):
return len(self.path) != 0
# return an integer... |
5b90a9bccc5a986eabcea1bd66cfb4bf0eef0d7c | graceknickrehm21/open-cv- | /colorspaces.py | 898 | 3.703125 | 4 | #there are many more color spaces than RGB
#e.g. the HSV color space is more similar to how humans conceive of color
#OpenCV provides support for many of these color spaces
import numpy as np
import argparse
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to th... |
c0c3ec28bc9159811446483001f8583dd3ffd440 | aniketkumarray/gui-1 | /q2.py | 613 | 3.578125 | 4 | from tkinter import *
def display():
txt = Label(root, text='Assignment of Gui Q2', bg='red', font='Arial 15 bold ')
txt.pack()
root = Tk()
root.title('assignment')
root.geometry('500x500')
root.configure(background='#EEEEEE')
hwL = Label(root, text='Hello World!!', bg='green', font='Times 15 bold ')
... |
43baccd5b3d198115fb8ca399ed2a39dc93a4799 | ivanenko0and/Colloquium-2 | /task 7.py | 1,379 | 3.828125 | 4 |
"""
Створіть масив А [1..12] за допомогою генератора випадкових чисел з елементами від -20 до 10 і виведіть його на екран.
Замініть всі від’ємні елементи масиву числом 0.
Виконав Іваненко Андрій Вадимович
"""
import numpy as np
answer = '1'
while answer == '1':
array = np.random.randint(-20, 10, 1... |
a90eb361ad2e104835e585fd69d7bd0b326626b8 | ulyssefred/leetcode-and-niuke | /重排链表.py | 1,703 | 3.78125 | 4 | class Solution:
def reorderList(self, head: ListNode) -> None:
if not head:
return None
list1 = []
pre = head
while pre:
list1.append(pre)
pre = pre.next
i, j = 0,len(list1)-1
while i<j:
list1[i].next = list1[j]
... |
531d01851d61372b689bd21a1d7aa59ec8649b14 | AyubHossain/small-python-projects | /Binary Search Algorithm.py | 2,029 | 4.28125 | 4 | #Python Projects for beginners
#Binary Search Algorithm
#https://www.codementor.io/ilyaas97/6-python-projects-for-beginners-yn3va03fs#binary-search-algorithm
import random
def createlist():
k=list()
for i in range(0,10):
num = random.randrange(0,101,2)
k.append(num)
return k
def ... |
bd6981ff79595782242d90832e3152f49d21c2a2 | barness/Exam_Scheduler | /python_version/to-graph.py | 1,161 | 3.890625 | 4 | #convert data to graph
#data input is a dictionary with the class crn number as the key and a
#list of the camel numbers of all students in that class as the value
data = {"crn1": ["student1"],
"crn2": ["student1"],
"crn3": ["student1"],
"crn4": ["student2"],
"crn5": ["student3", "stud... |
efc2fbdffc38c087f7637dd7c767ae088ba625b7 | sumukh1991/WQFS | /WQFS/Ingest FTP Files/calculateJulianDate.py | 3,643 | 3.609375 | 4 | #!/usr/bin/env python
'''
Sheifali Khare
khare2@purdue.edu
Calculate Julian Day and Year. ALso identify the previous JDay
(C) Purdue University 2015
'''
from datetime import datetime, timedelta
import os
import io
import sys
import json
import csv
currJDay = 0
currYear = 0
prevJDay = 0
prevJyear = 0
output = {
'isV... |
268c7372aa7fb1da2bd67ffbd61a076c440fe530 | dreamerHarshit/startxlabs | /balanced_or_not.py | 959 | 4.125 | 4 | '''1. Your task in this exercise is as follows:
Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.... |
05c115e5eac287dfd4e370fa321ed2ae1f46c21a | DavidYi/Intro-to-Computer-Science-Trimester-1 | /Python/BCA Tri 1 Final Review/Problem12.py | 131 | 3.84375 | 4 | '''
Rewrite the following code using a while loop.
for i in range (28, 7, -4):
print (i)
'''
i=28
while i>7:
print(i)
i-=4 |
25b4cd18d401cb609361c6b814ee035c11e33ae7 | tombrereton/WebScraperTest | /web_scraper.py | 8,089 | 3.5625 | 4 | #!/usr/bin/env python3
import bs4 as bs
import requests
import json
import collections
__author__ = "Tom Brereton"
__version__ = "1.0"
__email__ = "admin@thomasbrereton.com"
__status__ = "Development"
def handle_local_links(url, link):
"""
We use a function to handle local links
which start with '/' (i.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.