blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
821996a79eb5da411cc19924cc451ff0e2e4da38 | QuakeToEarth/StudentLevel-Attempt | /code.py | 329 | 3.640625 | 4 | import pandas as pd
import plotly.graph_objects as pg
df = pd.read_csv('data.csv')
id = input('Please Enter Student ID : ')
studentdf = df.loc[df['student_id'] == id]
newData = studentdf.groupby('level')['attempt'].mean()
graph = pg.Figure(pg.Bar(
x = ['Level 1', 'Level 2', 'Level 3', 'Level 4'], y = newData
))
gra... |
298356111652db613596be060b41eb69cf2abf9a | martin-tran/ucalgary-room-finder | /src/dbadmin.py | 6,600 | 3.765625 | 4 | import sqlite3
DAYS = {day:x for (x, day) in enumerate(['M', 'T', 'W', 'R', 'F', 'S', 'U'], start=1)}
def humanize_time(time):
"""Convert a time from the database's format to a human readable string.
Args:
time::Int - The time to convert.
Returns:
_::String - The converted... |
886e9a14a2ba4e9fd6a9f01b93ac708865be3f32 | gdoorenbos/adtran-hackathon-cipher | /1-caesar.py | 1,253 | 4.03125 | 4 | """
Rules: Throughout this puzzle, you will get various answers. When you get an answer, put it in the URL after the slash. For instance, this page is hackathon.adtran.com:8080/start. If the first answer is finish (it's not), you would navigate to hackathon.adtran.com:8080/finish to get the next answer. Keep solving un... |
cc937cea6df05260c6713ba3438ffba99ace5784 | litpuvn/MOSS-winnowing-seqMatcher | /cleanUP.py | 1,870 | 3.96875 | 4 | import pygments.token
import pygments.lexers
#Python module pygments is used to tokenize the code files. This module supports most of the popular languages
#http://pygments.org/languages/
#Hence this program can be used to clean up codes written in most languages
def tokenize(filename):
file = open(filename, "r")
... |
996d4b9a0b06f23fbe12e3022786110e72acfdb1 | IonaBartishvili/face_detection | /OpenCV.py | 832 | 3.640625 | 4 | import cv2
# Load the classifiers downloaded
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the image and convert to grayscale format
img = cv2.imread('people3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Calculate coordinates
faces = face_cascade.detectMultiScal... |
f63e59be10b7208ebcdcc195e16073a711d35047 | ThoraxTheImpaler/Potato.py | /Kevin/examplePy.py | 269 | 3.921875 | 4 | print('Hello world')
print("Double quotes")
print('concatena'+'tion')
print('hello','there')
#also concatenates
print('I am',5)
#print('I am'+5)
#cannot convert int to str
#print('I'm 5')
#RIP syntax
print('I\'m 5')
#escape char \ ez
print("I'm 5")
#also works
|
b4a89bf71d1aec7acf7076a7f0862be86ed0259a | trote/stepik | /568/step_5.py | 233 | 3.921875 | 4 | n = int(input())
text = "move "
if n == 1:
text += "up"
elif n == 2:
text += "down"
elif n == 3:
text += "left"
elif n == 4:
text += "right"
elif n == 0:
text = "do not move"
else:
text = "error!"
print(text)
|
6186c0e0d74c2a3a1f0d3e28e24e1cc33ccf803f | Jheandery/FundamentosProgramacion-2021-G2 | /eduhailton.py | 100 | 3.59375 | 4 | print("Hola Mundo")
a=50
b=10
print("suma:",(a+b))
print("resta:",(a-b))
print("multiplicacion:",(a*b)) |
29334254513b8d756828ffdfb4e94e3f9f64d321 | reenaramesh/second | /swap.py | 586 | 3.75 | 4 |
# swap 1st nd last value
"""a=[22,5,4,87,52]
n = len(a)
for i in range(0,n):
temp = a[0]
a[0] = a[n-1]
a[n-1] = temp
print(a)"""
# remove duplicate terms in list
"""new_list=[12,33,44,6,12]
new1_list=[]
[new1_list.append(x) for x in new_list if x not in new1_list]
print(new1_list) """
# fetch the wor... |
3b94901914ba40d20a29f0b89b2c6e8b42bf2e8a | garimasilewar03/Python_Task | /9.py | 976 | 4.4375 | 4 | '''Write a program such that it asks users to “guess the lucky number”. If the correct number is guessed the program stops, otherwise it
continues forever.
number = input("Guess the lucky number ")
while 1:
print ("That is not the lucky number")
number = input("Guess the lucky number ")
Modify the... |
8269c93481ca7fc3370dea035f7b3c367b31a7ba | vincent775/test_nlp | /tokenizer/mm.py | 761 | 3.59375 | 4 | # -*- coding: UTF-8 -*-
#实现基于规则的分词
#正向最大匹配法
import util.dic
class MM():
def __init__(self):
self.windows_size=4
#正向最大匹配法
def cut(self,text):
result = []
#加载词典
dic=util.dic.get_dic(self)
# print(dic)
txt_len = len(text)
index = 0
#
whi... |
d8d351a7620714cec32ce54387c8ff69d3fb4773 | vincent775/test_nlp | /util/dic.py | 424 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
#获取字典
class dic():
dic =[]
def __init__(self):
self.dic = self.get_dic()
def get_dic(self):
dict=[]
# read txt method one
f = open("./data/dic.txt",encoding='UTF-8')
line = f.readline()
while line:
# print(line)
... |
3bc00acae336161ad6d07df1a30e0faccdcd83f4 | katrinawalker06/LC101 | /lc101/crypto/helpers.py | 500 | 3.875 | 4 | import string
alpha_lower = list(string.ascii_lowercase)
def alphabet_position(letter):
return alpha_lower.index(letter.lower())
def rotate_character(char, rot):
new_letter=alphabet_position(char) + rot
small_letter=char.islower()
lower_letter=''
if new_letter>=26:
lower_letter= string.lo... |
93ed0c8e113f9d4a0a6ec614245afaf520a2bd9c | ataheri8/TipsToday | /main-service-master/mount/app/gen_fake_users.py | 798 | 3.59375 | 4 | import csv
HEADERS = ["First Name", "Last Name", "Mobile Number", "Employee ID", "Address",
"City", "Province", "Postal Code"]
if __name__ == "__main__":
print("hello")
with open("/tmp/fake_names.csv", "w") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=HEADERS)
writer.w... |
a398871845121069f7b2610339f8f787ac8e69e6 | lcsouzamenezes/deepstar | /deepstar/util/debug.py | 634 | 3.59375 | 4 | import os
from ansimarkup import ansiprint as print
def debug(message, level):
"""
This function conditionally prints to stdout based on the value of the
DEBUG_LEVEL environment variable as compared to the value of the level
argument.
:param str message: The message to conditionally print to std... |
f6aafaa0583531cbcb8ce33154e29db90b393760 | eddardd/CervicalCancerDetection | /utils/sampling.py | 2,177 | 3.8125 | 4 | import numpy as np
def stratified_sampling(X, y, proportion=0.8, shuffle=True):
"""Stratified Sampling function. Performs sampling on a dataset (x, y) using categories y.
Parameters
----------
X : :class:`numpy.ndarray`
Features matrix of shape (n, d).
y : :class:`numpy.ndarray`
L... |
5ed47bc2085e9808de61264f362a1d16e8eb78bc | softicer-67/ALGORITMS | /Lesson_7/2.py | 695 | 4.15625 | 4 | '''
2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами
на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
'''
from random import randint
def sort(array):
res = []
new_arr = arr[:]
for _ in range(len(new_arr)):
mini ... |
de8f98ee441145fdade65f76498dfa0df9ca8089 | softicer-67/ALGORITMS | /Lesson_2/4.py | 387 | 3.859375 | 4 | '''
4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125
Количество элементов (n) вводится с клавиатуры.
'''
n = int(input('Введите количество элементов: '))
N = 0
range = 1
sum = 0
while N < n:
sum += range
range /= -2
N += 1
print('Сумма', sum)
|
b16fa5b82118b0d71e48b7aaa274e22d65dd0585 | softicer-67/ALGORITMS | /Lesson_1/3.py | 609 | 4.21875 | 4 | """
3. По введенным пользователем координатам двух точек вывести уравнение прямой вида y=kx+b, проходящей через эти точки.
"""
print('Координаты точки A(x1,y1): ')
x1 = int(input('\tx1 = '))
y1 = int(input('\ty1 = '))
print('Координаты точки B(x2,y2): ')
x2 = int(input('\tx2 = '))
y2 = int(input('\ty2 = '))
print('У... |
6e2f6b6d0a2ca0e35cd697ab8ce23e89f8236abc | softicer-67/ALGORITMS | /Lesson_1/7.py | 1,173 | 3.90625 | 4 | """
7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним,
равнобедренным или равносторонним.
"""
b = []
for i in range(3):
x = int(input(f'Введите через... |
8a4584d2434c47a2a6eb30ba54c3fb10cbd30228 | cornell-zhang/heterocl | /tutorials/tutorial_02_imperative.py | 6,057 | 3.84375 | 4 | # Copyright HeteroCL authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Imperative Programming
======================
**Author**: Yi-Hsiang Lai (seanlatias@github)
There exist many applications that cannot be described using only vectorized
code such as `hcl.compute`. Thus, we introduce imperati... |
39053cb9d32fb5c76a44bfb827629ba4e6d5e6f8 | neilsxD/justCodes | /leetcode and gfg/leetCode/try_test.py | 5,954 | 3.5 | 4 | # # # # lis = [[]]
# # # # lis[0].append(2)
# # # # print(lis)
# # # # a = []
# # # # a.extend([2])
# # # # print(a)
# # # # # dic_t = {2: 1}
# # # # # print(dic_t)
# # # # # dic_t[3]= ((1,2))
# # # # # print(dic_t[3][1])
# # # # # dic_t[3] = dic_t[3].append(11)
# # # # # print(dic_t)
# # # # # print(... |
9ac04e45359f5cdfacb9760ea6b621a8aaa5a662 | neilsxD/justCodes | /leetcode and gfg/leetCode/268_2.py | 594 | 3.65625 | 4 |
def main (arr) :
temp , temp2 = 0 , 0
arr.append(arr[0])
for i in range (0,len(arr)) :
temp = arr[i]
while(arr[temp] != -1 and temp != -1) :
temp2 = arr[temp]
arr[temp] = -1
temp = temp2
i+=1
... |
8d5b4157ee7be9c4476bfcca33d39d84f6a7e0ca | Shmuelnaaman/Reinforcement_Learning | /smartcab/agent.py | 4,980 | 3.625 | 4 | import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
class LearningAgent(Agent):
"""An agent that learns to drive in the smartcab world."""
def __init__(self, env):
# sets self.env = env, state = None, next_waypoint = None, and a de... |
775348357da23fe10014d3c6ec2002cc1e127ddd | Highyard/Crypto_Tracker | /stringTemplates.py | 793 | 3.8125 | 4 | class StringTemplates:
# Here the string methods are defined. This makes the code more readable.
# The variables are called in the main.py file.
sortedByName = \
(
"""
SORTED BY NAME
-----------------------
"""
)
sortedByDailyChange = \
(
"""
SORTED BY DAILY CHANGE %
-------------------------------... |
16d40d0a34182faa017a49fb50a09fed7e4111b5 | caolele/adhoc-stuff | /peak/tunrstile.py | 3,612 | 4.28125 | 4 | """
A university has exactly one turnstile. Unfortunately many people want to pass through the turnstile in different directions.
The i-th person comes to turnstile at times[i] and wants to either exit the university(direction=1) or enter the university(direction=0).
People form 2 queues, one to exit one to enter. The... |
ed98750db0fbebd927194be422a46458ef1456f7 | caolele/adhoc-stuff | /peak/merge_sort_counting_inversions.py | 1,159 | 3.640625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def countInversions(arr):
result = 0
def merge(_arr, first, mid, last):
nonlocal result
left = _arr[first:mid]
right = _arr[mid:last + 1]
left.append(float('inf'))
right.append(float('inf'))
... |
2dff538253b69e80bffb0c97f4d9122423f56e8e | Aaronphilip2003/Python_Mosh_All_Programs | /Formatted_String.py | 190 | 3.890625 | 4 | #Aim: To show he working of a formatted String
first="Aaron"
last="Philip"
message=first+" ["+last+"] is a coder"
message2=f"{first} [{last}] is a coder"
print(message)
print(message2) |
ac6d22e98145493cc0941b5025b7454b09dabd0a | Aaronphilip2003/Python_Mosh_All_Programs | /For_Basic.py | 93 | 3.515625 | 4 | # Syntax: for x in range (lower lim upper limit step)
for x in range(5,100,5):
print(x) |
e7ae68b0c8364726c37dd0823b0e6802a55e70a9 | Aaronphilip2003/Python_Mosh_All_Programs | /Car_Start_Stop.py | 566 | 4.03125 | 4 | command=""
start= False
while command.lower()!="quit":
command = input("> ").lower()
if command == "start":
if start:
print("Car already started!")
else:
start=True
print("Car Started.....")
elif command == "stop":
print("Car Stopped..... |
20c30cbcea1a137a4416ac0fd5eb41056b50b6d9 | margarineHound/sorting-algorithms | /reverse_string.py | 576 | 4.125 | 4 | def reverse_string(word, word_new):
if len(word) > 0:
word_new.append(word[-1])
reverse_string(word[:-1], word_new)
return ''.join(word_new)
def reverse_string_loop(word, word_new):
for i in range(len(word)):
word_new.append(word[-(i+1)])
return ''.join(word_new)
def main():
... |
46981ad4de6e8a408302f80921a8290999cc512b | markstali/atividade-terminal-git | /code13.05.py | 2,854 | 4.25 | 4 | #01 - Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações:
# a) tamanho da lista.
# b) maior valor da lista.
# c) menor valor da lista.
# d) soma de todos os elementos da lista.
# e) lista em ordem crescente.
# f) lista em ordem decrescente.
""" L = [5, 7, 2, 9, 4, 1, 3]
... |
bb82e5b7c1d4333129b4fc7968671b2f6369d754 | psgareja/Ds-Algo | /General-Tree.py | 2,009 | 3.78125 | 4 | class Tree:
class Position:
def elemtent(self):
raise NotImplementedError('Must be implemtent by the subclass')
def __eq__(self,other):
raise NotImplementedError('must be implent by the sub class')
def __ne__(self,other):
return not (self==other)
d... |
478ca373da24adfc9232089a19efd530ec43de0b | psgareja/Ds-Algo | /CaesarCipher.py | 931 | 3.65625 | 4 | class CaesarCiphar:
def __init__(self,shift):
encoder=[None]*26
decoder=[None]*26
for k in range(26):
encoder[k]=chr((k+shift)%26+ord('A'))
decoder[k]=chr((k-shift)%26+ord('A'))
self._forward=''.join(encoder)
self._backward=''.join(decoder)
... |
fcf0219c59c08cd603caede3ed9ba08efe4c3f5b | psgareja/Ds-Algo | /dynamic-array1.py | 689 | 3.5 | 4 | import ctypes
class DynamicArray():
def __init__(self):
self.n=0
self.capacity=1
self.A=self.make_array(self.capacity)
def __len__(self):
return self.n
def __getitem__(self):
if not 0<=k<self.n:
raise IndexError('Invalid')
return self.A([k]
def... |
135d0343ecb95fa8839cc6e08a425a7d0f012e08 | shlee0882/coding-practice | /python/programmers/level1/완주하지못한선수.py | 290 | 3.546875 | 4 | # 완주하지 못한 선수
# 효율성 실패함...
def solution(p, c):
p.sort()
c.sort()
for i,j in zip(p,c):
if i != j:
return i
return p[-1]
solution(["marina", "josipa", "nikola", "vinko", "filipa"], ["josipa", "filipa", "marina", "nikola"])
|
9d344a786dd0a72fa7bf576b14653a1eaa7d167b | alexjustbarcelona/ap1-codis-2017-2018 | /2017-10-04 Més Python/p3.py | 554 | 3.78125 | 4 | # La funció power(x, y) retorna x^y, donat que y>=0.
def power(x, y):
p = 1
i = 0
while i < y:
p = p * x
i = i - 1
return p
# La funció primer(n) retorna si el natural n és o no un nombre primer.
def primer(n):
if n <= 1:
return False
# Mira si algun nombre entre 2 i √n... |
cd33c73a6fbaf919ef1bc02e43f4e43084af3c14 | AmberWow123/Projects | /Python programming labs/B5_client_server/client.py | 2,953 | 4 | 4 | # description: This client program shows a menu of setting new path, showing files, showing directories, and quit for the user to choose
# then, this program will check if the input is valid or not, and then send the user input to server, and then it will receive the returned value from server
# ... |
452c4fb84202dc42cc9a4f31c5338ad2a386dc14 | dofany/python300 | /111_120_파이썬 분기문/120.딕셔너리 값.py | 538 | 3.65625 | 4 | # 아래와 같이 fruit 딕셔너리가 정의되어 있다. 사용자가 입력한 값이 딕셔너리 값 (value)에 포함되었다면 "정답입니다"를 아닐 경우 "오답입니다" 출력하라.
#
# fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"}
# >> 좋아하는과일은? 한라봉
# 오답입니다.
fruit = {"봄" : "딸기", "여름" : "토마토", "가을" : "사과"}
a = input("좋아하는과일은? ")
if a in fruit.values():
print("정답입니다.")
else:
print("오답입니다.") |
175f82089dc5b65fbc79b49f2ba70f1dbad54c1d | dofany/python300 | /161_170 파이썬 반복문/169.홀수만 구한 값.py | 216 | 3.71875 | 4 | # 1~10까지의 숫자 중 모든 홀수의 합을 출력하는 프로그램을 for 문을 사용하여 작성하라.
#
# 합: 25
result = 0
for i in range(1,10):
if i % 2 != 0:
result += i
print(result) |
cab3e219537691a8d3387e6c006e1e282a6eac9c | dofany/python300 | /211_220_파이썬 함수/220.print_max.py | 348 | 4 | 4 | # 세 개의 숫자를 입력받아 가장 큰수를 출력하는 print_max 함수를 정의하라. 단 if 문을 사용해서 수를 비교하라.
def print_max(x,y,z):
if x > y:
if y > z:
print(x)
if x < y:
if y > z:
print(y)
if x < y:
if y < z:
print(z)
print_max(3,4,5)
|
4e21ca1df5479e3258ffa059c53fe462a445864e | dofany/python300 | /221_230_파이썬 함수/229.실행 결과.py | 255 | 3.640625 | 4 | # 아래 코드의 실행 결과를 예측하라.
#
# def my_print (a, b) :
# print("왼쪽:", a)
# print("오른쪽:", b)
#
# my_print(a=100, b=200)
def my_print (a, b) :
print("왼쪽:", a)
print("오른쪽:", b)
my_print(a=100, b=200) |
bd0bf0a5dda69498aeaf9cc1d4b2102806ed85af | dofany/python300 | /161_170 파이썬 반복문/163.3의배수.py | 169 | 3.5625 | 4 | # 1부터 30까지의 숫자 중 3의 배수를 출력하라.
#
# 3
# 6
# 9
# 12
# 15
# 18
# 21
# 24
# 27
# 30
for i in range(1,31):
if i % 3 == 0:
print(i) |
eb85cdf2e92a64b205aec046ed43af648e89984f | dofany/python300 | /61_70_파이썬 리스트/69.문자열 split 메서드.py | 363 | 3.515625 | 4 | # 회사 이름이 슬래시 ('/')로 구분되어 하나의 문자열로 저장되어 있다.
#
# string = "삼성전자/LG전자/Naver"
# 이를 interest 이름의 리스트로 분리 저장하라.
#
# 실행 예시
# >> print(interest)
# ['삼성전자', 'LG전자', 'Naver']
string = "삼성전자/LG전자/Naver"
interest = string.split('/')
print(interest) |
38e7f523c40194b7da68f5228f57df063bf0af80 | dofany/python300 | /161_170 파이썬 반복문/165.for문.py | 146 | 3.5 | 4 | # for문을 사용해서 아래와 같이 출력하라.
#
# 0.0
# 0.1
# 0.2
# 0.3
# 0.4
# 0.5
# ...
# 0.9
for i in range(0,10):
print(i/10)
|
aa28ca5380b842401cda2190135accd952c126f1 | dofany/python300 | /51_60_파이썬 리스트/57.리스트 최댓값과 최소값.py | 217 | 3.9375 | 4 | # 다음 리스트에서 최댓값과 최솟값을 출력하라. (힌트: min(), max() 함수 사용)
# nums = [1, 2, 3, 4, 5, 6, 7]
nums = [1, 2, 3, 4, 5, 6, 7]
print("max: %d"%max(nums))
print("max: %d"%min(nums)) |
e68cc20e021a7fab55e7a33f40a580c6ad9e4cae | dofany/python300 | /71_80 파이썬 튜플/74.오류 원인.py | 327 | 3.515625 | 4 | # 다음 코드를 실행해보고 오류가 발생하는 원인을 설명하라.
#
# >> t = (1, 2, 3)
# >> t[0] = 'a'
# Traceback (most recent call last):
# File "<pyshell#46>", line 1, in <module>
# t[0] = 'a'
# TypeError: 'tuple' object does not support item assignment
print("튜플의 값은 수정할 수 없다.") |
7c96f0f262074eab31e12b9505a7cb4f4846807f | dofany/python300 | /231_240_파이썬 함수/235.정수 변환.py | 242 | 3.703125 | 4 | # 콤마가 포함된 문자열 숫자를 입력받아 정수로 변환하는 convert_int 함수를 정의하라.
#
# convert_int("1,234,567")
# 1234567
def convert_int(s):
return int(s.replace(',',''))
print(convert_int("1,234,567"))
|
af3780f36ce9777e32ae8eae9ca5ca371e210ef2 | dofany/python300 | /111_120_파이썬 분기문/116.입력 시간.py | 202 | 3.828125 | 4 | # 사용자로부터 입력 받은 시간이 정각인지 판별하라.
a = input("현재시간:").split(':')
if a[1] == '00':
print("정각 입니다.")
else:
print("정각이 아닙니다.")
|
20abb6590e333b3a46e37e9d01a886b928767675 | ivankwist/data-analytics-exam | /1_Coding.py | 3,350 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1- Coding
#
# ## Problem
#
# Seems like the following function has an error. The function returns random values from a
# list, given the weights. For example: weighted_random([1, 2, 3], [0.5, 0.3, 0.2]), should return 1
# with 50% of probabilities, 2 with 30% and 3 with 20%.... |
d4dc815773eacbba302dc3c6350c3ed0543ace6f | harshavardhanm03/DataStructures | /LinkedList.py | 3,645 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 17:05:33 2019
@author: harsh
"""
#Creating a linked list
#create nodes for each node
#Point each node next to next nodes value
class Node:
def __init__(self,val,next=None):
self.val=val
self.next=None
class Solution:
def traverse(self,node=... |
666dfc9739e11a5a2b93ee7bfcce805316802344 | EmeraldE11/ProgrammingWithFunctions | /week-12/fruit.py | 145 | 3.734375 | 4 | def main():
# Create and print a list named fruit.
fruit_list = ["pear", "banana", "apple", "mango"]
print(f"original: {fruit_list}") |
25736ccf77f1554e609bbe35a8337b6ef65986bc | EmeraldE11/ProgrammingWithFunctions | /discount.py | 618 | 4.09375 | 4 | from datetime import datetime
current = datetime.now()
weekday = 3
# current.isoweekday()
subtotal = float(input("Please enter the subtotal: "))
if (subtotal >= 50.00) and ((weekday == 2) or (weekday == 3)):
discount = subtotal * .1
print(f"Discount amount: ${discount:.2f}")
subtotal -= discount
elif (sub... |
76539502c422538d73653a4773a2a9fd3b110d43 | Dansultan/python_fundamentals-master | /08_file_io/08_02_writing.py | 426 | 3.953125 | 4 | '''
Write a script that reads in the contents of words.txt and writes the contents in reverse
to a new file words_reverse.txt.
'''
fin = open('words.txt','r')
list = []
for word in fin.readlines():
list.append(word)
new_list = []
for word in list:
reversedstring=''.join(reversed(word))
new_list.append(... |
34f88b64105e960ae15d83589f7f808497d3e6e3 | Dansultan/python_fundamentals-master | /04_conditionals_loops/04_07_search.py | 358 | 4.28125 | 4 | '''
Receive a number between 0 and 1,000,000,000 from the user.
Use while loop to find the number - when the number is found exit the loop and print the number to the console.
'''
number = int(input("Please choose a number between 1 and 1,000,000 : "))
i = 0
while i <= 1000000:
i+=1
if i == number:
... |
2b8b5b514e3daf20d8afb5e026cc732dc2d99a9a | Dansultan/python_fundamentals-master | /09_exceptions/09_03_else.py | 180 | 3.96875 | 4 | '''
Write a script that demonstrates a try/except/else.
'''
try:
age = int(input('Please enter your age:'))
except :
print('Noooo')
else:
print("Your age is ",age)
|
3e3dc59db239de899a8db4fbdf73bf0a19c6977c | Dansultan/python_fundamentals-master | /03_more_datatypes/4_dictionaries/03_17_first_dict.py | 323 | 3.671875 | 4 | '''
Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example:
result = {1: 1, 2: 4, 3: 9, ...and so on}
'''
item1=0
item2 = item1*item1
user = {item1: item2}
for x,y in user.items():
if item1<=0:
item1+=1
user[item1]=item2
else:
break
print(us... |
05f89d81c140e24536a8370a3a9ba5faa6a0d2f1 | Dansultan/python_fundamentals-master | /04_conditionals_loops/04_01_divisible.py | 362 | 4.5 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
number = int(input("Please enter a number between 1 and 1,000,000,000 :"))
if number%3 == 0:
print("Your number is divisible by 3")
else:
... |
9db0ee45913e68d0b7080e7387d156a9b814cd14 | acecoder93/python_exercises | /Week1/Day5/File_IO_Notes.py | 2,364 | 4 | 4 | # File I/O = File Input Output
# Read a File
# file_handle = open('lorem.txt', 'r') # "r" stands for read
# contents = file_handle.read() #lorem ipsum is a dummy file that programmers used
# file_handle.close() # This closes off the open connection
# print (contents)
# Write a File
# file_handle = open('newFileTest... |
2430c5d0ad1b3c340be21963928f26b576552196 | acecoder93/python_exercises | /Week1/Day5/PhoneBook_App.py | 2,024 | 4.40625 | 4 | # Phone Book App
print ('Welcome to the latest version of hthe Electronic Phone Book')
print ('Please see the list below of all of the options that are available.')
print ('''Electronic Phone Book
---------------------
1. Look up an Entry
2. Set an entry
3. Delete an entry
4. L... |
40481f8a85390bea84fca8c88c82ab35011c70ea | colledkm/01-IntroductionToPython | /src/m6_your_turtles.py | 2,192 | 3.703125 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Katana Colledge.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with y... |
f5be79c5a49c8cba0824278b2f59ee445e92cc24 | steve9164/maze-generator | /maze.py | 6,542 | 4.375 | 4 |
'''
Maze Generator
By Stephen Davies
Builds a maze using tree construction
'''
# Current idea:
# - Build maze and tree at the same time
# - Start at some square - say (0, 0) for now - and randomly add unused square to leaves of the tree
import random, json
from collections import namedtuple
SquareNode = namedtuple... |
c2942788fadc4b667dc0df14de2f4bfedddc148f | shiseru/DataStructure | /binary_heap.py | 2,059 | 3.8125 | 4 | """"
heap:
- a binary satisfying the heap property and is complete.
heap property:
1. the value of the node is greater than or equal to all of its descendants
complete binary tree (CBT):
- binary tree is complete if and only if
1. every leaf must be in one of the two bottommost levels.
... |
546dce178ae93f71ab5658828f4ca40b00667f19 | szabadkai/daily-katas | /uniq.py | 538 | 3.5 | 4 | import test
def is_unique(s):
charset = set()
for i in s:
if i in charset:
return False
charset.add(i)
return True
def is_unique_no_new_ds(s):
return not any((i[1] in s[i[0] + 1:] for i in enumerate(s)))
if __name__ == "__main__":
test.ok(is_unique("abc"))
test.... |
8d81d4358c95976200bfab5d0384096d4578763f | crisrm96/Python-ejercicios1 | /Ejercicio14-18.py | 117 | 3.75 | 4 | while True:
frase=input('Dime una frase: ')
if frase == 'salir':
break
print(frase)
|
7aca12b6ff9732f41f1a6bf6349a80b690f5913a | crisrm96/Python-ejercicios1 | /Ejercicio14-17.py | 113 | 3.65625 | 4 | frase=input('Dime una frase: ')
letra=input('¿Qué letra quieres que cuente?')
y= frase.count(letra)
print(y) |
e3297e73b01e3c69df8c1f8108dc639e9e0be0c3 | crisrm96/Python-ejercicios1 | /defuser.py | 312 | 3.828125 | 4 | import os
def new_user():
confirm = 'N'
while confirm != 'Y':
username =str(input('Enter the name of the user to add: '))
print('Use the username ' + username + '? (Y/N)')
confirm = str (input ('')).upper()
#if confirm =='Y'
os.system(username)
new_user() |
cc753d455e0d043a7739acb5a78856dca4f7fc8d | crisrm96/Python-ejercicios1 | /Ejercicio14-7.py | 817 | 3.90625 | 4 | def numeroAmes (indice):
m = {
'01':"Enero",
'1':'Enero',
'02':'Febrero',
'2':'Febrero',
'03':'Marzo',
'3': 'Marzo',
'04':'Abril',
'4':'Abril',
'05':'Mayo',
'5':'Mayo',
'06':'Junio',
'6':'Junio',
'0... |
78f3e711ebed705e50eb6cc4c78db3e6a6c6fc65 | aadilkhhan/Conditional-Expressions | /06_pr_01.py | 408 | 3.953125 | 4 | num1 = int(input("Enter number 1 : "))
num2 = int(input("Enter number 2 : "))
num3 = int(input("Enter number 3 : "))
num4 = int(input("Enter number 4 : "))
if (num1>num2):
f1 = num1
else:
f1 = num2
if (num3>num4):
f2 = num3
else:
f2 = num4
if (f1>f2):
print("The greatest of ... |
aa3bc6fc02567c1133a7f903897f31b9ed7e71ce | gabrielx52/code-katas | /src/first_non_repeating_number.py | 585 | 3.84375 | 4 | """Kata: First non-repeating number - Return first non-repeating number.
#1 Best Practices Solution by tachyonlabs, gianneng, Echezeaux, john_doe_web
def first_non_repeating_letter(string):
string_lower = string.lower()
for i, letter in enumerate(string_lower):
if string_lower.count(letter) == 1:
... |
64b03bade736c1c05597dd761540d58f79368df0 | ivaneyvieira/pythonJango | /copiaArquivo.py | 290 | 3.640625 | 4 | #!/usr/bin/env python3
def copiaArquivo(origem, destino):
forigem = open(origem, 'r')
fdestino = open(destino, 'w')
print('Copiando', end='')
for texto in forigem:
fdestino.write(texto)
print('.', end='')
copiaArquivo('arquivoNum.txt', 'arquivoNum2.txt') |
926a60d1843e0e1161b64521cbd91c5808fec66d | ivaneyvieira/pythonJango | /testeIF.py | 219 | 4.21875 | 4 | #!/usr/bin/env python3
num = int(input("Digite um número: "))
if num % 2 == 0:
print("Eh par")
else:
print("Eh impar")
if num % 2 == 0:
print("Eh um número par")
else:
print("Eh um número impar")
|
6507d0c392d22062f6e8ff3e0d8dbbe6236dc9bd | ningke/udacity_cs212 | /lession1_poker/lession2/floor_puzzle.py | 1,240 | 4.0625 | 4 | #------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a h... |
e71b1573a8d35343eb1a178051dc8bc7cc7e0c22 | nielsen192/PythonMegaCourse | /Exercises/exercise5.py | 554 | 3.640625 | 4 | temperatures=[10,-20,-289,100]
def c_to_f(c):
if c > -273.15:
f=c*9/5+32
return f
with open("temps.txt",'w+') as file:
for temp in temperatures:
file.write(str(c_to_f(temp)) + "\n")
## Solution 2
temperatures=[10,-20,-289,100]
def writer(temperatures):
with open("temps.txt"... |
e11238a3be69695b4523d92c5187bfb7ee81a289 | Alex9823/hw | /HW5/ДЗ5.py | 139 | 3.9375 | 4 | a=[]
n=input()
while n!= '':
if n.endswith('re') or n.endswith('ri'):
a.append(n)
n=input()
else:
print(a)
|
3a1485adcfde1d73fc77e0d90a53741e6f24430b | oinqu/network-protocol-design-course | /chat/Message.py | 1,675 | 3.859375 | 4 | # -*- coding: utf-8 -*-
class Message:
"""
Message object.
Author: Stanislav Grebennik
This class represents an incoming or outgoing message. Each message is stored in memory
as a separate object.
Main purpose of this class is to be a cache for message segments. The cache can be used in case... |
18e58f8a8c7e1ddb3fdd79cd1f5b46cc9ce889ac | zahidur124/Python-Projects | /Print Checkerboard.py | 2,246 | 4 | 4 | ##
## ***************************************************
## Zahidur Abedin (20549852)
## CS 116 Winter 2015
## Assignment 05, Problem 2
## ***************************************************
##
import check
#new_line(n) consumes n, an Integer, and prints a pattern consisting of
# '#', and produces none.
#new_line: I... |
5d4fd7fbd8754c5a181039df07b4848596a08635 | marvinmendozajr/BIOL5153 | /Chapter_Exercises/Ch8_exercise.py | 373 | 4 | 4 | #set DNA variable
dna = "ATGTTCGGT"
codon1 = dna[0:3]
codon2 = dna[3:6]
codon3 = dna[6:9]
#View chunks of DNA
print(codon1, codon2, codon3)
#calculate the start position for the final codon
last_codon_start = len(dna) - 2
#process the dna sequence in three base chunks
for start in range(0,last_codon_start,3):
codo... |
76384fcd407b5d010b9bb56bac5f23c71aa45a0d | chloe-wong/leetcodechallenges | /088_Merge_Sorted_Array.py | 1,281 | 4.28125 | 4 | """
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, ... |
720243b942fe1e5c274c020bf1934c889ec60f56 | chloe-wong/leetcodechallenges | /066_Plus_One.py | 701 | 3.734375 | 4 | """
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, e... |
616b930ffcc7f4179580ac6cf8e81129cb641da7 | sokkyyy/news-highlight | /app/models.py | 916 | 3.796875 | 4 | class Source:
'''
Class to create the news source instances.
'''
def __init__(self, id, name, description):
'''
Initilization method to instantiate Source objects.
Args:
id: The unique identification of Source object.
name: The name of the Source object
... |
6e86913973f28c15ffd8996fc9697624d562f8dc | hudiankun/study | /scratch_10.py | 317 | 3.78125 | 4 | import random
for i in range(5):
# random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print(random.randint(1,20))
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print(random.random())
|
f788a30c4e9a80b3520624d6f5e1875882b976a7 | atadriansoon/python_playground | /python_learn/grades_calculator.py | 752 | 3.90625 | 4 | grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(scores):
result = 0
for each in scores:
result += each
return result
def grades_average(grades):
dividend = grades_sum(grades)
divisor = float(len(grades))
return dividend/divisor
def grades_varian... |
31a3302e3bab009027a5d0aa7c024c0a50390f76 | emragins/demo-catch | /source/ballthrower.py | 793 | 3.5 | 4 | import collisions
class BallThrower(object):
def __init__(self):
self.holdsBall = None
self.hitBall = False
#so the ball isn't caught as soon as it's released
self.throwTimer = 10
self.throwTimerMax = 10
def Update(self):
if self.holdsBall:
return
if self.throwTimer < self.thr... |
79f1d2c44c9e858eb586af5b9860d57dd0d8b32f | Ian0113/Python-Test | /20181029/例外處理.py | 375 | 3.59375 | 4 | b = True
while b:
try:
inp = int(input('請輸入整數:'))
print('{0} 為 {1}'.format(inp, '奇數' if inp % 2 else '偶數'))
b = False
except ValueError:
print('請輸入整數!')
except EOFError:
print('程式中斷')
b = False
except:
print('不明程式中斷')
b = False
print('再見~')... |
6b0b945e3664f6ac8fd578d103754836a7669fd7 | Ian0113/Python-Test | /20181008/tst_1008.py | 268 | 3.6875 | 4 | list_garage = ["Banz", "BMW", "Rolls-Royce"]
tuple_garage = ("Honda", "Toyota", "Nissan")
print("迴圈取出(會多一個字尾)", end='-----')
for s in list_garage:
print(s, end=" >")
print()
print("類指標取出", end='-----')
print(*list_garage, sep=" >")
|
14448fdf092025b4d05db9bbbe2f9e29b6031a59 | Ian0113/Python-Test | /final_test_20181204/MySQLite.py | 1,818 | 3.578125 | 4 | import sqlite3
class typeForSQL:
CHAR = " char"
TEXT = " text"
AI = " integer primary key autoincrement"
INT = " integer"
NOT_NULL = " not null"
class MySQLite:
def __init__(self, dbName):
self.conn = sqlite3.connect(dbName)
def createTable(self, tableName, dictField):
t... |
c029dcc81d399d812767e1fefcf03a11807310c4 | royalxsarthak/C-100 | /ATM.py | 902 | 3.71875 | 4 | class ATM(object):
def _init_(self,cardnumber,cvv):
self.cardname=cardname
self.cardnumber=cardnumber
self.expirydate=expirydate
self.cvv=cvv
def cashwithdrawal(self,cardnumber,cvv):
print("Cash withdrawal successful for "+cardnumber )
def balanceenquiry... |
a5bfc3163002084e274f971292f7fd5fe51916b6 | sardar1023/myPyGround | /OOP_impl.py | 2,227 | 4.53125 | 5 | #Python is amazing language. You can also implement OOPs concepts through python
#Resource: https://www.programiz.com/python-programming/object-oriented-programming
####Creat a class object and method####
class Parrot:
species = "bird"
def __init__(self,name,age):
self.name = name
self.age =... |
829f8731ae1f42aba338be5fca3d3a462077ae8c | LinhN16/eeb-c177-project | /project-script.py | 3,265 | 3.9375 | 4 | import pandas
# need pandas to import dataset
import numpy
# need numpy for numerical analysis
import matplotlib.pyplot as plt
# need this to plot visual representation of data
import csv
# need csv for file reading and writing
def np_from_csv(csv_file):
temp_data = pandas.read_csv(csv_file, header = None)
dat... |
8335f02d62792fa297d2b86c8e8be3a9070ffeee | Gudavis/python_simple_game | /hangman/hangman.py | 4,356 | 3.765625 | 4 | import random
def play():
welcome()
secret_word = get_secret_word()
correct_letters = show_correct_letters(secret_word)
print(correct_letters)
hanged = False
matched = False
errors = 0
while(not hanged and not matched):
try_letter = player_try_letter()
... |
e96c3b0c2e4352ef18044a4355e0d875e34ba637 | yiyuqiuchi/python-practise | /devops/ping.py | 715 | 3.640625 | 4 | #!/usr/bin/env python
#description:ping module
import os
def To_view_help():
print """
a ---- check hosts is alive or not.
b ---- check hosts' uptime.
"""
item = raw_input("please enter an item: ")
return item
def To_ping_host():
default_ip = ['132.96.77.29', '132.96.77.130']
for ... |
a66edfbbb549c647d3cee9df5a4742551e2bc09b | LuisFelipeUrena/Graphs | /projects/ancestor/ancestor.py | 7,313 | 4.0625 | 4 | # from projects.graph import Graph
# Note: This Queue class is sub-optimal. Why?
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
... |
770b5ed3683ea8a43ad479170894becb5549d43f | pakeng/python | /PyTest/oop/oop_class.py | 1,106 | 4.09375 | 4 | # 测试面向对象编程
class People(object):
def __init__(self, human_id=-1):
self.__dna = None
self.__id = human_id
self.__type = 'HUMAN'
def get_type(self):
return self.__type
def get_id(self):
return self.__id
def get_dna(self):
return self.__dna
def print... |
f5d6cb6bc9bc83425f61b30e73dbe117486e65fd | anliec/GTL_autonomiousRobotic | /face_detect/nodes/rosfacedetect.py | 4,091 | 3.515625 | 4 | #!/usr/bin/python
"""
This program is demonstration for face and object detection using haar-like features.
The program finds faces in a camera image or video stream and displays a red box around them.
Original C implementation by: ?
Python implementation by: Roman Stanchak, James Bowman
"""
import roslib
import sys... |
17cb6f794e10a7c838bb2b781ceaf4a3bc82468a | Tibisfly/firstExercisesOfPython | /exercises/19-Looping-With-FizzBuzz/app.py | 277 | 3.8125 | 4 | import random
def fizz_buzz():
for i in range(1, 101):
if (i % 3 == 0) and (i % 5 == 0):
print("FizzBuzz")
elif (i % 3 == 0):
print("Fizz")
elif (i % 5 ==0):
print("Buzz")
else: print(i)
fizz_buzz()
|
13da1ab6ad5d2b8ac194fd937d67e56a6d12f90b | Deondrede/AniRec | /test/PlotRec.py | 5,884 | 3.5625 | 4 | # Following tutorial at https://www.datacamp.com/community/tutorials/recommender-systems-python
# Importing pandas due to data manip and analysis
import json
import pandas as pd
import re
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kernel
# ... |
2ac8c63a05d3c36ad3c04e6a1f95513acd777563 | hguzman/flask-rest-api | /clase4/models/peticion.py | 538 | 3.5 | 4 | import pytz
from datetime import datetime
timezone = pytz.timezone("America/Bogota")
class Peticion:
def __init__(self, cedula, peticion, fecha_atencion,estado = "Creada"):
self.cedula = cedula
self.peticion = peticion
self.fecha_atencion = timezone.localize(datetime.strptime(fecha_atencio... |
ad56b083441b129aedde2f61ef207fff5d0ec65a | DimaKalbfleysh/ZombieGun | /bonus.py | 1,402 | 3.8125 | 4 | from random import randrange
import pygame
from sprite import GIFT
class Bonus:
""" The class is responsible for behavior of the bonus. """
def __init__(self, win, sprite, hero, game):
self.win = win
self.gift_x = randrange(20, 400)
self.gift_y = -100
self.bonus_y = 260
... |
99962d1c4eba31c6cc61e686fa475dc46c87699f | praveenkumarjc/tarzanskills | /loops.py | 250 | 4.125 | 4 | x=0
while x<=10:
print('x is currently',x)
print('x is still less than 10')
x=x+1
if x==8:
print('breaking because x==8')
break
else:
print('continuing....................................')
continue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.