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 |
|---|---|---|---|---|---|---|
a4d9de3b6d7217ede3f6615ed997d49c5ac0b923 | vishal2835/Internship-of-Python-Django | /Day 2/touple.py | 204 | 3.5625 | 4 | list1=(88,89,90,100,"vishal")
print(list1[2])
print("the value of list1[0:4] = ",list1[0:4])
print("the value of list1[0:4] = ",list1[:5])
print("the value of list1[0:4] = ",list1[:4])
print(type(list1)) |
1ba5a9fe1d19da445bee3c4ac0eb2526323e40e3 | LeonardoRamirezAndrade/DataAcademy | /primera_semana_reto3.py | 1,125 | 4.03125 | 4 | #Reto 3 - Conversor de millas a kilómetros
#Imagina que quieres calcular los kilómetros que son cierta cantidad de millas. Para no estar repitiendo este cálculo escribe un programa en que el usuario indique una cantidad de millas y en pantalla se muestre el resultado convertido a kilómetros.
#Toma en cuenta que en cad... |
a49ee3b21d43e92dd044374d3a18f9e894c8f301 | kaitlynson/SDL-lab-research | /reorderingSOCcodes/reorder.py | 610 | 3.640625 | 4 |
class Recoder(object):
def __init__(self, dictionary):
self.d = dictionary
def recode (self, old_value, strict=False):
if strict==True:
return self.d[old_value]
else:
return self.d.get(old_value, old_value) # if val not there and on strict ret err... |
3fd77d370ebdc05c5bbbbb946a17a54a6d78c2a9 | dhildreth/pyunit_intro | /suite/src/text/goodbye.py | 820 | 3.90625 | 4 | '''This is a simple program to demonstrate how to create a unittest in
Python. For more information and documentation, please see the official
documentation page here: http://docs.python.org/library/unittest.html'''
import unittest #Include the pyUnit unittest framework
def goodbye(a):
'''A simple function to... |
f1d9493d7dc32dfa492a3e029128e688c6665462 | jsa4000/Getting-Started-Python | /Basic/Functions.py | 9,070 | 3.90625 | 4 |
"""
It's needed to put some documentation using pyLint.
You can disable by using some directives as you can see some lines bellow-
"""
import time
# The Python programing language
# pylint: disable=invalid-name
#To run the code in Visual Studio Code Just press Ctrl+Shift+B
x = 1
y = 5
def my_sum(parm_x, param_y):
... |
7dd51e1260472324ac2fe4feb9adf50bd5f5cb82 | jsa4000/Getting-Started-Python | /Basic/Classes.py | 10,808 | 4.40625 | 4 | """
This file is going to explain some of the functionailty of the Classes
"""
# pylint: disable=invalid-name
#exec
print("#Creating Classes ")
# Following a basic definition of a Class using Python
class Car(object):
"""
Documentation for the class
"""
# Global variables shared for all the instance... |
9d5bea9e2af5108c64898075fc1c3efd15b52507 | jsa4000/Getting-Started-Python | /Basic/Pandas.py | 17,323 | 4.3125 | 4 | """
This is the Pandas basic guide for Python
pandas is a software library written for the Python programming language
for data manipulation and analysis. In particular, it offers data structures
and operations for manipulating numerical tables and time series. pandas
is free software.abs
The name is derived from the... |
3d658a5aad21f37950db9b7d9d968830694d5d72 | jsa4000/Getting-Started-Python | /Basic/Sequences.py | 5,733 | 4.46875 | 4 | """
This is a document to explain how the sequences works in python
"""
# pylint: disable=invalid-name
def my_sum(param_x, param_y):
"""
This is a simple funciom
"""
return param_x + param_y
print("# TYPES")
# Let's get started by seeing what it the type of a string
my_string = "This is a sequence"
p... |
279cf58493ba2c62f768303ffa93dd84776d2a90 | jsa4000/Getting-Started-Python | /Advanced/Numpy/Main.py | 1,896 | 3.96875 | 4 | import numpy as np
import Statistics
import DataSet
import Plotter
from NeuralNetwork import NeuralNetwork
from BackPropagation import BackPropagation
def main():
# Start the code
# Get the inputs and expected outputs to train the Neural Network
inputs, outputs = DataSet.getDataSet( ".\Data\data_sets.... |
7cb13329a33e0967a26267a90f88692d194ea13e | yanavedel/Partitioning | /split_by_capacity.py | 7,429 | 3.5 | 4 | """Algorithms for partitioning data.
One-dimensional case. Partitioning by one feature.
"""
from __future__ import division
import collections
import itertools
import random
import pulp
def split_by_capacity(vehicles, k):
"""Split vehicles by capacities.
Splitting set of vehicles into `k` subsets with alm... |
4583257b37eab2a239f9e6e2026e79b41a832efb | ThomasjD/Week2 | /Shopping_list.py | 2,697 | 4.09375 | 4 | import os
from random import*
class Shopping_lists:
def __init__(self, shopping_list, item_list, price_list):
self.shopping_list = shopping_list
self.item_list = item_list
self.price_list = price_list
def add_list(self, item, quantity, price):
self.item... |
6f981cffe48a96eb3506b95f21f7135f7accffef | ytyi/Introduction-to-algorithm | /knapsack.py | 3,075 | 3.609375 | 4 | import timeit
import numpy as np
import random
import matplotlib.pyplot as plt
def knapsack(total,L):
if total==0:
return 1,[]
if len(L)==1 and L[0]!=total:
return 0,[]
elif len(L)==1 and L[0]==total:
return 1,L
else:
num=L[0]
Lti=[]
for i in range(0... |
23abdf186a23430a0abf00e029161641d797ada3 | sttteephen/Collision | /collision.py | 6,840 | 3.578125 | 4 | import pygame
import random
# Import pygame locals
from pygame.locals import (
K_q,
K_r,
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
KEYUP,
QUIT,
)
# Define a player object by extending pygame.sprite.Sprite
# the surface drwn on the screen is an attribute of player
class Player(pyga... |
c785987e560d990ac54670b5c136d862802c2017 | professorgilzamir/artificialintelligence | /gradient_demo_it_pynative.py | 2,214 | 3.8125 | 4 | '''
=========================================================================
Uma demonstração simples de uso do gradiente de descida em uma
superfície bidimensional.
Autor: Gilzamir F. Gomes (gilzamir@outlook.com, gilzamir@gmail.com)
=========================================================================
'''
from m... |
f16e43c21e22b78a00ea9f2c266ad106ace3ba57 | Harsh-B-Patel/League-of-Legends-Riot-Api | /APIGrabber.py | 2,355 | 3.578125 | 4 | #First we need to import requests. Installing this is a bit tricky. I included a step by step process on how to get requests in readme.md which is included in the file along with this program.
import requests
def requestSummonerData(region, summonerName, APIKey):
#Here is how I make my URL. There are many w... |
b0d067d2c1772e0ed0e942532789c7912be730b9 | Afsaan/Python-Coding-Practice | /hidden.py | 766 | 3.8125 | 4 | """
Given an array of integers, find another integer such that, if all the elements of the array are subtracted individually from that number, then the sum of all the differences should add to 0. If any such integer exists, print its value otherwise print '-1'.
Input:
3
1 2 3
where:
First line represents ... |
5dd033a8cec4906dd835b0b32e536afa3f42497d | wenima/statistics | /codewars/Python/src/linear_regression.py | 1,009 | 3.921875 | 4 | """Module for solution to https://www.codewars.com/kata/linear-regression-of-y-on-x."""
import operator as op
import numpy as np
from scipy import stats
def regressionLine(x, y):
"""Return a tuple of intercept and slope of a given line x_coords, y_coords."""
sum_xy = sum([xy for xy in map(op.mul, x, y)])
... |
e5d111d2f756cca2c5ab771bd4315d4b18101795 | wenima/statistics | /codewars/Python/src/unfair_dice_OR.py | 628 | 3.828125 | 4 | """Module for solution to https://www.codewars.com/kata/statistics-in-kata-1-or-case-unfair-dice."""
def mutually_exclusive(d6, n1, n2):
"""Return a string containing the probability of either n1 or n2 being rolled
or None if input is invalid."""
out = sanitize_input(d6)
if out:
return None
... |
1c38b76f61bd0ba268f0430976c59f729e82af1a | limfiq/DasarPython3.9 | /2.number.py | 75 | 3.578125 | 4 | a=1
b=5
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
print(a%b) |
65047fd02025a90a840f071674bbcd17040b8d7f | VilMe/fishes | /fish.py | 2,450 | 3.90625 | 4 |
class Fish:
def __init__(self, first_name, last_name="Fish",
skeleton="bone", eyelids=False):
self.first_name = first_name
self.last_name = last_name
self.skeleton = skeleton
self.eyelids = eyelids
def swim(self):
print("The fish is swimming.")
de... |
2b68547c785f4531e6d1068fec9c15da37e38760 | Morfindien/validator | /password validator (1).py | 422 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
password = input("Password: ")
password_list = list(password)
password_len = len(password_list)
spaces = " " in password
number = any(x.isdigit() for x in password)
special = any(x.isalnum() for x in password)
if spaces == False and number == True and special ==... |
488a28f55a962fed9075546670b5794315482eef | gabijap/NLP-Enchanced-Search | /data/wikipedia/clean_data.py | 1,742 | 3.5 | 4 | """
This is for cleaning wikipedia files:
1. One sentence per line
2. Lower case (only lower case words exist in vocabulary)
3. Splitting sentences to words (like mr. will be changed to mr, as only mr exists in vocabulary),
This will also remove the punctuation marks, as they are not a words according by g... |
ee4a7c8672c7a55fad5f37a965a11e1ffcb24ecb | paras-jain/algorithms | /mergeSort_Invesions.py | 1,289 | 3.53125 | 4 | inversions = 0
def merge_and_count_inversions(left , right):
global inversions
i=0
j=0
result = []
inversions_indicies = []
while i < len(left) and j <len(right):
if right[j]<left[i]:
result.append(right[j])
j +=1
if j not in inversions_indicies:
... |
77ee96c305f1d7d21ddae8c1029639a50627382b | SamuelHealion/cp1404practicals | /prac_05/practice_and_extension/electricity_bill.py | 1,317 | 4.1875 | 4 | """
CP1404 Practice Week 5
Calculate the electricity bill based on provided cents per kWh, daily use and number of billing days
Changed to use dictionaries for the tariffs
"""
TARIFFS = {11: 0.244618, 31: 0.136928, 45: 0.385294, 91: 0.374825, 33: 0.299485}
print("Electricity bill estimator 2.0")
print("Which tariff a... |
823282e7460b9d11b4d4127fa68a87352a5543ce | SamuelHealion/cp1404practicals | /prac_02/practice_and_extension/word_generator.py | 2,154 | 4.25 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
def first_version():
"""Requires c and v only"""
... |
d2539727c20ffae59e81cccadb78648b10797a5d | SamuelHealion/cp1404practicals | /prac_06/guitar.py | 730 | 4.3125 | 4 | """
CP1404 Practical 6 - Classes
Define the class Guitar
"""
VINTAGE_AGE = 50
CURRENT_YEAR = 2021
class Guitar:
"""Represent a Guitar object."""
def __init__(self, name='', year=0, cost=0):
"""Initialise a Guitar instance."""
self.name = name
self.year = year
self.cost = cost... |
7ed8c1c53c80c4740739308c7768e5cb65fe92e5 | SamuelHealion/cp1404practicals | /prac_02/practice_and_extension/random_boolean.py | 854 | 4.25 | 4 | """
Three different ways to generate random Boolean
"""
import random
print("Press Q to quit")
print("What random function do you want to run: A, B or C? ")
user_input = str(input("> ")).upper()
while user_input != 'Q':
if user_input == 'A':
if random.randint(0, 1) == 0:
print("False")
... |
d47f116b7633041984bd9f974da5ede5af6face3 | SamuelHealion/cp1404practicals | /prac_08/taxi_test.py | 446 | 3.71875 | 4 | """
CP1404 Practical 8 - Inheritance
Program to test inheritance of the taxi class from the car class
"""
from taxi import Taxi
def main():
"""Test the Taxi class."""
prius = Taxi('Prius 1', 100)
prius.drive(40)
print(prius)
print("The current fare is ${:.2f}".format(prius.get_fare()))
prius.... |
7a91b87e5da468bbba0cb2b7335fa9c51bd44862 | SamuelHealion/cp1404practicals | /prac_04/subject_reader.py | 730 | 4.03125 | 4 | """
CP1404/CP5632 Practical
Data file -> lists program
"""
FILENAME = "subject_data.txt"
def main():
"""Program for taking data from a file and displaying it with context"""
data = get_data()
print_data(data)
def get_data():
"""Read data from file with the structure: subject, lecturer, number of st... |
dedceffbeea74f9e79d1772bd90e9609d830f347 | rynemccall/lightning-talk | /random/shuffle/demo.py | 842 | 3.78125 | 4 | #!/usr/bin/env python
import copy
import random
NUMBER_OF_SIMULATIONS = 100000
def shuffle(items):
""" A biased implementation of the Fisher-Yates shuffle
:return: List[items]
:rtype: List[Any]
"""
items = copy.deepcopy(items)
for i, _ in enumerate(items):
swap_index = random.ran... |
ebc30bac29808390fa692b66fd1d402acc0470a3 | kevinhu98/EulerProject | /Problem_16.py | 508 | 3.6875 | 4 | """
https://projecteuler.net/problem=16
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""
def Problem_16():
product = 1
for i in range(1000):
product *= 2
product = str(product) # convert to string to allow splitting
dig... |
1d3c87186f6ee211144ba8f1e8045f91450a9c41 | SushAzad/BorneanBirds | /xeno-canto-download.py | 583 | 3.828125 | 4 | # file download script by Khalsa Labs
# MP3 file download
import urllib.request
import sys
mp3_link = input('Enter the link for mp3 file e.g: http://abc.com/fil1.mp3: ')
try:
urllib.request.urlretrieve(mp3_link, "bird1.mp3")
except Exception as e:
print(e)
sys.exit()
ext = mp3_link.split('.')[-1]
if... |
28856e414bf5484f7fba5ef60b3f76d3c2ac93f5 | AndreiZavo/STIHL-Application | /STIHL Last App/Backend/Domain/Date/Date.py | 3,693 | 4.3125 | 4 | import datetime
class Date(object):
def __init__(self, year=0, month=0, day=0):
self.__day = day
self.__month = month
self.__year = year
# Getters
@property
def day(self):
return self.__day
@property
def month(self):
return self.__month
@property... |
e9ffc4b98b05ce7ef499e9c42ec22bc892576f4b | KataBedn/AutomatedTestingExercise | /utilities/dataGenerator.py | 404 | 3.625 | 4 | import random, string
class DataGenerator:
@staticmethod
def generate_random_number_with_n_digits(n) -> int:
lower = 10 ** (n - 1)
upper = 10 ** n - 1
return random.randint(lower, upper)
@staticmethod
def generate_random_string(length=10, chars=string.ascii_uppercase + string... |
4b582e7b57e865131632b2efb3eb2d6e5396a52c | sombriyo/random_questions | /bit_manipulation/divide_two_numbers.py | 1,099 | 4 | 4 | '''
Divide two number without using / operator
'''
import numpy as np
def brute_force(x, y):
'''
This will calculate x / y
'''
div = 0.0
if x > y:
a = x
b = y
elif x < y:
a = y
b = x
while a >= b:
a -= b
div += 1
if x < y:
div = n... |
5f2ab718a6549968f584f15e39bb943f2fd8571e | Yi-Pin-chen/yzu_python_20210414 | /day05/Set串列.py | 276 | 3.640625 | 4 | import random as r
lotto = set() #不重複串列
lotto.add(10)
lotto.add(20)
lotto.add(10)
print(len(lotto),lotto)
#今彩539電腦選號1~39 取出任意5個不重複的號碼
lotto=set()
while len(lotto)<5:
n= r.randint(1,39)
lotto.add(n)
print("n=",n)
print(lotto)
|
1bec9502a6cf34eaf461dd1c91d04526fe442567 | Yi-Pin-chen/yzu_python_20210414 | /day03/BMI 多筆計算.py | 398 | 3.609375 | 4 | import math
"""
170,60
180,70
160,60
"""
import math
def GetBMI(h,w):
bmi = w/math.pow(h/100,2)
#result = "Too Fat" if bmi>23 else "Too Thin" if bmi <=18 else "正常"
result = "過輕"
if 18 < bmi <= 23:
result = "正常"
elif bmi > 23:
result = "過胖"
print("h=%.1f w=%.1f bmi=%.2f result=%s" % (h... |
817d4b40dc4010e755c9300d55de8fd75f554069 | Yi-Pin-chen/yzu_python_20210414 | /day03/BMI 輸入.py | 236 | 3.9375 | 4 | h= input("請輸入身高 : ")
w= input("請輸入體重 : ")
print(h,type(h))
print(w,type(w))
h= float(h) #將Str 轉成 float
w= float(w) #將Str 轉成 float
print(h,type(h))
print(w,type(w))
bmi = w/((h/100)**2)
print("%.2f" % bmi) |
1226bf347a2c7d5fe8edecd55869b1b5ce546167 | casc1990/python-s14 | /day2/with_as语句.py | 439 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:pengbo
with open('yesterday','r',encoding='utf-8') as f: #with...as(文件访问完了,会自动关闭)
for line in f:
print (line.strip())
with open('yesterday','r',encoding='utf-8') as f, \
open('yesterday3', 'r', encoding='utf-8') as f2: #python2.7以上可以2个文件(一行代码不易超过... |
cce5402c916457d536ecffcbd1790d0b5211e8dd | casc1990/python-s14 | /day1/format1.py | 290 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:pengbo
user = input('user: ')
age = int(input('age: '))
print (type(age))
job = input('job: ')
salary = int(input('salary: '))
info = '''------ info of %s------
Name:%s
Age:%d
Job:%s
Salary:%d
''' %(user,user,age,job,salary)
print (info) |
9933b909b17caca45a0f7d896ad24a71a65fb62c | casc1990/python-s14 | /python基础教程/函数.py | 597 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#函数文档
def square(x):
'Calculates the square of the number x.'
return x*x
a = square(5)
print (a) #25
print (square.__doc__) #Calculates the square of the number x.
print (help(square)) #help函数也可以看到帮助信息
def test():
print ('this is printed')
return
pr... |
204ccec163eb6f92aa6795bf05dc73bd38492035 | casc1990/python-s14 | /python基础教程/条件-循环.py | 7,049 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:pengbo
__date__ = '2017/7/4 22:24'
print ('Age:',42) #输出 Age: 42
print ('Hello',',','Mr','Gumby' ) #输出 Hello , Mr Gumby
#print时 ',' 会被替换成空格
import os
import sys,time
from math import sqrt
from math import isclose,isinf
from math import *
import math as foobar
from ... |
fa898219f1414bd65930f10322df0b10b5a9f164 | casc1990/python-s14 | /day2/字符串.py | 3,939 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:pengbo
name = 'my \tname is Mr Peng'
name2 = 'hello! {name},your age is {year}'
msg = '我爱北京天安门'
print (name.capitalize()) #第一个单词的首字母大写
print (name.title()) #所有单词的首字母大写
print (name.casefold()) #将字符串所有字符转换成小写
print (name.center(50,'*')) #字符串总共要占50字符,不够用修饰符左... |
fe7c7273876053fe23592bcb8e9f837ea53b1e7d | casc1990/python-s14 | /day2/列表.py | 3,256 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:pengbo
name = ['zhangsan','lisi','wangwu','pb','liuhaoran','huyuedong','zhoushan']
print (name)
''''
#列表切片
print (name[0:]) #打印所有。类似 print(name)
print (name[-1]) #打印最后一个元素
print (name[2],name[4])
print (name[2:5]) #打印第3个元素到第5个元素(顾前不顾尾)
print (name[0:-1:2]) #从开头到... |
b89412c18142f97bde6576c0b1fa5897325adf5d | casc1990/python-s14 | /day7/异常处理-8.py | 4,242 | 4.03125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#错误
'''
for i in range(10)
print (i)
'''
print ('错误指程序在运行之前,python解释器检测到的语法错误')
#异常
lst = [1,2,3,4,5]
#print (lst[5])
print ('异常指程序运行中,遇到的内部错误')
'''
常见的异常如下:
NameError 尝试访问一个没有申明的变量
ZeroDivisionError 除数为 0
SyntaxError 语法错误
IndexError 索引超出序列范围
KeyError 请求一个不存在的字典关键字
IOEr... |
5a9b5db21437f4c7e1f979a64ed356fdec66c9d7 | wenlianggg/CBCodeSnippets | /snippets/liftsim/gui.py | 4,260 | 3.640625 | 4 | # Wen Liang Goh - https://github.com/wenlianggg
# 18 April 2020
# Not a very good attempt at simulating lift movements
from tkinter import Label, Button, Text, Checkbutton
class LiftSimGUI:
def __init__(self, master, numFloors, numLifts):
# Lift Logic
# --------------------
self.lifts = ... |
4387cc86fb1f132ef3af3fe8a26114d94378de09 | WhaleChen/task_lpthw | /ex15.py | 531 | 4.09375 | 4 | #-*- coding:utf-8 -*-
# "Hard coding" means putting some bit of information that should come from the user as a string directly in our source code.
from sys import argv
script, filename=argv
txt=open(filename)
# open file does not necessarily show the file,only making it alive.
print "Here's your file %r:" % filename
... |
1411e49b5b6020cc9cea71724cd253197898982a | Saninsusanin/general-graph-contest | /tasks/task2/task2.py | 362 | 3.6875 | 4 | from typing import List
def task2(p: str, t: str) -> List[int]:
"""
:p: Pattern of lowercase latin letters. May contain up to 10 wildcards (?) that representrs any letter.
:t: Text of lowercase latin letters.
:return: List of all positions in the text that are beginnings of substrings that match patte... |
6339d40839889e191b3ef8dae558cf3266b08ba8 | jamieboyd/neurophoto2018 | /code/simple_loop.py | 407 | 4.46875 | 4 | #! /usr/bin/python
#-*-coding: utf-8 -*-
"""
a simple for loop with conditionals
% is the modulus operator, giving the remainder of the
integer division of the left operand by the right operand.
If a number divides by two with no remainder it is even.
"""
for i in range (0,10,1):
if i % 2 == 1:
print (str ... |
b660cdda7070308927698667087d720c5627f2a1 | jm-wltr/Graphical-Projections | /PythonVersion.py | 6,997 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 11 14:22:08 2021
@author: jaimewalter
"""
## Visualize a cube that rotates in 3D, and its 2D orthographic projections. Made with linear transformations.
import numpy as np
import math
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3... |
c25ece7dae0b8583f7eaa954f76eee1b07d4b76d | suphiteksuti/Python-Classes-Functions-Roadmap-2 | /Function/exercise5.py | 1,293 | 3.984375 | 4 | def hotel_cost(days):
days = float(days*140)
print("Hotel Cost : ", end = ' ')
print(days)
return days
def plane_ride_cost(city):
if city == "Charlotte" :
city = 183
print("Plane Ride Cost : ", end = ' ')
print(city)
return city
elif city == "Tampa" :
... |
2cf48520a63f859fa43cb2d3f5dcf2e45782fe3d | pg2455/Coding4Fun | /take_zeros_to_end.py | 180 | 3.53125 | 4 | def zeros_inplace(A):
n = len(A)
i,j = 0,0
for j in range(n-1):
if A[j+1] != 0:
A[i], A[j+1] = A[j+1], A[i] #swapping
i+=1
return A
|
395541d35628503cb5f471b8a54fdaeb9408d196 | thewildsnorlax/Automated_Gmail_Virtual_Assistant | /fun_time.py | 905 | 3.6875 | 4 | def checkformat (string):
hours = ''
minutes = ''
seconds = ''
if(string[2:4]==' p'):
if(string[0:2]!='12'):
temp = int(string[0:2])+12
hours = str(temp)
minutes = '00'
seconds = '00'
else:
hours = string[0:2]
minutes = '00'
seconds = '00'
elif(string[2:4]==' a' ):
if(string[0:2]!='12'... |
86dec63990bd3ae55a023380af8ce0f38fcdf3e2 | CQcodes/MyFirstPythonProgram | /Main.py | 341 | 4.25 | 4 | import Fibonacci
import Check
# Driver Code
print("Program to print Fibonacci series upto 'n'th term.")
input = input("Enter value for 'n' : ")
if(Check.IsNumber(input)):
print("Printing fibonacci series upto '" + input + "' terms.")
Fibonacci.Print(int(input))
else:
print("Entered value is not a valid inte... |
a520701e1746c290c29b2b7376722c547c236441 | Ronyaco/OOP | /employee.py | 780 | 3.65625 | 4 |
from person import Person
class Employee(Person):
def __init__(self, name, age, address, phone, salary, office_address, office_phone):
"""self.name = name
self.age = age
self.address = address
self.phone = phone"""
"""Person.__init__(self, name, age, address, phone)"""
... |
4401a0492cb9d8ecf5d93063b4de3fc1527c8176 | tobspm/TSX | /src/trajectory_parser.py | 1,567 | 3.6875 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
#Modified date: 17/05/2016
#Method first wrote by Jim
#Nima
#
import numpy as np
import scipy as sp
import PyKEP as pk
from tools import motion
class TrajParser:
"""Class giving the location of the spacecraft at a certain eppoch.
This class reads the contents ... |
03dfac55e505ad8aa5acf34be80f068c2764d3cc | otaviocesar/jackcompiler | /code-generator/JackTokenizer.py | 7,242 | 4.09375 | 4 | #!/usr/bin/env python3
'''
- Design of a lexical analyzer
- Author: https://github.com/otaviocesar
- Author: https://github.com/otaviobelfort
'''
#Suporte para expressões regulares
import re
class JackTokenizer:
def __init__(self, raw_code):
# arquivo(.jack) com o script a ser compilado
self.file... |
caa6c8392c5898d4deb6f09c0eca43f2ecec3baf | moun3imy/morocovid | /read_stats.py | 6,449 | 3.59375 | 4 | # this script generates the general statistics about covid-19 for today
# run with python read_stats.py
# Using PyMuPDF
# https://github.com/pymupdf/PyMuPDF
# for Code Snippets : https://pymupdf.readthedocs.io/en/latest/tutorial.html
import fitz
import re
import datetime
from os import path
import utils
#TODO genera... |
e2f55129c04745dd81793e7d6867af117c988661 | rinogen/Struktur-Data | /Perkenalan List.py | 1,569 | 4.25 | 4 | # parctice with list in phyton and falsh back in first alpro 1
colors = ["red", "green" , "blue" , "yellow" ]
for i in range (len(colors)) :
print (colors[i])
print()
for i in range (len(colors) -1 , -1 , -1): # --> (panjangnya , sampai ke berapa , mundurnya berapa) #
print (colors[i])
print ()
print ()
pri... |
bef3fa04bba05ee7a00e93f8ac00ec0e9511bb67 | CDSteer/mini-adventure | /src/game.py | 1,327 | 3.78125 | 4 | import sys
import player
from player import *
import mob
from mob import *
import powers
from powers import *
import battle
from battle import *
"""Game Starts here"""
print "Welcome Player, start by entering your name:"
name = raw_input(">")
print "Hello there %s, \nYou are about to enter a cave of no return." % ... |
f398daec20f81cfd72bb8c083676787d15dd8ac5 | Doaxan/kt_test | /db.py | 2,699 | 3.84375 | 4 | import os
import sqlite3
def create_table():
try:
sqlite_connection = sqlite3.connect(os.getenv('DB_CONN', 'rates.db'))
sqlite_create_table_query = '''CREATE TABLE rates (
id INTEGER PRIMARY KEY,
created_at datetime,
... |
fc962624e347cf172197ab9074d483f694be92a5 | aungkhinemin89/Week03Assignment | /inventroy_app.py | 5,350 | 3.59375 | 4 | from db_connector import connect
cursor, mydb = connect()
def setup():
cursor.execute('create database if not exists inventory')
cursor.execute("use inventory")
cursor.execute(
"create table if not exists stocks(id int auto_increment, name text, sale_price int,purchase_price int,stock_in_qty int, ... |
81023a7a24c4ca4bacb24fbb0b0dd51e8159cbab | nperk7/My-Stuff | /NPES.py | 3,127 | 3.546875 | 4 | __author__ = 'naperkins'
import random
createBool = False
primeFile = None
yourName = None
yourUser = None
yourPass = None
yourNameNum = None
yourUserNum = None
yourPassNum = None
passList = []
end = None
def getFactors(num):
factors = ''
num = int(num)
for a in range(num):
a += ... |
bd2e9ef74ca83fe21c4e5380f2276a34bfb79da6 | Sadof/random_scripts | /euler project/num35.py | 183 | 3.640625 | 4 | import math
def prime(num):
for i in range(2,round(math.sqrt(num))):
print(num%i)
if num%i == 0:
return False
return True
for i in range(2,100):
if prime(i):
print(i) |
3e3f00dfb6c3a7402908eed1073ed7cf0d982b50 | ta-verma/codechef | /cpp/new.py | 1,357 | 3.625 | 4 | from PIL import Image, ImageDraw, ImageFont
#variables for image size
x1 = 612
y1 = 612
#my quote
sentence = "Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid. -Albert Einstein"
#choose a font
fnt = ImageFont.truetype('/Users/muthu... |
230660d8e2fbfb64e5b3beac4990f9ad152e1509 | ZhangHuiqi77/codinglearn | /Python/PythonDemo.py | 54,229 | 3.625 | 4 | #python范例代码
#温度转换TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
if TempStr[-1] in ['F', 'f']:
C = (eval(TempStr[0:-1]) - 32)/1.8
print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
F = 1.8*eval(TempStr[0:-1]) + 32
print("转换后的温度是{:.2f}F".format(F))
else:
print("输入格式错误")
-----------------------------... |
f402b5688e9fa717a5c6d4b07cac73bc7fa2f22f | FlavienGelineau/RL_algorithms | /Code_base/environments/EnvironmentGrid2Dwithkeys.py | 3,297 | 3.5625 | 4 | import random
from environments.Environment import Environment
import time
import numpy as np
class EnvironmentGrid2Dwithkeys(Environment):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
def __init__(self, params):
#print("we enter in EnvironmentGrid2Dwithkeys init")
self.n_x = int(params['nu... |
f193bf10635f1b1cc9f4f7aa0ae7a209e5f041db | Yashs744/Python-Programming-Workshop | /if_else Ex-3.py | 328 | 4.34375 | 4 | # Nested if-else
name = input('What is your name? ')
# There we can provide any name that we want to check with
if name.endswith('Sharma'):
if name.startswith('Mr.'):
print ('Hello,', name)
elif name.startswith('Mrs.'):
print ('Hello,', name)
else:
print ('Hello,', name)
else:
print ('Hello, St... |
012cc0af4adbfa714a4f311b729d89a9ba446d35 | Tagirijus/ledger-expenses | /general/date_helper.py | 1,213 | 4.1875 | 4 | import datetime
from dateutil.relativedelta import relativedelta
def calculateMonths(period_from, period_to):
"""Calculate the months from two given dates.."""
if period_from is False or period_to is False:
return 12
delta = relativedelta(period_to, period_from)
return abs((delta.years * 12) ... |
987b0e326d93e090116e5971c6591a13b029ee4f | heikalb/decision-mushroom | /get_mushroom_data.py | 2,456 | 3.78125 | 4 | """
Get and process dataset on mushrooms consisting of labels ('p (poisonous) vs.
e(edible)), and 22 nominal features. Fix missing values based on plurality.
Heikal Badrulhisham, 2019 <heikal93@gmail.com>
"""
from collections import Counter
def missing_values(example, funct):
"""
Tell what features are missi... |
bd076e7e1b1b05a2036c2b13ee2a66c81e5aa7a2 | yazidsupriadi/Memulai-Pemrograman-dengan-Python | /04 - Operator, Operands, dan Expressions/Main.py | 1,847 | 4.0625 | 4 | # Operator dan Expresi (Expressions)
# Operator matematika
print('Tambah'.center(20,'='))
a = 10 + 2
print('10 + 2 = ', a)
print('kurang'.center(20, '='))
a = 10 - 2
print('10 - 2 = ', a)
print('kali'.center(20,'='))
a = 10 * 2
print('10 x 2 = ', a)
print('bagi'.center(20,'='))
a = 10 / 2
print('10 / 2 = ', a)
pri... |
6ea626062ee959e71654f6434e4503e44d9f38c0 | cemrifki/sentiment-embeddings | /turk_dict.py | 3,477 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author: Cem Rıfkı Aydın
"""
import os
from collections import Counter
import lexical_interface
import preprocessing
TURK_DICT_PATH = os.path.join("Lexical_Resources", 'Turkish_Dictionary_Disamb')
WORD_SEP = "wordsep"
MEANING_MARK = "meaning"
turk_dict_word_freqs = Coun... |
039dd3727cdd229548d94108ee220efa4a5b4838 | mertdemirlicakmak/project_euler | /problem_5.py | 1,144 | 4.0625 | 4 | """"2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly
divisible by all of the numbers from 1 to 20?"""
# This function returns the smallest number that is divisible to
# 1 to num
def find_smallest_divisible(nu... |
b201a6f3f1a174e5b5e1a403d75c88a42a80a0db | BonnieThompson/cp1404pracs | /Prac02/ascaii table.py | 149 | 3.828125 | 4 | LOWER = 10
UPPER = 100
print("Enter a number ({}) - ({})".format(LOWER, UPPER))
for i in range(34, 127, 1):
print("{:<4d} {}".format(i, chr(i)))
|
e61d37fb0d3fc9c262e00bfa784b22ed91e2c546 | ABDM357/python_summary_knowledge_001 | /Day01-15 Python基础课程/Day01-15课程与项目/03多任务-线程/03-代码/04-创建线程的第二种方式-验证线程执行顺序.py | 684 | 3.828125 | 4 | import threading
import time
class myThread(threading.Thread):
"""1 集成Thread 2 实现其中run方法 3 创建该类的实例对象 4对象.start()启动创建和执行"""
def run(self):
for i in range(3):
time.sleep(1)
msg = "I'm " + self.name + ' @ ' + str(i) # name属性中保存的是当前线程的名字
print(msg)
if __name__ == '__m... |
511ff37f1cfcf073c97d12d96733429026d39991 | ABDM357/python_summary_knowledge_001 | /Day01-15 Python基础课程/Day01-15课程与项目/04多任务-进程/03-代码/05-使用Queue完成进程间通信.py | 1,015 | 3.65625 | 4 | import multiprocessing
import time
"""主进程往队列中放入屏幕上输入的数据 子进程从队列中取出数据并且打印出来"""
def proc_func(queue):
while True:
if queue.empty():
print("队列是空的 我稍后来取一次")
time.sleep(2)
else:
data = queue.get()
print("从队列中取出数据%s" % data)
time.sleep(2)
if ... |
dff7b2bc4004c56843ec2378b1522ef97e322927 | yosef8234/test | /hackerrank/python/sets/the-captains-room.py | 1,564 | 3.953125 | 4 | # -*- coding: utf-8 -*-
# Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
# One fine day, a finite number of tourists come to stay at the hotel.
# The tourists consist of:
# → A Captain.
# → An unknown group of families consisting of KK members per group where KK ≠ 1... |
9b55f10342373ef4438c08c0d93dd28a4ff267cc | yosef8234/test | /pfadsai/02-array-sequences/questions/array-pair-sum.py | 1,704 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Array Pair Sum
# Problem
# Given an integer array, output all the unique pairs that sum up to a specific value k.
# So the input:
# pair_sum([1,3,2,2],4)
# would return 2 pairs:
# (1,3)
# (2,2)
# NOTE: FOR TESTING PURPOSES< CHANGE YOUR FUNCTION SO IT OUTPUTS THE NUMBER OF PAIRS
# Solution
... |
52cb2a151344ef7bf3f8f5d10ff74b68fddbbbc7 | yosef8234/test | /pfadsai/07-searching-and-sorting/notes/implementation-of-insertion-sort.py | 872 | 3.984375 | 4 | # Implementation of Insertion Sort
# Insertion Sort builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
# Resources for Review
# Check out the resources below for a review of Insertion sort!
# Wiki... |
86c53c62cc53ee5007cc8efcedd4af5d99e0d486 | yosef8234/test | /python_essential_q/q1.py | 1,740 | 4.0625 | 4 | # Question 1
What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer
# Answer
Here are a few key points: - Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpr... |
b5a66fd0978895aaabb5cb93de5a7cfabd57ad8e | yosef8234/test | /python_simple_ex/ex28.py | 477 | 4.3125 | 4 | # Write a function find_longest_word() that takes a list of words and
# returns the length of the longest one.
# Use only higher order functions.
def find_longest_word(words):
'''
words: a list of words
returns: the length of the longest one
'''
return max(list(map(len, words)))
# test
print(fin... |
b787971db2b58732d63ea00aaac8ef233068b822 | yosef8234/test | /python_simple_ex/ex15.py | 443 | 4.25 | 4 | # Write a function find_longest_word() that takes a list of words and
# returns the length of the longest one.
def find_longest_word(words):
longest = ""
for word in words:
if len(word) >= len(longest):
longest = word
return longest
# test
print(find_longest_word(["i", "am", "python... |
9b22d6e5f777384cd3b88f9d44b7f2711346fc74 | yosef8234/test | /pfadsai/07-searching-and-sorting/notes/sequential-search.py | 1,522 | 4.375 | 4 | # Sequential Search
# Check out the video lecture for a full breakdown, in this Notebook all we do is implement Sequential Search for an Unordered List and an Ordered List.
def seq_search(arr,ele):
"""
General Sequential Search. Works on Unordered lists.
"""
# Start at position 0
pos = 0
# Targ... |
720f5fa949f49b1fa20d7c0ae08ae397fc6fc225 | yosef8234/test | /pfadsai/03-stacks-queues-and-deques/notes/implementation-of-stack.py | 1,537 | 4.21875 | 4 | # Implementation of Stack
# Stack Attributes and Methods
# Before we implement our own Stack class, let's review the properties and methods of a Stack.
# The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where ... |
5d1b9a089f9f4c0e6b8674dafffa486f4698cdb4 | yosef8234/test | /toptal/python-interview-questions/4.py | 1,150 | 4.5 | 4 | # Q:
# What will be the output of the code below in Python 2? Explain your answer.
# Also, how would the answer differ in Python 3 (assuming, of course, that the above print statements were converted to Python 3 syntax)?
def div1(x,y):
print "%s/%s = %s" % (x, y, x/y)
def div2(x,y):
print "%s//%s = %s" % (x, ... |
3c39888213a9dcc78c1c0a641b9ab70c87680c0a | yosef8234/test | /pfadsai/04-linked-lists/questions/linked-list-reversal.py | 2,228 | 4.46875 | 4 | # Problem
# Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return the new head of the list.
# You are given the example Linked List Node class:
class Node(object):
def __init__(self,value):
self.value = value
self.nextnode = None
#... |
e5559c70c6359152adbdb9ed7d83b869f917ae3c | yosef8234/test | /sorting-algorithms/3-cocktail_sort.py | 1,160 | 3.53125 | 4 | # Best Case Time: O(n)
# Worst Case Time: O(n^2)
# Average Case Time: O(n^2)
import numpy as np
# Sort while moving forward or backward
def partly_sort(array, i, forward):
n = len(array)
# Range of forward traverse
if forward == True:
interval = range(i, n-i-1)
# Range of backward traverse
... |
63af1d869f6bac7e550595494b2ff9bac93a0afe | yosef8234/test | /spbau/unix/cp/task1.py | 853 | 3.9375 | 4 | #!/usr/bin/python
A = int(raw_input("enter A:"))
B = int(raw_input("enter B:"))
C = int(raw_input("enter C:"))
AS = "A"
BS = "B"
if A > B:
temp = B
B = A
A = temp
temp = BS
BS = AS
AS = temp
def nextstep(AC, BC, path):
if (AC == 0):
AC = A
path.append(">"+AS)
return AC, BC
if (BC == 0):
BC = AC
AC... |
13a9ba16bf9cd24d84a9c3a647c568edb65d67b7 | yosef8234/test | /pfadsai/10-mock-interviews/social-network-company/phone-screen.py | 1,923 | 3.9375 | 4 | # Phone Screen - SOLUTION
# Problem
# Remove duplicate characters in a given string keeping only the first occurrences. For example, if the input is ‘tree traversal’ the output will be ‘tre avsl’.
# Requirements
# Complete this problem on a text editor that does not have syntax highlighting, such as a goolge doc!
# ... |
9041e5cb16518965f170e82bdac4929e93ab0273 | yosef8234/test | /hackerrank/30-days-of-code/day-24.py | 2,826 | 4.375 | 4 | # # -*- coding: utf-8 -*-
# Objective
# Check out the Tutorial tab for learning materials and an instructional video!
# Task
# A Node class is provided for you in the editor. A Node object has an integer data field, datadata, and a Node instance pointer, nextnext, pointing to another node (i.e.: the next node in a lis... |
adeda8cb5a30e9fa9aa12501024a6649ed85e4f6 | yosef8234/test | /python_simple_ex/ex30.py | 684 | 4 | 4 | # Represent a small bilingual lexicon as a Python dictionary in the following
# fashion
# {"merry":"god", "christmas":"jul", "and":"och", "happy":gott",
# "new":"nytt", "year":"år"}
# and use it to translate your Christmas cards from English into Swedish.
# Use the higher order function map() to write a function t... |
756868b809716f135bb1a27a9c35791e116a902a | yosef8234/test | /pfadsai/04-linked-lists/questions/implement-a-linked-list.py | 952 | 4.46875 | 4 | # Implement a Linked List - SOLUTION
# Problem Statement
# Implement a Linked List by using a Node class object. Show how you would implement a Singly Linked List and a Doubly Linked List!
# Solution
# Since this is asking the same thing as the implementation lectures, please refer to those video lectures and notes for... |
b57ace821bec902a08067f8df3c56bd839d76000 | yosef8234/test | /hackerrank/30-days-of-code/day-10.py | 1,106 | 3.9375 | 4 | # -*- coding: utf-8 -*-
# Objective
# Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
# Task
# Given a base-1010 integer, nn, convert it to binary (base-22). Then find and print the base-1010 integer denoting the maximum number of consecutive 11's... |
6eb333b658f76812126d0fefdb33a39e66f608bf | yosef8234/test | /pfadsai/10-mock-interviews/ride-share-company/on-site-question3.py | 2,427 | 4.3125 | 4 | # On-Site Question 3 - SOLUTION
# Problem
# Given a binary tree, check whether it’s a binary search tree or not.
# Requirements
# Use paper/pencil, do not code this in an IDE until you've done it manually
# Do not use built-in Python libraries to do this, but do mention them if you know about them
# Solution
# The f... |
3ce8c11c515ce118040f15fc43ea8f708ede2733 | yosef8234/test | /hackerrank/algorithms/graph-theory/permutation-game.py | 2,123 | 3.75 | 4 | # # -*- coding: utf-8 -*-
# Alice and Bob play the following game:
# They choose a permutation of the first NN numbers to begin with.
# They play alternately and Alice plays first.
# In a turn, they can remove any one remaining number from the permutation.
# The game ends when the remaining numbers form an increasing ... |
5ed90c779c6c76ed22e298cf24c021293bd86e57 | yosef8234/test | /toptal/python-interview-questions/8.py | 413 | 4.09375 | 4 | # Q:
# Given the following subclass of dictionary:
class DefaultDict(dict):
def __missing__(self, key):
return []
# Will the code below work? Why or why not?
d = DefaultDict()
d['florp'] = 127
# A:
# Yes, it will work. With this implementation of the DefaultDict class, whenever a key is missing, the instance... |
cf33a03b2d97e608f8d7699605e69c92a2aac8af | yosef8234/test | /python_data_structure/3-linkedlist.py | 1,376 | 4.03125 | 4 | class Node:
def __init__(self, item):
self.val = item
self.next = None
class LinkedList:
def __init__(self, item):
self.head = Node(item)
def add(self, item):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)
def... |
08460d10f8127d583e93ec2032ad3f0c66210bc2 | yosef8234/test | /spbau/unix/python/hw3/matrix.py | 3,620 | 3.546875 | 4 | #!/usr/bin/python
class abstractmatrix(object):
def __init__(self, rows, cols):
self._rows = rows
self._cols = cols
self._matrix = [[0 for c in xrange(cols)] for r in xrange(rows)]
def rows(self):
return self._rows
def cols(self):
return self._cols
def getitem(self, r, c):
return self._matrix[r][c]
... |
0d349d0708bdb56ce5da09f585eaf41d8f9952c3 | yosef8234/test | /python_essential_q/q8.py | 2,234 | 4.6875 | 5 | # Question 8
What does this stuff mean: *args, **kwargs? And why would we use it?
# Answer
# Use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we dont know how many keyword arguments wi... |
c4286b6053c22342360c5833b3f9c0e93fd366f4 | yosef8234/test | /coursera_algorithmic-toolbox/w2/01_introduction_starter_files/fibonacci/fib.py | 284 | 3.78125 | 4 | # Uses python3
def calc_fib(n):
fb = [0,1]
i = 2
while i <=n:
fb.append(fb[i-1]+fb[i-2])
i += 1
return fb[n]
# def calc_fib(n):
# if (n <= 1):
# return n
# return calc_fib(n - 1) + calc_fib(n - 2)
n = int(input())
print(calc_fib(n))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.