blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
44c05d319d060d2ce7da5ceb51782fdda9b43e89 | yoniivan/Python | /string_brackets.py | 1,089 | 4.28125 | 4 | # A program the check if bracket are valid in terms of math rules.
str_good = "[(hjgfhjgdfhgf)]{}{[(lkjhkjggf)()](hgfdghdfh)}"
str_not_good = "[(cgfjhgkjh]kjgkjhg)"
def brackets_to_arr(str):
arr = []
for char in str:
if char == '[' or char == ']' or char == '{' or char == '}' or char == '('... |
2b9118f8c0fd37e277cd590ca217999139bd2900 | rainyuxia0112/xgboosting-feature-selection | /xgboosting.py | 687 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 18:15:07 2019
this py is to use xgboosting to select features from data
@author: rain
"""
import numpy as np
import pandas as pd
from xgboost import XGBClassifier
import matplotlib.pyplot as plt
# load data
dataset = pd.read_csv('/Users/ra... |
51a08160115292e47b98689b251b83638dc2f09a | rhivent/py_basic | /file handling/create_file.py | 1,419 | 4.125 | 4 | '''
Membuat text file dan write in it
caranya dengan built-in function pada python yaitu open()
file handling
use open() function to open the file. The open() function
two parameters; filename and mode
deskripsi open()
mode : r ==> utk Read ==> Default value. Opens a file just for reading. Throws Error if file does n... |
0e46db66c64591c506c24eb9b8a56025d3327400 | rhivent/py_basic | /34pattern_floyds.py | 361 | 3.828125 | 4 | '''
1
2 3
4 5 6
7 8 9 10
segitiga yg number berurutan, atau floyds triangle by robert floyds
'''
# inisiasi variabel
n = int(input("enter the number of row:"))
# nested for() loop
# there are 4 cols and 4 rows
# inisiasi
num = 1
for row in range(1,n+1):
for col in range(1,row+1):
print(num,end=" ")
... |
a02e304074b2f35874a19886fc565ec9459fa4a5 | sswan0629/LPTHW | /ex6.py | 590 | 4.125 | 4 | # %r is for debugging, since it display "raw data". %s is for users to read.
x = "There are %d types of people." %10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." %(binary, do_not)
#print x
#print y
# % r is a formatter character short for repr().
print "I said: %r." % x
print "I als... |
18080a600e739185b0a26dc8f86f48add68ac19f | ba-san/DL-CV-toolbox | /plt-handles.py | 537 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(10)
handles = [] # A list of Artists (lines)
labels = ['red','green','blue'] # 簡単のため色=ラベル名とする
for i in range(6):
ys = (xs ** 2) / (i+1)
line, = plt.plot( xs, ys, linestyle="solid", label='line{}'.format(i),color=labels[i//2])
if i % 2 == 0: ... |
fc7839cf893ea5057f76d76472b7b6f3f1423de5 | vrlambert/Small_Projects | /minesweeper/minesweeper.py | 11,694 | 4.21875 | 4 | """
Code to run minsweeper in the terminal
By Victor Lambert
"""
import random
class Board(object):
"""
This class holds the functions for generating and displaying a minesweeper
board, but not the full game.
"""
def __init__(self, mines = 10, size = (10,10), show = False):
# extract the ... |
1d86746d60e14489c3dacac6d15353cd02881a86 | Dexter011001/DexterProjects | /Algortihms/linear search.py | 320 | 3.84375 | 4 | #linear search algorithm
number = 341
array = [0,20,42,45,70,100,225,226,230,231,290,300,323,329,330,341,346,389,400]
for index,item in enumerate(array):
if number == array[index]:
print("Found number: " + str(item) + " at array location: " + str(index))
break
else:
print("Number not found")
|
e5e94c5136fd75b88f49d8214bac358183fe1cb2 | cde/algorithms | /stack/remove_duplicate_letter.py | 2,183 | 3.84375 | 4 | def removeDuplicateLetters(self, s: str) -> str:
dictionary ={} #// dictionary data structure to store last index of character
stack = [] # to keep track of order of characters
sets = set() # to see whether the element is added to stack or not if not add to stack
res = '' # final result ... |
88f3f7d967b8f30113db372c7001d6b9b258202d | cde/algorithms | /sorting/bubble_sort.py | 291 | 3.90625 | 4 | # bubble sort
def bubble_sort(arr):
for end in range(len(arr) - 1, -1, -1):
swap = false
for i in (0..end):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swap = True
break: if swap == False
return arr |
c867d18bae2abdbaf94dac92b0d651d90eb38bd4 | NieGuozhang/Python-Spider | /06.高性能异步爬虫/03.协程.py | 1,149 | 3.515625 | 4 | import asyncio
async def request(url):
print('正在请求URL是:', url)
print('请求成功,', url)
return url
# 使用async修饰的函数,调用返回的是一个协程对象
c = request('www.baidu.com')
# # 创建一个事件循环对象
# loop = asyncio.get_event_loop()
#
# # 将协程对象注册到事件循环对象loop中, 然后启动loop
# loop.run_until_complete(c)
"""task的使用"""
# loop = asyncio.get_ev... |
a1b851a7d6f6491111fb3fa4285ecbed18fb703c | joekennerly/companies_employees | /dep.py | 950 | 3.90625 | 4 | class Employee:
def __init__(self, name):
self.name = name
self.title = ""
self.start = ""
def __str__(self):
return f'{self.name}'
class Company:
def __init__(self, name):
self.name = name
self.address = ""
self.type = ""
self.employees = lis... |
b174acdc5d9c932873dcaaaba0ede27dd223f5cc | danathughes/AtariRL | /utils/counter.py | 1,047 | 3.8125 | 4 | ## counter.py
##
## Simple counter to allow univeral maintainance of a common value
class Counter:
"""
Simple class to maintain a shared counter between objects
"""
def __init__(self, initial_count=0):
"""
"""
self.count = initial_count
# Timing at which to perform particular actions
self.hooks = {}
... |
c7e5ea5db1bcf0f8298ace51ec8b45d17f89f814 | thinthread/skills_assesments_hackbright | /lists_testing/testing_list.py | 3,164 | 3.96875 | 4 | # def print_list(number):
# number_list = [1, 2, 6, 3, 9]
# for number in number_list:
# print number
# print print_list(print_list)
# def long_words(words):
# longer_words = []
# for word in words:
# if len(word) > 4:
# longer_words.append(word)
# return longer_word... |
b6cb5a790144803a06b62a389ea55248b4219b80 | Avneet08/DeepLearning | /Deep_Learning_A_Z/Volume 1 - Supervised Deep Learning/Part 1 - Artificial Neural Networks (ANN)/Artificial_Neural_Networks/ann2.py | 3,290 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 30 18:12:05 2018
@author: Avneet
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
from sklearn.preprocessing i... |
ee4881b4f9f828dd3c1a667866c7d10d6edad36b | hidayattaufiqur/Teknofest_Tugas-3_Array | /1.py | 1,179 | 3.546875 | 4 | arrBerat = []
bMin = 0
bMax = 0
def hitungMinMax(arrBerat):
global bMin, bMax
Min = min(float(i) for i in arrBerat)
Max = max(float(j) for j in arrBerat)
bMin = (Min)
bMax = (Max)
# Definisikan Proses Mencari Berat Maximum Dan Minimum
def rerata(arrBerat):
total = 0
# D... |
b44ace31640f66c596ac9b1cad78ca4bf1e0049e | syeal01/python_programing | /temperature_c_to_f.py | 770 | 4.15625 | 4 | # Aliabbas Syed
# Convert from temperature in C to F
# F = C 9/5 + 32
import os
import datetime
def C_to_F(temp_in_C):
temp_in_F = float(temp_in_C * 9 / 5 + 32)
return(temp_in_F)
temp_in_C = float(input("Enter Temperature in ºC: "))
if( temp_in_C <= -273.15):
print("Sorry lowest possible temperature that... |
02d5452cecc1249ab16bafe05bd9dbe8ed24aa8a | hanchang7388/PythonExercises | /test/test_class_2.py | 888 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# class P1():
# def foo(self):
# print 'p1-foo'
#
# class P2():
# def foo(self):
# print 'p2-foo'
# def bar(self):
# print 'p2-bar'
#
# class C1(P1,P2):
# pass
#
# class C2(P1,P2):
# def bar(self):
# print 'C2-bar'
#
# cla... |
d996235013ab7f2c73eff17eabd79650e900d2cd | hanchang7388/PythonExercises | /test/test_exception.py | 200 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def func(number):
if number>1:
raise Exception("IIIIInvalid number",number)
print "never run"
a=int(raw_input("pls input"))
func(a) |
c3d6b7f8b43b70e62d316110694088ec82ded2c8 | hanchang7388/PythonExercises | /test/test_generator.py | 123 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
xl=[1,2,3]
yl=[4,5,6]
print zip(xl,yl)
print sum(x*y for x,y in zip(xl,yl)) |
686b3a7562cb57c68cb42d0fd8ded020f8f465f9 | adekur09/HAcker-Rank | /Staircase.txt | 305 | 4.03125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the staircase function below.
def staircase(n):
for i in range(n):
b=i+1
a=n-b
print(" "*a + "#"*b)
if __name__ == '__main__':
n = int(input())
staircase(n)
|
21f038eb11630209b02fd625fc09096da359a994 | Christine340/R_Project_2 | /blackjack/blackjackDealerSim2.py | 3,652 | 3.9375 | 4 | #Simulating the dealer in blackjack
## Needs minor modifications
## Triple pounds (###) indicate either:
## 1. that line was altered from the in-class version, or
## 2. you need to change something here for the lab
from random import *
def main():
#print intro
printIntro()
#input nu... |
84f8aad6579f4db4cd5778cd45e32ecc8a9ed286 | Patkloe/BinaryTreeSearch | /Python/BinarySearchTree.py | 1,402 | 4.15625 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert method to create nodes
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left =... |
e43902512ce6f73bf329af14cdd722fd914c09d6 | agilgur5/GradeExplorer | /app/Model/readGrades.py | 5,643 | 3.515625 | 4 | import csv
import json
def readGrades(fname):
if '14' in fname:
return readGrades14(fname)
elif '15' in fname:
return readGrades15(fname)
else:
return "NOT VALID FILE"
def readGrades15(fname):
grade_full = ['A+','A','A-','B+','B','B-',... |
54b0f04e01fc0f88918499c3e3e0bdcf9682a236 | gerssivaldosantos/MeuGuru | /projeto001/qt_divisores.py | 335 | 3.78125 | 4 | def qtd_divisores(numero):
contador = 0
""" Percorrendo do 1 ao número e verificando se o resto de divisão de cada
número no intervalo é igual à zero, caso seja, adição ao contador """
for i in range(1, numero + 1):
if numero % i == 0:
print(i)
contador += 1
return co... |
a961d6ea6858565c9695977f25fe7011c504db22 | gerssivaldosantos/MeuGuru | /projeto001.5/2048_desafio3.py | 576 | 4.3125 | 4 | """
(3) Crie uma função que dado uma lista numérica de tamanho qualquer, junte todos
os elementos diferentes de zero no extremo direito da lista.
Exemplo:
>> l = [1,2,2,4,0]
>> funcao_auxiliar2(l) #nome generico nao use esse nome
>> l
[0,1,2,2,4] """
def mover_zeros(numeros):
zeros = []
outros = []
for nu... |
62e6f7bfed5b7325fabc78380344b87dbd95a09e | gerssivaldosantos/MeuGuru | /projeto001/trash.py | 79 | 3.5625 | 4 | lista = [2,3,4,56,7,2]
for i in range(len(lista) -1,-1,-1):
print(lista[i]) |
64c981d95626142bb499c569ae98478ee7305995 | wanghengquan/repository | /tmp_client/tools/corescripts2/DEV/tools/scan_report/tools/spreadSheet/xlib.py | 1,520 | 3.578125 | 4 | import re
def _csv2dict(csv_file, start_title_mark=""):
"""
convert csv file's line to a dictionary
After find the title line, line --> dictionary
otherwise line --< list
"""
if not start_title_mark:
start_title_mark = "Design"
title = list()
for line in open(csv_fi... |
dbf14226be6db192b6e3ab228b127fd27493d8ea | toadmo/firestorm | /tkinter_practice.py | 644 | 4.28125 | 4 | import tkinter as tk
window = tk.Tk()
greeting = tk.Label(text="Tkinter Starting Point")
greeting.pack() # makes window as small as possible while including whatever was added
label = tk.label(
text="Hi",
foreground="white", # can use fg instead
background="#34A2FE", # bg
width = 10,
height = 10
)... |
2d39f02a322b6c13caee0e826afda5e45edfaad2 | raghavatreya/python-raghavatreya | /forLoop.py | 99 | 3.84375 | 4 | i=0
for i in range(0,10):
print("A:"+str(i))
i+=1
print("Fo Loop Program")
#list iterator
|
227cb8fa91ea7c4625c81dbc20c7edf2f8c4348c | ninavv/python_course_repo | /les01_normal.py | 3,562 | 3.625 | 4 |
__author__ = 'Nina Vinokurova'
# Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа.
# Например, дается x = 58375.
# Нужно вывести максимальную цифру в данном числе, т.е. 8.
# Подразумевается, что мы не знаем это число заранее.
# Число приходит в виде целого беззнакового.
# Подск... |
00326de859bbe3dc5f034170002b9af38e31d27b | shreyanikkam/Page-Replacement-Using-Stack-Implementation | /Page-Replacement-OS/Queue.py | 1,097 | 3.96875 | 4 | """
Queue.py
Description: This file contains the implementation of the queue data structure
"""
# The queue class is used to implement functionality of a queue using a list
class Queue:
# Default constructor
def __init__(self):
self.items = []
# Function used to tell us if the queue i... |
ea6d643347303df423d96fd044afd1b7d33c42cb | kinokosu3/course-project | /sqlfunction/SQLapartment.py | 1,178 | 3.609375 | 4 | import sqlite3
def apartment_search(apartment_name, name,value):
conn = sqlite3.connect('main.db')
cursor = conn.cursor()
data = (name,value,apartment_name)
result = cursor.execute('''
select * from apartment_manage where name = ? and value = ? and apartment_name=?;
''', data).fet... |
318f5e8dc3ff29f068034b4574a9b3cda683e2f4 | komissvaleri/lesson_1 | /my1.py | 1,757 | 4.0625 | 4 | #print('Hello world')
#dict_a={1:'one', 1.0:'two',True: 'three', 2: 'true'}
#print(dict_a)
#list_a=[1, 'a', 4.6]
#print(list_a)
#list_a.append('additional elem')
#print(list_a)
#a=56
#b=134
#print(a + b)
#print(b - a)
#print(a * b)
#print(b // a)
#print(b % a)
#print (a ** 3)
#print(a < b and b % a == 0)
#print(a <... |
86ddd1605ca8e094506cbc7606bfdc3ee7469b41 | komissvaleri/lesson_1 | /lesson_1/t_5.py | 575 | 3.671875 | 4 | proceed = int(input("Введите выручку: "))
outlay = int(input("Введите издержки фирмы: "))
if proceed > outlay:
profitability = proceed - outlay
rent = profitability / proceed
print(f"Хорощая работа, ваша рентабильность {profitability}")
worker = int(input("Численность ваших сотрудников: "))
print(f"... |
fc91c39de4538b21dba6ce6ee19d1654650002a2 | AhmaadJ/Class-Projects | /Grade Reader (Python)/Quiz5.py | 1,617 | 4.125 | 4 | #Write a program that reads 30 grades from a file(grades.txt)
#Uses three functions to calculate the average, standard deviation,
#& grade range frequency for the 30 grades
#variance = sum of all differences between
#the points in the data
#and the mean
#square it, and divide by
#All of the numbers in the data minus ... |
7942a2252dbda895fba555a0351a2e1ccdd706ab | nelson54/oiler | /euler4.py | 255 | 3.703125 | 4 | palindromes = []
MIN, MAX = 100, 999
def is_palindrome(p):
return str(p) == str(p)[::-1]
for x in range(MIN, MAX):
for n in range(MIN, MAX):
b = x*n
if is_palindrome(b):
palindromes.append(b)
print(max(palindromes)) |
05dfa4e1ddd9434292f00c5d1449ceee9c0b72ed | kamilBoksa/Python_adventure_game | /hot_warm_cold.py | 2,105 | 4.15625 | 4 | import random
import win
import loose
def print_instruction():
print("Hey little Hero ! Wan't to play a game?")
print("Here are the rules:")
print("I will think of 3-digits number")
print("If none of the digits is in the number the hint is cold")
print("If the digit is in in the number - the hint... |
3ac5821e0c222e93e7fdca481c6dca084c5b73f9 | LitRidl/checker-content | /cont11lab/30/solution.py | 568 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
удалить десятичные числа, превышающие INT_MAX
24456 35454 2132324454\45nsdgfdg fgfdh 2341
'''
from __future__ import print_function
from sys import stdin, stdout
from string import *
INT_MAX = 2 ** 31 - 1
def check(w):
try:
a = long(w)
if (a <= INT_... |
d1db16f92969229b4a8757aa40ad37ec2ac6090e | LitRidl/checker-content | /cont6lab/14/solution.py | 464 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
Проверка делимости на 3.
записано целое беззнаковое число произвольной длины в десятичной системе счисления
0 -- если не делится, 1 -- если делится
648
'''
from __future__ import print_function
a = raw_input()
inta = long(a, base=10)
result = int(inta % 3 == 0)
print(... |
56a81c5d846f5965440cabe578377cd4f206d1e9 | LitRidl/checker-content | /contlab5/26/solution.py | 521 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
Проверить палиндромию двоичного числа.
записано беззнаковое число произвольной длины в двоичной системе счисления
0 -- если не палиндром, 1 -- если палиндром
11011
'''
from __future__ import print_function
num = raw_input().strip()
tmp = num[::-1]
result = 0
if tmp == nu... |
dc87d63146a6b9a8674f2cf3f59c6c391b7c7eb0 | LitRidl/checker-content | /contlab5/12/solution.py | 830 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
Вычисление наименьшего общего кратного двух чисел в натуральной системе счисления.
через пробел записано два числа произвольной длины в натуральной системе счисления {|}
число в натуральной системе счисления, которое является наименьшим общим кратным исходных чисел
||| ||... |
cb2352d01e06fa498d657d80c517faf866b63a57 | LitRidl/checker-content | /contlab5/08/solution.py | 688 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
Обмен местами разрядов двоичного числа, находящихся на чётных и нечётных позициях.
записано беззнаковое число произвольной длины в двоичной системе счисления
двоичное число после обмена разрядов
11011
'''
from __future__ import print_function
a = raw_input().strip()
in... |
47e6fcf12fd62e0465469bdfc9a6c7e0ba800e98 | LitRidl/checker-content | /cont11lab/problems/36/solution.py | 2,146 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''
Выделить все дясятичные числа от 17 до 77 по модулю и распечатать их значения в словесной форме по-испански
hgsdf 324 fgd -35\n3 22 77 67ad
'''
from __future__ import print_function
from sys import stdin, stdout
from string import *
INT_MAX = 2 ** 31 - 1
def check(w):
... |
78dd4a7d3fe9d815fb791b5c2441870d4ed5560c | JacobRammer/CIS122 | /labs/Lab 4/cis122-lab04-calendar.py | 2,613 | 4.3125 | 4 | '''
CIS 122 Fall 2018 Lab 4
Author: Jacob Rammer
Partner: None
Description: Lab 4
'''
def get_full_month(month):
"""Return the month
Return the month to print
Args:
month (Int): Use month to determine what month to return
Returns:
month as a string
"""
if month == 1:
r... |
32fe6b11e94bd4e5a2c94411b24e4b2d2d20dc07 | jfarrell-bsu/CS111-resources | /archived/cs111-project3-component4-stub.py | 3,332 | 3.984375 | 4 | # Author:
# Date:
# Description: Jackpot Challenge - Component Four - Selection Menu
# Step 1: Import required libraries
# Step 2: Copy the playGameOfDice() function from Component 1 and paste it here
# Step 3: Copy the playGameOfSlots() function from Component 2 and paste it here
# Step 4: Copy the playGam... |
e11a5ab7999388278d7713332b956416aa659bf1 | jfarrell-bsu/CS111-resources | /projects/dice_game.py | 2,458 | 4.21875 | 4 | # Author:
# Date:
# Description: Retro Arcade - Component One - Dice Game
# Step 1. Import required libraries
#
# This game is player vs computer where each take turns rolling a single six-sided
# die. The player with the highest roll each round wins a point. The computer
# receives the point for a tie... |
13fc43004529de4e60e563449a1c790685c61f93 | Gyufei/show-me-the-code | /0004.py | 1,370 | 3.65625 | 4 | #coding=utf-8
"""其实可以通过正则表达式匹配单词更快更方便
使用\b匹配单词边界,使用re.findall得到每个单词的不去重列表
再使用list.count统计列表中各单词个数(或使用collections模块"""
import string
def count_word(text):
word_count_dict={}
word=''
for line in text:
for char in line:
if char in string.letters:
word+=char.lower()... |
4df43f8398a71e17db8a64151b084e6d8d2160f8 | MariaMokbel/advent-of-code-2020 | /day_06/solution.py | 1,356 | 3.734375 | 4 | from functools import reduce
from typing import List
def parse_input(filename: str) -> List[str]:
file_content = []
with open(filename) as f:
for line in f:
file_content.append(line.replace('\n', ''))
return file_content
def get_groups(file_content: List[str]) -> List[str]:
group... |
706efb0ba49e9c36b1d1398e1c4089d92d7a8159 | MariaMokbel/advent-of-code-2020 | /day_16/solution.py | 4,301 | 3.65625 | 4 | from functools import reduce
from typing import List, Dict, Set
def parse_input(filename: str):
f = open(filename, "r")
lines = f.readlines()
actual = 'rules'
rules = {}
my_ticket = None
tickets = []
for line in lines:
line = line.replace('\n', '')
if actual == 'rules':
... |
ab1d9ddd9eb6a23ba4e696c906847491eaedb16c | ryan-kanghyun-moon/2021-snakathon | /food.py | 1,174 | 3.546875 | 4 | # backend
# keeps track of food
import random
import time
class Food:
def __init__(self, s_x, s_y):
x = self.get_rand_int(-5 , 5)
y = self.get_rand_int(-5 , 5)
self.coord = [s_x + x, s_y + y]
def place_new_food(self, snake, width, height):
candidates = self.get_empty_coords(sna... |
094210492fa173bc3068bf2021d87aa2e621817b | RyTaus/coding-practice | /python/array-problems.py | 225 | 3.78125 | 4 | def add_up(nums, s):
seen = set()
pairs = []
for num in nums:
if num in seen:
pairs.append((num, s - num ))
seen.add(s - num)
return pairs
print add_up([2, 4, 6, 8, 3, 3, 1], 10)
|
bde97177bf18c8c8a7cab1a3acceb58c3e024b3d | xuanita1/APS106Summer | /lab2.py | 1,163 | 4.25 | 4 | import math
def horizontal_distance(v, theta, del_h):
""" (num, num, num) -> (num)
This function receives initial velocity, launch angle, and altitude change
in the landing position and returns the horizontal range of a projectile.
v is in [m/s]
theta is in [degrees]
del_h is in [... |
1ef13cfe2bab60a2ecde1d10a2fbbd00434f508f | danrimr/codificador-cesar-vigenere | /test.py | 10,565 | 3.90625 | 4 | import tkinter as tk
from tkinter import messagebox
class Security:
def __init__(self, algorimth: str = "cesar") -> None:
"""Aplica el cifrado {'cesar', 'vigenere'} utilizando el alfabeto español
:params
algorimth: str, default='cesar'
Algoritmo a utilizar, soporte ['c... |
fb79a6daf0b3466ad408295608c791be41443be8 | roozbehsaffarkhorasani/bacheha | /fibonachi3.py | 261 | 3.84375 | 4 | a = int(input("How many students in programming class? "))
score_list = []
for i in range(a):
score = float(input("Score: "))
score_list.append(score)
print('AVG:', sum(score_list) / a)
print('MAX:', max(score_list))
print('MIN:', min(score_list)) |
7b30553a63163817c3181e981bf04853ae616395 | jsterling23/CrackingCodeInterview | /interview_questions/ch2/MISC/linked-lists-V2.py | 6,583 | 3.953125 | 4 | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
current_node = self.head
new_node = Node(data)
prev_node = current_node
current_node = cur... |
e86562d63dc451c33877a17b427623a0e688e0b7 | NJU-SE-15-share-review/professional-class | /软统/Exercise28.py | 846 | 3.75 | 4 | # -*- coding:utf-8 -*-
# 下面为大数定律一,伯努利大数定律的python实现,请完成以下练习:
# (1)仔细阅读,理解代码含义,并运行代码,看看结果如何?
# (2)调整泊松分布的参数,看看结果会如何变化?
# (1)此题为普通编程练习题
# (2)scipy.stats.bernoulli.rvs(p,loc=0,size=1)返回size个符合泊松分布的随机变量
import sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import bernoulli
def law_of_large_numbe... |
9562474f43ecc996b41d207128fd82ffb1f202f3 | NJU-SE-15-share-review/professional-class | /软统/Exercise59.py | 772 | 3.765625 | 4 | # -*- coding:utf-8 -*-
# 对于一个包含一系列数字字符串的列表,寻找其中的回文串存入一个列表中并返回
from __future__ import print_function
class Solution():
def solve(self, A):
# use isPalindrom function to check if the string is palindrome or not
result = []
for i in A:
if (self.isPalindrome(i) == True):
... |
ee9d4cca736f6baab9fe326ff64596718953f821 | NJU-SE-15-share-review/professional-class | /软统/Exercise1.py | 1,890 | 4.125 | 4 | #-*- coding:utf-8 -*-
# 下面为针对蒙提霍尔三门问题进行模拟中奖概率的代码,请仔细阅读,理解代码含义,并试着修改Monty Hall程序来模拟最原始的游戏规则。蒙提霍尔三门问题规则如下:
# (1)参赛者会看见三扇关闭的门,其中一扇的后面有一辆汽车,选中后面有车的那扇门就可以赢得该汽车,另两扇门后则各藏有一只山羊
# (2)当参赛者选定了一扇门,但未去开启它的时候,知道门后情形的节目主持人会开启剩下两扇门的其中一扇,露出其中一只山羊
# (3)主持人其后会问参赛者要不要换另一扇仍然关上的门
import random
def MontyHall(Dselect, Dchange):
Dcar = ... |
634ba891da0028d17ce8eca6965c63cda072f4dd | NJU-SE-15-share-review/professional-class | /软统/task1/problem4_fruit.py | 728 | 3.609375 | 4 | # -*- coding:utf-8 -*-
"""
log api example: log('output is: ' + str(output))
"""
from __future__ import print_function
# 已知列表fruits中顺序保存了某商店每日出售的水果品名,
# 例如fruits=['apple','banana','cherry','pineapple','banana','peach','pear','peach','cherry' ],
# 完成函数solve()计算每一种水果的出售次数,存入字典result中并将结果返回
class Solution():
def solv... |
68b4465f0ebc618c9b2b0fdf430400e7bf1d025c | NJU-SE-15-share-review/professional-class | /软统/Exercise36.py | 1,384 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# 下面为样本均值抽样分布-norm分布的python实现,请完成以下练习:
# (1)仔细阅读,理解代码含义,并运行代码,看看结果如何?
# (2)使用其他分布替代norm分布,看看结果如何变化?
# (1)此题为普通编程练习题
# (2)matplotlib.pyplot.subplot(nrows,ncols,plot_number)生成nrows * ncols 个subplot并返回plot_number所指定plot
# (3)numpy.linspace(start,end,num=50)返回start到end之间num个等间距数字
# (4)scipy.stats.n... |
ab9af91a6817c0871325654894f6ad0f02591989 | NJU-SE-15-share-review/professional-class | /软统/Exercise32.py | 1,503 | 3.703125 | 4 | # -*- coding:utf-8 -*-
# 下面为卡方分布的python实现,请完成以下练习:
# (1)仔细阅读,理解代码含义,并运行代码,看看结果如何?
# (2)替换df为不同的自由度,看看结果如何变化?
# (1)此题为普通编程练习题
# (2)matplotlib.pyplot.subplot(nrows,ncols,plot_number)生成nrows * ncols 个subplot并返回plot_number所指定plot
# (3)numpy.linspace(start,end,num=50)返回start到end之间num个等间距数字
# (4)scipy.stats.chi2.ppf(q,df)是... |
b3bf33a36beb89e196b2caa7f918c965c73b8e8f | Fr3dric0/EeyyStarAlgorithm | /app.py | 3,028 | 3.578125 | 4 | import sys
from eystar import eystar
from node import Node
from visualize import generate_board_image
def readfile(path):
with open(path, 'r') as f:
return [line.strip() for line in f.readlines()]
def create_board(lines: list) -> (list, Node, Node):
"""
Takes in a list of strings,
where the ... |
d2c2caad4ba5ffe97c5c83242e11fecff80902ed | kyooryoo/think-python | /10_9.py | 443 | 3.65625 | 4 | def tolist1():
res = []
fin = open('words.txt')
for line in fin:
word = line.strip().strip(' ')
res.append(word)
return res
def tolist2():
res = []
fin = open('words.txt')
for line in fin:
word = line.strip().strip(' ')
res += [word]
return res
# uncomme... |
528aae970aac1db8695590cdf465e0335626bd9f | kyooryoo/think-python | /9_0.py | 1,039 | 3.71875 | 4 | def has_no_e(word):
for letter in word:
if letter == 'e':
return False
return True
def avoids(word, forbidden):
for letter in word:
if letter in forbidden:
return False
return True
def uses_only(word, available):
for letter in word:
if letter not in ... |
204605f60ffbb067fc39920c4a15bac49d53215b | thenickrj/DSA-450 | /Maximum and minimum of an array using minimum number of comparisons.py | 3,639 | 4.0625 | 4 | # Maximum and minimum of an array using minimum number of comparisons
# Method 1 (Simple Linear search)
"""
Initialize values of min and max as minimum and maximum of the first two elements respectively.
Starting from 3rd, compare each element with max and min, and change max and min accordingly
(i.e., if the element... |
41b347b009931d3fd7d3e23511b34fff86b1ec0b | Genskill2/02-bootcamp-estimate-pi-anjusetty138 | /estimate.py | 1,959 | 3.515625 | 4 | import math
import random
import unittest
class TestWallis(unittest.TestCase):
def test_low_iters(self):
for i in range(0, 5):
pi = wallis(i)
self.assertTrue(abs(pi - math.pi) > 0.15, msg=f"Estimate with just {i} iterations is {pi} which is too accurate.\n")
def tes... |
cb9706b51556d3ad027054dc401abbadfa158887 | kkarbowiak/advent-of-code-2015 | /day14.py | 1,596 | 3.59375 | 4 | import re
def get_speed_time_rest_from_instruction(line):
regexp = re.compile('[a-zA-Z]+ can fly ([0-9]+) km/s for ([0-9]+) seconds, but then must rest for ([0-9]+) seconds.')
m = regexp.match(line)
return int(m.group(1)), int(m.group(2)), int(m.group(3))
def get_distance_after_time(speed, time... |
4b1a4f68adfc09e095125f7fd7096da221c1b121 | Bhasheyam/DataStructure-and-Algorithms | /Stack/TwoStackusingarray.py | 1,270 | 3.703125 | 4 | class twostack:
def __init__(self,n):
self.maxsize = n
self.stack = [None] * n
self.topsize1 = -1
self.topsize2 = n
def push1(self,item):
if( self.topsize1 < self.topsize2 -1 ):
self.topsize1 += 1
self.stack[self.topsize1] = item
else ... |
19b407a944e80f2cef18b0bb67a7c8f8d713e4f5 | aditi1206/student-assessment | /students_assessments/utils/directory_management.py | 1,852 | 3.609375 | 4 | """DIRECTORY MANAGEMENT"""
import os
from students_assessments.constants import CSV_EXTENSION, APP_DIRS, CLASS_DATA_FILES_PATH
# TODO: Convert Functions to a Class
def get_files(current_working_directory, extension=CSV_EXTENSION):
"""
GET FILES IN A DIRECTORY
:param current_working_directory: {str} Path... |
3b78396d2a2e4f0d8e3f0e8e914b416d243c316b | RudrakshAgarwal/Python-Notes | /OOPS18.py | 3,684 | 4.15625 | 4 | #Object Introspection:
class Employee:
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname
# self.email = f"{fname}.{lname}11173@gmail.com"
def explain(self):
return f"This Employee is {self.fname} {self.lname}"
@property
def email(self):
... |
0eed6897829d5f6428235bd971985b7bf8c798db | RudrakshAgarwal/Python-Notes | /Health_Management_System_Exercise.py | 4,288 | 4.15625 | 4 | '''
Exercise 5: Health Management System
The task is to create a "Health Management System." Suppose you are a fitness trainer and nutritionist. You have to deal
with three clients, i.e., (Rudraksh, Rahul, Soham, Rishi). For each client, you have to design their exercise and diet
plan.
Instructions:
1) Create a... |
2fcc018e9e025c52605a16d8103c1075b960f8ba | RudrakshAgarwal/Python-Notes | /args & kwargs.py | 4,265 | 4.34375 | 4 | def function_name_print(a,b,c,d,e): #This approach is not suitable when we add larges of name, numbers etc.
print(a,b,c,d,e)
function_name_print("Harry", "Rohan", "Skillf", "Hammad", "Shivam")
def funargs(normal, *args, **kwargs): #The prototype is fixed: first normal, then args and then kwargs. and this will ... |
55bfcec6f7161afa91333fd6f91822babae14c31 | RudrakshAgarwal/Python-Notes | /File Writing.py | 3,184 | 4.09375 | 4 | f = open("Rudra2.txt", "a") # "w" is for write and "a" is for append
a = f.write("Mein ek bhut hi smart or handsome ladka hu \n")
print(a) #This will print no. of characters which has written in the file.
f.close()
#Handle Read and Write both
file = open("Rudra2.txt", "r+") #"r+" this means read and write both... |
641a6f0e24b60a58800af9f58b6d83fe5c09e81e | RudrakshAgarwal/Python-Notes | /OOPS9.py | 4,466 | 4.21875 | 4 | #Multiple Inheritance
class Employee:
var = 8
no_of_leaves = 8
def __init__(self,aname,asalary,arole):
self.name = aname
self.salary = asalary
self.role = arole
def printDetails(self):
return f"My Name is {self.name}. Salary is {self.salary}. and Role is {s... |
b1cd46e2acc5fc5cba394ab81d15945a1ac9c4bc | RudrakshAgarwal/Python-Notes | /OOPS11.py | 2,846 | 4.375 | 4 | #Access Specifiers:
class Employee:
no_of_leaves = 8 #public
_protect = 9 #Protected
__private = 98 #Private
def __init__(self,aname,asalary,arole):
self.name = aname
self.salary = asalary
self.role = arole
def printDetails(self):
return f"My Name is {... |
3de15852cd11c95383802f18c97ffade35f79c6f | RudrakshAgarwal/Python-Notes | /Else & Elif.py | 3,364 | 3.8125 | 4 | var1 = 6
var2 = 56
var3 = int(input())
if(var3>var2):
print("Greater")
elif var3==var2:
print("Equal")
else:
print("Lesser")
list1 = [5,7,8,9,10]
print(5 in list1) #This will return true or false.
print(15 not in list1)
if 5 in list1:
print("Yes it's in the list")
#Quiz:
Legal_age =18
... |
1126d1280782a8aaf046d9aef7d6dcd7eadfff74 | RudrakshAgarwal/Python-Notes | /Read_Newspaper_Exercise.py | 2,143 | 3.96875 | 4 | '''
Problem Statement:-
The task you have to perform is to read the news using python. Build a program that will give you daily top 10 latest
news. For that, you have to check the website https://newsapi.org/ which gives the news API. First, you have to
create an account on that website, and then you will get free... |
38a1dff1f0110a32d61d79fa0812844fb725eeae | RudrakshAgarwal/Python-Notes | /Enumerate Function.py | 3,359 | 4.4375 | 4 | l1 = ["Bhindi", "Aalo", "chopsticks", "Chowmein"]
i = 1
for item in l1:
if i%2!=0:
print(f"Jarvis please buy {item}")
i +=1
for index, item in enumerate(l1):
if index%2==0:
print(f"Jarvis please buy {item}")
'''
An enumerate is a built-in function that provides an index to ... |
cf20a50433336464ce6b9883076aa84e655a9116 | smhtbtb/Maktab | /hw7/3.py | 1,163 | 3.578125 | 4 | class BackUpOpen:
def __init__(self, file_name, mode):
self.file_name = file_name
self.mode = mode
def __enter__(self):
self.back_up = open('back_up_file.txt', 'w')
# with open(self.file_name, 'r') as original:
# helper = original.read()
# self.back_up.w... |
8f9549e9d2cbb4f59a1455e2c5ff57b6bb7e6c27 | smhtbtb/Maktab | /hw1/2.py | 651 | 3.640625 | 4 | sentence = input('Write your sentence: ')
vowels = 0
for i in sentence.lower():
if i == 'a' or i == 'i' or i == 'o' or i == 'e' or i == 'u':
vowels += 1
print('vowels= ', vowels)
Digits = 0
for i in sentence.lower():
if i.isdigit():
Digits += 1
print('Digits= ', Digits)
sum_of_digits = 0
f... |
d10670e3ceb81fe90a9fb1a2a62f7f620c71ee58 | smhtbtb/Maktab | /Example session 13.py | 1,584 | 3.8125 | 4 | class User:
def __init__(self):
pass
class Register:
def __init__(self, name: str, phone: str, pswd: str, email=None):
self.name = self.setter_name(name)
self.phone = self.setter_phone(phone)
self.__pswd = self.setter_pswd(pswd)
self.email = self.setter_email(email)
... |
98680a6bc8558e9652090808f08021e823920910 | smhtbtb/Maktab | /hw1/8.py | 181 | 3.953125 | 4 | n = int(input('give me a num: '))
if n == 1:
print('*')
elif n > 1:
for i in range(n + 1):
print('*' * i)
for j in range(n - 1, 0, -1):
print('*' * j)
|
bc12889cd2131275305e17c1cb643fb8eac10f90 | smhtbtb/Maktab | /hw7/4.py | 506 | 3.609375 | 4 | # import os
#
# for (root, dirs, files) in os.walk('F:\me\Maktab Sharif\جنگو', topdown=True):
# print(root)
# print(dirs)
# print(files)
# print('--------------------------------')
from os import walk
def get_files_of_one_dir(path):
# f = []
for (dirpath, dirnames, filenames) in walk(path):
... |
747993d50c92d71114578f9d4e4cc836a485655e | easywaldo/python_basic | /missing_method_sample.py | 239 | 3.65625 | 4 | standards = {
"tech": "python",
"country": "korea",
"limit": 100,
}
class Tech(dict):
def __missing__(self, key):
standards[key] = "default value"
tech_specs = Tech()
tech1 = tech_specs["arch"]
print(standards)
|
896a2d7c4840532561b4c7a7c655e3561cdd5324 | easywaldo/python_basic | /select_gcd.py | 461 | 3.65625 | 4 | def select_gcd(a, b):
gcd_value = 0
min_value = min(a, b)
for n in range(min_value, 1, -1):
if a % n == 0 and b % n == 0 and n > gcd_value:
gcd_value = n
return gcd_value
print(select_gcd(10, 4))
print(select_gcd(27, 90))
def select_gcd_uqlid(a, b):
print('select_gcd_uqlid', ... |
6e80396c94b7ca4c850e3e9cf43eb04f67b29df3 | easywaldo/python_basic | /rest_argument.py | 169 | 3.53125 | 4 | def fun(a,b,c,d,*rest):
return a,b,c,d,rest
print(fun(*[1,2],3,*range(4,7)))
print(*[1,2])
print(*range(4,7))
print(*range(1,10))
for i in range(4,7):
print(i) |
56726629c94d943997d372e69a6f8b508a5532b8 | easywaldo/python_basic | /search_number.py | 277 | 3.703125 | 4 | def search_number_in_list(searchNumber, list):
index = 0
for item in list:
if item == searchNumber:
return index
index +=1
return -1
print(search_number_in_list(100, [1,2,10, 27, 88, 9, 70, 100, 54, 28, 30, 3]))
|
1f597c06bcd3e752bdbf37a9ecea3803887afda9 | easywaldo/python_basic | /sequence_sample.py | 1,596 | 3.65625 | 4 | # sequence
# container > list, tuple, collections.deque (서로 다은 타입을 저장이 가능하다)
# flat > str, bytes, bytearray, array.array, memoryview (단일 타입만 저장이 가능하다)
# 가변형 > list, bytearray, array.array, memoryview, deque
# 불변형 > tuple, str, bytes
import array
chars = '+_!@#$)&^'
code_list = [c for c in chars]
print(code_list)
... |
7d74c5bf0a4c0063bf86fcbef36af92e53858e70 | easywaldo/python_basic | /dict_hashtable_sampley.py | 975 | 3.71875 | 4 | # hashtable
# key 에 value 를 저장하는 구조 => __dict__
# 파이썬 엔진이 해쉬 기반으로 구성이 되어있음
# python dict => hash table 의 종류
# 키 값에 연산 결과에 따라 직접 접근이 가능한 구조
# key 값을 해싱 하는 함수 >> 해쉬 주소 >> key 에 대한 value 참조
# dict구조
print(__builtins__.__dict__)
# hash 값 확인
t1 = (10, 20, (30, 40, 50))
t2 = (10, 20, [30, 40, 50])
print(hash(t1))
# prin... |
5ae722945cd9cd659812656524f91f71c58d6789 | easywaldo/python_basic | /first_func_sample.py | 1,646 | 3.53125 | 4 | # 일급함수(일급 객체)
# 1. 런타임 초기화
# 2. 변수할당
# 3. 함수 인수 전달
# 4. 함수 결과 반환
def factorial(num: int):
'''
Factorial Function -> num : int
'''
if num == 1:
return 1
return num * factorial(num-1)
class A:
pass
print(factorial(5))
print(factorial.__doc__)
print(type(factorial), type(A))
print(dir... |
2d3a817b925d35f6fd58ef937cec494068683f98 | easywaldo/python_basic | /polymorphism_sample.py | 1,318 | 3.796875 | 4 |
import abc
class Robot(metaclass=abc.ABCMeta):
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
return self.name
@property
def age(self):
return self.age
#Private method 의 경우 __ underscore
def ... |
44f9b2ec144ad34bec5cf7cddc806e011f2d3fe9 | kramburley/SalaryCalculator | /salaryCalculator.py | 2,336 | 4.0625 | 4 | import numpy as np
import os
'''
#constants
'''
number_of_days = 365
number_of_four_weeks = 13
number_of_weeks = 52
number_of_weeks_in_a_month = 4
hours_per_week = 40
options = [0,1,2,3]
program_Start = True
#input must be annual rate
def compute_salary_hourly(annual_amt):
temp = annual_amt / number_of_weeks / ho... |
bd8d784a922565791d86b72a5b68015c372cd35f | markdgoodrich/Project-Euler-Solutions | /pe_27.py | 600 | 3.75 | 4 | #27
#b must be prime
#try 2nd formula when n= 80 to see if a type of divisibility pattern emerges
#80^2 - 79*80 + 1601 = 1681
#1681 = 41^2
#hm....
#1681^2 = 2825761
import math
def is_prime(n):
if any( n % i == 0 for i in range(2,int(math.sqrt(n)+1))):
return False
else:
return True
counter ... |
40079ab9e95b440cc6e2b29f0364e83f4e2be9dd | markdgoodrich/Project-Euler-Solutions | /pe_7.py | 386 | 4.0625 | 4 | import math
def is_prime(n):
if any( n % i == 0 for i in range(2,int(math.sqrt(n)+1))):
return False
else:
return True
counter = 1 #including '2' already
i=3
while counter < 10001:
if is_prime(i) is True:
#print i #testing purposes
counter += 1
i += 2 #only testing odd numbers
... |
20b7087e941c033d3d8b3282e7235f60f0fdc759 | MarijaZ/Casino | /Ugani_skrito_stevilo.py | 368 | 3.65625 | 4 | from random import randint
sec = randint(1,60)
print("Dobrodosli!")
g = 0
while g != sec:
g = int(raw_input("Ugani pravilno stevilko: "))
if g == sec:
print("Zmagal/a si! ")
elif g > sec:
print("Previsoka stevilka.")
else:
print("Premajhna stevilka")
print("Cestitam za pravil... |
fe42173488b980e2dc8fa4ff5e5e2803412c7fff | Kaifee-Mohammad/labs | /PythonLab/leetcode/house_robber.py | 353 | 3.59375 | 4 | class Solution:
def rob(self, nums = list) -> int:
if len(nums) == 0:
return 0
total = nums[0]
for i in range(1, len(nums)):
if i % 2 == 0 and i <= len(nums):
total = total + nums[i]
return total
if __name__ == "__main__":
... |
ed066957836a77773deec292794e9d64d547707c | Kaifee-Mohammad/labs | /PythonLab/animal.py | 288 | 3.65625 | 4 | class animal():
def sound(self, say):
print("it " + say)
class dog(animal):
def barks(self, say):
animal.sound(self, say)
def main():
a = animal()
a.sound("makes a sound.")
a = dog()
a.barks("barks.")
if (__name__ == "__main__"):
main()
|
20215c53da3f32781aa95f0884bee05ef0ff3100 | jingong171/jingong-homework | /王中昊/第二次作业/第四题.py | 491 | 3.546875 | 4 | cities={'bj':{'country':'China','population':'1','fact':'a'},
'sh':{'country':'China','population':'2','fact':'b'},
'gz':{'country':'China','population':'3','fact':'c'}}
for cities_name ,cities_infor in cities.items():
print('\nCities_name:'+cities_name)
Country_name=cities_infor['country']
Popula... |
1b4482af373c7005e2032cc13c0fd2097dc6aea4 | jingong171/jingong-homework | /孙金萌/第四次作业-金工17-1-2017310407-孙金萌/模拟.py | 299 | 3.765625 | 4 | from random import randint
class Die():
"""模拟掷骰子的程序"""
def __init__(self):
self.sides = 6
def roll_die(self):
x = randint(1,6)
print(x)
die = Die()
print(str(die.sides)+"sides")
for i in range(0,10):
die.roll_die()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.