blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4e1476ca90033beb5ddb1c719769705c3182ce20 | greenelab/simulate-groups | /simulate_groups.py | 8,461 | 3.578125 | 4 | import random
import contextlib
import itertools as it
import numpy as np
BETA_NOISE_SCALE = 0.1
def simulate_ll(n,
p,
uncorr_frac,
num_groups,
prev_betas=None,
prev_groups=None,
group_sparsity=0.5,
seed=... |
e26d17c3c75d7f9dac2cce20080005bfcdf81353 | OtsuboRyuto/LMS | /docker-python/cgi-bin/make_online_test_html_backup.py | 9,512 | 3.6875 | 4 | #!/usr/bin/python3.9
"""
ver 1.02 12/20
What's new
ディレクトリを作成しファイルをテストごとに分けて保存できるようになった.
整合性チェックに永遠と成功できない場合->強制的にssを取らせるシステムを入れてそれをもとに採点する。 →データ送信機構は未実装
Improvement for problem
テストごとにHTMLを変更できるように、出力先を変更できるようにする.
->してもいいが、しない方が使いやすい気もする
->結局テストは同じところでやるので、ページを変えるとユーザーも混乱しやすい。
->あって損はないかもしれないが実装するメリットがあまりない
->ssの禁止... |
b0ccc6f2c1eaa6fa974e360fa4b4ae44da2cb605 | arita37/mystic | /examples2/olympic.py | 3,424 | 3.875 | 4 | #!/usr/bin/env python
#
# Problem definition:
# Example in google/or-tools
# https://github.com/google/or-tools/blob/master/examples/python/olympic.py
# with Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com
# and disclamer as stated at the above reference link.
#
# Author: Mike McKerns (mmckerns @caltech and @u... |
695c18d8e2fb09061dd245dfc150738553faa665 | arita37/mystic | /mystic/penalty.py | 17,518 | 3.765625 | 4 | #!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Author: Alta Fang (altafang @caltech and alta @princeton)
# Copyright (c) 1997-2016 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project... |
82bcb9cd8e35d1abf14e48bcf2a6ad706a33b997 | SeoJinhye/diceduel | /diceduel.py | 955 | 3.6875 | 4 | import random
import pygame
from pygame import mixer
P1 = random.randrange(1,6)
P2 = random.randrange(1,6)
P1win = 0
P2win = 0
mixer.init()
s = mixer.Sound('bgm.wav')
Start = raw_input("write start to start the game")
if(Start == "start"):
s.play()
while(P1win != 3 or P2win != 3):
print("P1 got:" + str(P1) + " P2... |
67172136301a865addc97d99a9d65798d62507d5 | SeoJinhye/diceduel | /practice/number.py | 195 | 3.75 | 4 | #number = raw_input("give me number")
#number = int(number)
#number += 5
#print(number)
#number = type(number)
#print(number)
from random import randint
mynumber = randint(1,6)
print (mynumber) |
2a9768c0349e912d6c145c6a54018ba20b8672e1 | srv7197/python-first | /mergeSort.py | 714 | 3.75 | 4 | listA= list(map(int,input().split()))
def merge(list1, list2):
c=[]
m=len(list1)
n=len(list2)
i=0
j=0
for _ in range(m+n):
if i==m:
c.extend(list2[j:])
break
elif j==n:
c.extend(list1[i:])
break
elif list1[i]... |
4e1ff3356d89126270208dcc782e76efe7779577 | Kevin3099/PRACTICAL-PI | /gpio_python_code/6_morsecode.py.save | 2,086 | 3.625 | 4 | #!/usr/bin/python
import os
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(22,GPIO.OUT)
loop_count = 0
#define a function called morsecode
def morsecode ():
GPIO.output(22,GPIO.HIGH)
sleep(.1)
GPIO.output(22,GPIO.LOW)
sleep(.1)
os.system("clear")
print "Morse Code"
loop_cou... |
6ccfaa4ae60ea4bcda41670b821725d252e4bb4d | Saumy26/CipherSchools_Assignment | /Searching & Sorting/ElementPositions.py | 796 | 3.703125 | 4 | def firstOccurrence(arr, x, n):
low = 0
high = n - 1
ans = -1
while (low <= high):
mid = (low + high)//2
if arr[mid] > x:
high = mid - 1
elif arr[mid] < x:
low = mid + 1
else:
ans = mid
high = mid - 1
return ans
def la... |
05415938d46cc70cfc398135dddc64fd376ddf22 | Saumy26/CipherSchools_Assignment | /Searching & Sorting/AlternativeSort.py | 331 | 3.875 | 4 | def alternativeSort(arr, n):
arr.sort()
i = 0
j = n-1
while (i < j):
print(arr[j], end =" ")
j = j - 1
print(arr[i], end =" ")
i = i + 1
if (n % 2 != 0):
print(arr[i])
arr = [1, 6, 9, 4, 3, 7, 8, 2]
n = len(arr)
alternativeSort... |
ed1b7d7a578291b5fafbbc0ff2a02e7954507c43 | Zamy97/Superhero-team | /superheroes-2.py | 11,789 | 3.8125 | 4 |
import random
class Ability:
def __init__(self, name, attack_strength):
self.name = name
self.attack_strength = attack_strength
def attack(self):
lowest_attack_val = self.attack_strength // 2
attack_value = random.randint(lowest_attack_val, self.attack_strength)
retu... |
fb646995f118bd50efe714f40788d36c1b7aee4f | salilathalye/cwa-dphitech-challenge-54 | /src/app.py | 4,417 | 3.578125 | 4 | # app.py
# Streamlit application for serving a Machine Learning Model
# Salil Athalye
import pathlib
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
from pycaret.regression import load_model, predict_model
# TODO: We could have a list of models saved in a JSON file, allow user to pick one
... |
1bf38a3019d8c789a4ea6da18c983be793beb2e7 | RavenKyu/baekjoon_algorithm | /test_1330.py | 911 | 3.78125 | 4 | """
문제
두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
입력
첫째 줄에 A와 B가 주어진다. A와 B는 공백 한 칸으로 구분되어져 있다.
출력
첫째 줄에 다음 세 가지 중 하나를 출력한다.
A가 B보다 큰 경우에는 '>'를 출력한다.
A가 B보다 작은 경우에는 '<'를 출력한다.
A와 B가 같은 경우에는 '=='를 출력한다.
제한
-10,000 ≤ A, B ≤ 10,000
"""
def _input():
a, b = map(int, input().split())
return a... |
429e71589c799e2566f0c0661ef103341ca9d306 | gurupratap-matharu/ta-te-ti | /tateti.py | 4,263 | 4.3125 | 4 |
#!/usr/bin/python3
# Simple TicTacToe game in Python - EAO
import random
import sys
import time
board=[i for i in range(0,9)]
# Corners, Center and Others, respectively
moves=((1,7,3,9),(5,),(2,4,6,8))
# Winner combinations
winning_combinations = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
de... |
0b4382a76134f958925439d728e0c373613aeb9a | HugoTien/ML_Backup | /ML_A-Z/Machine Learning A-Z Chinese Template Folder/Part 2 - Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression - Hugo.py | 3,778 | 3.78125 | 4 | # Multiple Linear Regression
################################################
###### Data Preprocessing Template #############
################################################
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv(... |
f69f2ea6f5ade12161e31c3bb4c23bb817d0c645 | sonalinegi/Training-With-Acadview | /assign7.py | 1,215 | 4 | 4 | #Create a function to calculate the area of a circle by taking radius from user.
rad=float(input("enter the radius:"))
def area(radius) :
radius= 3.14*rad*rad
print("area of circle is:%d"%(radius))
print(area(rad))
#Write a function “perfect()” that determines if parameter number is a perfect number.
def perfec... |
e416b2b621cfa2619bc83d37d1b1c6ac65ab143f | sonalinegi/Training-With-Acadview | /assign3.py | 920 | 4.15625 | 4 | #question no 1
list=[]
f=int(input("1st ele:"))
s=int(input("2nd ele:"))
t=input('3rd ele:')
list.append([f,s,t])
print(list)
#question no 2)
list.append(['google','apple','facebook','microsoft','tesla'])
print(list)
#question no 3
a=[1,2,1,4,2,3,2]
print(a)
print(a.count(1))
print(a.count(2))
#question no 4
no=[1,2,... |
266a871837d09944d9f22d150877143c54785f44 | emmanuelthegeek/URL-shortener | /URL shortner.py | 763 | 3.78125 | 4 | #import urllib and requests libraries
import urllib
import requests
#Insert your API key generated from cuttly API page
api_key = 'insert api key here'
#Enter the link you want to shorten
url = urllib.parse.quote('insert url you want to shorten')
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={u... |
c28514c93ba41fbf2bddae86c9913f28cd028338 | sameeha21-meet/meet2019y1lab6 | /maths_plots.py | 138 | 3.703125 | 4 | import turtle
result=[]
for count in range(1,n):
if count %3==0:
result.append("Fizz")
else:
result.append(count)
|
0bceb17ff3348434ef2869ed669d781d52b03876 | yanyanrunninggithub/Leetcode-Python | /BST.py | 3,585 | 3.734375 | 4 | #108. Convert Sorted Array to Binary Search Tree: using bs to create the BST
class Solution:
def BSHelper(self,nums:List[int], start:int,end:int) -> TreeNode:
if start > end:
return None
mid = start+(end-start)//2
root = TreeNode(nums[mid]) #create new node
root.left = s... |
fd821e8dd1819345979293f1c56a8908e57fe633 | AmanKamboj09/Python | /List Comprehension/set_comp.py | 53 | 3.5 | 4 | sq = {x**2 for x in [1,2,3,2,5,4,6,4,3,2]}
print(sq) |
4a80bb9c513e227cb8ab66c2e3c5a2f08ea8941f | AmanKamboj09/Python | /List/List 3.py | 599 | 3.609375 | 4 | numList = [5, 15, 35, 8, 98]
alphabets =['a','b','c','d','e','f','g','h']
fruits =["Apple","Banana", "Grapess", "Mango"]
MixList = [25, "Amit", 'A',5.6]
print(alphabets[::4])
# print(MixList)
# print(fruits)
# for item in fruits:
# print(item)
#Append an item
# fruits.append("Orange")
# fruits.insert(2... |
15d07cc1c03aaac2332aabdd53cc876406f6be18 | AmanKamboj09/Python | /List/List9.py | 116 | 3.65625 | 4 | row = 1
while row <= 5:
val = 5 - row
print(" "*val , end = '')
val = 2 * row - 1
print("*"*val)
row += 1 |
3339069f9749846dd9a9ca0fe6811258daa4854c | BleShi/PythonLearning-CollegeCourse | /Week 6/12-求平均再输出大于.py | 566 | 4.0625 | 4 | # 设计一个函数,接收任意多个数,返回一系列值,其中第一个值为所有参数的平均值, 后面是所有大于平均值的数值。然后用不同的例子调用三次。
def average_above(*numbers):
sum = 0
above = []
length = len(numbers)
for index in range(0,length):
sum+=numbers[index]
average = sum/length
for num in numbers:
if num > average:
above.append(num)... |
a2511ab16c5f2d91bd43a385fbe6efca5450d00a | BleShi/PythonLearning-CollegeCourse | /Week 6/9-阶乘的和.py | 332 | 3.75 | 4 | # 求1!+2!+3!+4!+……+n! ,分别计算到n=10和20的和
sum10 = 0
sum20 = 0
calc = 1
n10 = 10
n20 = 20
for i in range (1,n10+1):
calc = calc * i
sum10 = sum10 +calc
for i in range (1,n20+1):
calc = calc * i
sum20 = sum20 +calc
print("n=10的和为:",sum10)
print("n=10和20的和为:", sum20) |
f8460081faa0301311e9ea54978b650b74933b26 | BleShi/PythonLearning-CollegeCourse | /Unit 4/4-求一元二次方程的根.py | 718 | 3.671875 | 4 | # 求一元二次方程的根
import math
a=float(input("请输入一元二次方程的二次系数:"))
b=float(input("请输入方程的一次系数:"))
c=float(input("请输入方程的常数项:"))
if a==0:
print("方程二次系数不能为0!")
else:
delta=b*b-4*a*c
x=-b/(2*a)
if delta==0:
print("方程有唯一解,即X=",x)
elif delta>0:
x1=x-math.sqrt(delta)/(2*a)
x2=x-math.sqrt(delt... |
4d3caa3df4c3d88a3f1d0c1cac166b0eb4179e00 | danielkaifeng/guess_game | /guess_number.py | 1,133 | 3.59375 | 4 | # coding=utf-8
import random
def generate_key():
key_list = []
while True:
a = random.randint(0,9)
if a not in key_list: key_list.append(a)
if len(key_list) == 5: break
return ''.join([str(x) for x in key_list])
def check_position(guess,key):
count = 0
for i in range(len(g)):
if guess[i] in key[i]: coun... |
d68d0070362b165c06c64e5ea2d0c30bacf32953 | jwday/orbitSim | /orbit_decay_num_sim_v5.py | 11,123 | 3.5 | 4 | # Numerical Integration of Polar Eqns. of Motion for Orbital Motion
# =============================================================================
# Polar Equations of Motion
# =============================================================================
# r'' = r(th')^2 - mu/r^2 # Radial acceleration
# ... |
3f6130711fb57b406fc1ef17b04e711be6a0687d | PrzemyslavJ/pp1 | /05-ModularProgramming/5.8.py | 614 | 3.625 | 4 | import turtle
def drawSquare(x,y,n):
Square = turtle.Turtle()
Square.penup()
Square.setposition(x,y)
Square.pendown()
for i in range(4):
Square.forward(n)
Square.setheading(270-i*90)
def drawStructure(x,y,n):
Structure = turtle.Turtle()
for i in range(4):
for j in r... |
158ff82f373dee6adbd0a41fb4d558dac95dc2cd | PrzemyslavJ/pp1 | /02-ControlStructures/2_AFTER_CLASS/2CA_28.py | 310 | 3.625 | 4 | import sys
a = int(input("Podaj wymiar pionowy a: "))
b = int(input("Podaj wymiar poziomy b: "))
for x in range(a):
for y in range(b):
if((x>0 and x <a-1) and (y>0 and y<b-1)):
sys.stdout.write(" ")
else:
sys.stdout.write("*")
print("")
|
f4b45831bbe611af39fd58c1fa3e50653ef0d361 | PrzemyslavJ/pp1 | /06-ClassesAndObjects/6.16.py | 891 | 3.515625 | 4 | class Book():
def __init__(self,tytul,autor,liczbastron):
self.tytul = tytul
self.autor = autor
self.liczbastron = liczbastron
self.open = False
self.nrstrony = 0
def Open(self):
self.open = True
self.nrstrony = 1
def Close(self):
... |
05a2e468718c69cdef071e47182693243ddfeaaf | jurbanski/week5 | /machine.py | 1,303 | 3.84375 | 4 | """ machine class module """
# 2015-02-07
# Joseph Urbanski
# MPCS 50101
class CoinDispenser():
""" CoinDispenser class contains:
- A list of *coins* it will dispense.
- An amount of *change* (>100) given as a list of coins.
"""
coins = [25, 10, 5, 1]
change = [0, 0, 0, 0]
def make... |
582c357cd909fb4f7a0ca15a32d033af6f5dcec6 | azeemchaudhrry/30DaysofPython | /Day1/hellopython.py | 487 | 3.625 | 4 | # 30 days of python
# Day 1
print(2 + 3)
print(3 - 2)
print(-2 - 3)
print(2 * 3)
print(3 / 2)
print(3 % 2)
print(3 // 2)
print(3 ** 2)
print('Hafiz Muhammad')
print('Azeem')
print('Pakistan -> United Arab Emirates -> oo')
print('30 days python')
print(type(10))
print(type(9.8))
print(type(3.14))
print(type(4-4j))
pr... |
458c89d7d0d59471abf3b6f766ae888c4e3ecea7 | Jean-Parra/LaboratorioVCSRemoto | /Pre-InformeLab10_Jean_Parra.py | 1,498 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 18:16:40 2020
@author: Jean Parra
"""
# ------------- Funciones ------------- #
#%%
import numpy as np
def Kellogs():
Años = np.array([27834,23789,30189,30967,32501,
32701,31665,17155,4614,834])
return Años
def mediapr... |
1535d1a9bc67e2e8f124d0533aec22269e189ba7 | soultalker/workon | /TuLingXueYuan/猜数字.py | 673 | 3.671875 | 4 | #给用户三次机会,猜想程序生成的一个100以内随机数字。每次猜想后会给出提示。当机会用尽后提示失败
import random as r
secret = r.randint(1, 100)
times = 10
while times:
number = input('请输入1-100的数字(0直接退出):')
if number.isdigit():
temp = int(number)
if temp == 0:
break
elif temp > secret:
print('输入数字过大。')
e... |
8f15703abc07e82c03e459be8c468ff2af18840d | soultalker/workon | /TuLingXueYuan/九九乘法表.py | 114 | 3.765625 | 4 | #九九乘法表
for i in range(1, 10):
for k in range(1, i+1):
print(k*i, end=' ')
print('\r\n')
|
41a4374fe97b39558313bc5fdfcf8d37a84a5c2a | Deluxe247/hello-world | /Test.py | 77 | 3.609375 | 4 | x = 4
y = 5
z = x + y
print(z)
v1 = input("Enter data: ")
print(v1)
|
5b832984f4276b7259a60f2c775a69ee8a21a671 | solomonli/PycharmProjects | /Idioms/lesson4/task1/task.py | 490 | 4.125 | 4 | # Dictionary loops
prices = {'bread': 2, 'water':1, 'beer':2.5, 'apples':0.6 }
print( "goods:", list( prices.keys() ) )
average = sum(prices.values()) / len( prices)
print( "average price:", average)
# simple loop
print("\n Prices of Goods:")
for food in prices:
print( food, "costs", prices[food] )
# pri... |
35f052637f784fd9360ddcb643ebac78f329b525 | solomonli/PycharmProjects | /classes/soloLearn.py | 10,772 | 4.4375 | 4 | class Animal:
def __init__(self, name, color): # technically, it's called 'instantiation'
self.name = name
self.color = color
class Cat(Animal): # inherit from the superclass Animal
def purr(self):
print("Purr...")
felix = Cat("ginger", 4)
rover = Cat("dog-colored", 4)
stumpy = Cat... |
c6a31c9aa08e85f76c3de63129d8ed73c6e916fc | solomonli/PycharmProjects | /GooglePython/hello.py | 1,573 | 4.03125 | 4 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from t... |
b2742ee81dbec2389942c114fd1a4b58f8feb051 | solomonli/PycharmProjects | /Stepik_Adaptive_Python/Purchase pies.py | 458 | 4.03125 | 4 | '''print("Please enter the dollar (integer): ", end='')
d = int(input())
print("Please enter the cent (integer): ", end='')
c = int(input())
print("Please enter the pizza units (integer): ", end='')
N = int(input())
D = d*N
C = c*N
if C >= 100:
D += C // 100
C %= 100
print(D, C)'''
a, b, n = [int(input()) f... |
0f07ca35ddfd6c13fe4c47bffce49437e148777e | solomonli/PycharmProjects | /The Absolute Basics/Chapter 3/Section 2.py | 610 | 4.09375 | 4 | __author__ = 'phil'
# Getting the integers ready
a = 56
b = 74
# Printing them both in one combined print() statement
print("The value of a is %d, and the value of b is %d" % (a, b))
# More complex patient example
# Variables
patientName = "Fred"
patientDOB = "20/04/1982"
patientNum = 187314973495
# Printing
print("P... |
5cb44013a84eae002a88df7e54c33057837c264f | solomonli/PycharmProjects | /The Absolute Basics/Chapter 4/Section 1.py | 1,702 | 4.3125 | 4 | __author__ = 'phil'
# Create a variable with input()
guess = input("Guess my favourite number: ")
# Now some basic logic
if guess == "7":
print("You got it!")
# Variable names changed slightly to allow them to all be in the same file
guess2 = input("Guess my favourite number: ")
# Same as before
if guess2 == "7":... |
8622e7ab981114a84595e6e363e90a05911f8704 | solomonli/PycharmProjects | /CodingBat/Logic-2/make_chocolate.py | 913 | 4.0625 | 4 | def make_chocolate(small, big, goal):
"""
We want make a package of goal kilos of chocolate.
We have small bars (1 kilo each) and big bars (5 kilos each).
Return the number of small bars to use, assuming we always use big bars before small bars.
Return -1 if it can't be done.
make_chocolate(4, ... |
023163a3a1a272d78e387ddf45a583e066f600ca | solomonli/PycharmProjects | /Stepik_Adaptive_Python/adaptive-python-en-master/Step 096 Frequency of number.py | 348 | 3.59375 | 4 | n = int(input())
numbers = input().split()
counts = {i: 0 for i in set(numbers)}
# print("Initial Counts = {}".format(counts))
# Initialized frequency count
for item in numbers:
counts[item] += 1
# print("Final Counts = {}".format(counts))
# frequency dict
print(1 if max(counts.values()) > n / 2 else 0)
'''
Sa... |
52995ca2ec9667eeab98be5b0d210c2dc975f186 | solomonli/PycharmProjects | /CodingBat/Logic-1/date_fashion.py | 926 | 4.28125 | 4 | def date_fashion(you, date):
"""
You and your date are trying to get a table at a restaurant.
The parameter "you" is the stylishness of your clothes,
in the range 0..10, and "date" is the stylishness of your date's clothes.
The result getting the table is encoded as an int value with
0=no, 1=may... |
dbe7f9994c4c03a8e0dd8e432cb5ea78e03809aa | solomonli/PycharmProjects | /Stanford/kevins_daughter/main.py | 918 | 3.6875 | 4 | # Find at least 40 sets of five distinct unit fractions that add up to 1.
# An example (a set of three items) would be 1/2 + 1/3 + 1/6 = 1.
# A great math puzzle from Kevin's daughter
import time
import itertools
class Solution(object):
def five_unit_fraction(self):
tic = time.time()
a = range... |
75444055494eb97e0855f29c4ccbfc9788b19484 | solomonli/PycharmProjects | /Stepik_Adaptive_Python/Leap.py | 256 | 3.90625 | 4 | print("Please enter a year: ", end='')
Y = int(input())
if Y % 4 == 0 and Y % 100 != 0 or Y % 400 == 0:
print("Leap")
else:
print("Regular")
'''
n = int(input())
print('Leap' if (n % 4 == 0 and n % 100 != 0) or (n % 400 == 0) else 'Regular')
'''
|
74a8f252bcbbe0d5761031573e942a55bd7e804a | solomonli/PycharmProjects | /CodingBat/String-2/cat_dog.py | 950 | 3.890625 | 4 | def cat_dog(str):
"""
Return True if the string "cat" and "dog" appear
the same number of times in the given string.
cat_dog('catdog') → True
cat_dog('catcat') → False
cat_dog('1cat1cadodog') → True
:param str: str
:return: boolean
"""
count_cat = 0
count_dog = 0
for i... |
1019c73f97a991b6fe9b60aef1f44dc40310deae | solomonli/PycharmProjects | /CodingBat/Logic-1/cigar_party.py | 772 | 4.09375 | 4 | def cigar_party(cigars, is_weekend):
"""
When squirrels get together for a party, they like to have cigars.
A squirrel party is successful when the number of cigars is between 40
and 60, inclusive. Unless it is the weekend,
in which case there is no upper bound on the number of cigars.
Return Tr... |
4a6f6a9d0374080901661e5882a120eeb03e8fb0 | solomonli/PycharmProjects | /CodingBat/Warmup-1/diff21.py | 377 | 4.03125 | 4 | def diff21(n):
"""
Given an int n, return the absolute difference between n and 21,
except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0
"""
distance = abs(n - 21)
if n > 21:
distance *= 2
return distance
pri... |
139bf2447eb5da09e7c91c5ffe3031d52919f338 | solomonli/PycharmProjects | /Idioms/lesson3/task1/task.py | 101 | 3.5 | 4 | # List loops
finances = [10, -5, 15]
for i in range(len(finances)):
print( finances[i] )
|
567971ab94c8ecf680ecd47bb5265e0e458b8d3a | solomonli/PycharmProjects | /Stepik_Adaptive_Python/adaptive-python-en-master/Step 086 Containing the words.py | 307 | 3.640625 | 4 | # import pprint
words = input().split()
lengths = list(map(len, words))
d = {l: lengths.count(l) for l in sorted(set(lengths))}
for length, amount in d.items():
print('{}: {}'.format(length, amount))
# pprint.pprint(d)
# I didn't get desired result with pprint; maybe I can refer to the Jupyter note
|
3441064e8fa0d14d3bd5e01873d2e48ce77e50bc | gitryder/ctci-python | /my_solutions/ch1/is_unique.py | 353 | 4.21875 | 4 | str = input("Enter a string:\n")
checklist = []
is_unique = True
for char1 in str:
for char2 in checklist:
if char1 == char2:
is_unique = False
break
if is_unique:
checklist.append(char1)
else:
print(f"{str} is not unique!")
break
if is_uniqu... |
dc953265e0b52beb1df71ce0dc09f0b9ac2fb1b8 | rohitvish30/CSE-587-Big-Data-Processing-with-Hadoop | /Part 1/reducer1.py | 811 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import sys
word_count_dict={}
for words in sys.stdin:# reading the mapper input
words = words.strip() #removing the trailing space if any
word,count=words.split('\t',1) #splitting the input into word and count
try:
count=int(count) #making the coun... |
5ebe5c3b6a5a6d383b760a4caf948dfd24f2cfb4 | tom-dell/Notes | /ConditionalTestingNumbers.py | 316 | 3.75 | 4 | numbers = [1, 2, 3]
num = int(input('enter a number '))
if num in numbers:
print('in list')
elif num < 10:
print('you are close')
else:
print('number not in list, you are way off')
##########################################
# Matts testing
##########################################
try:
'yeet'
|
ec1df1db472cfbe6e7af8c9c6ec9cb665068e156 | skywithlight/Algorithms | /HackerRank/Practice/Implementation/Extra_Long_Factorials.cpp | 232 | 3.609375 | 4 | #!/bin/python
import sys
def extraLongFactorials(n):
ans = 1
i = 2
for i in range (i, n + 1):
ans = ans * i
print ans
if __name__ == "__main__":
n = int(raw_input().strip())
extraLongFactorials(n)
|
6cdf2d282276d47f30e35941ff94c62e215998ad | semg101/2-IBM-Deep-Learning-fundamentals-with-Keras | /keras_regression.py | 2,461 | 4.15625 | 4 | #1. Download and Clean Dataset 2. Import Keras 3. Build a Neural Network 4. Train and Test the Network
#Download and Clean Dataset
#Let's start by importing the pandas and the Numpy libraries.
import pandas as pd
import numpy as np
#Let's download the data and read it into a pandas dataframe.-------------------------... |
79902bc48276ce1766a333a6a19d57b546168d95 | oregonstatetm/Python_Problems | /palindromeNumber.py | 960 | 4.0625 | 4 | Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is palindrome while 123 is not.
class Solution(object):
def isPalindrome(self, x):
if(x<0): #Negative numbers are not palendromes
return False
... |
2de58357ffa2d96f8cbdcca65b1b7a7fbf1315e8 | abdullahelnajjar/FirstPythonProject | /Python Exercises/reading_files2.py | 474 | 3.953125 | 4 | # Open the file
with open("mydata2.txt", encoding="utf-8") as myFile:
lineNum = 1
# We'll use a while loop that loops until the data
# read is empty
while True:
line = myFile.readline()
# line is empty so exit
if not line:
break
print('Line', lineNum)
... |
f6ad069828114bc6cf94383020653f504b916d87 | abdullahelnajjar/FirstPythonProject | /Python Exercises/List Less Than Ten.py | 220 | 3.71875 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 0]
b=[]
key = input('Please input key number: ')
for index in range(len(a)):
if a[index] < int(key):
b.append(a[index])
print(b)
print([aa for aa in a if aa<5]) |
288549a9c01d638bdaeddbb83be00407eb63069e | abdullahelnajjar/FirstPythonProject | /Python Exercises/Reverse Word Order.py | 317 | 4.0625 | 4 | def reverse_sentence(sent):
new_list = sent.split()
return ' '.join([new_list[itr] for itr in range(len(new_list) - 1, -1, -1)])
# Another Solution
def reverseWord(word):
return ' '.join(word.split()[::-1]
)
print(reverse_sentence(input('Please enter sentence to be reversed: '))) |
01268acebbc1bd9f46e18bebe619fae5841573ef | somangshu-create/somangshu-work | /project 10.py | 326 | 3.640625 | 4 | fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
count=0
fh = open(fname)
for line in fh:
line.rstrip()
if line.startswith('From'):
if line.startswith('From:'):
continue
x=line.split()
print(x[1])
count=count+1
print(count)
... |
3e7c2877fab7db8bdbe1ec99d8dfbd4c1c677056 | danrichmond/web-scraper | /webscraper.py | 758 | 3.921875 | 4 | import urllib2
from bs4 import BeautifulSoup
# Change this URL to scrape you website! This lets Beautiful Soup know
# what website your want to scrape
quote_page = 'Enter your URL here.' # Enter your URL on this line
page = urllib2.urlopen(quote_page)
# This extracts the html from the website
soup = BeautifulSoup(pag... |
bbfee56c6621000ca568e7ebb2b23f5479e8e42f | rongjingli/VisualStudio | /pythonFile/demo.py | 1,270 | 4.03125 | 4 | print("hello world")
print(2333)
print(2.333)
print(None)
print(True, False)
print(())
print([])
print({})
name = "李四"
print("你好, {}".format(name))
# 单行注释
"""
多行注释
"""
num = ((3+2)*100-99)/3.2
print(num)
"""
name1 = input("请输入你的姓名: ")
print("这是input获取的值:", name1)
num1 = float(input("请输入你的第一个数: "))
num2 = float(inp... |
1989c034f75dbf5c0d433ce3f639516e330d10d5 | HuguesDelamare/Centre-Echecs | /controller/player_controller.py | 4,689 | 3.53125 | 4 | import view
import model
import datetime
import string
class PlayerController(object):
# Function to set the birthdate of the new player
@classmethod
def set_player_birthdate(cls):
# List of valid date format
format_list = ["%d-%m-%Y", "%d/%m/%Y", "%d %m %Y"]
while True:
... |
7e89e42c9c00eec44afd85543f745eb56bb7b4fe | tinasoni77/tinasoni77 | /movies.py | 980 | 4.15625 | 4 | import sqlite3
connection=sqlite3.connect('Movies.db')
cursor=connection.cursor()
command1=""" CREATE TABLE IF NOT EXISTS Movies(name TEXT PRIMARY KEY,actor TEXT,actress TEXT, director TEXT,year INTEGER) """
cursor.execute(command1)
cursor.execute(" INSERT INTO Movies VALUES ('Holiday','Akshay Kumar','So... |
8c9bf056f9622e95364dcdf45aec5a37ab20fab4 | cheukwing/ascii-box | /box.py | 1,176 | 4.15625 | 4 | import argparse
def box(w: int, h: int) -> str:
"""Returns a string representation of a box, with the given width and height.
e.g. box(4, 4)
┌--┐
| |
| |
└--┘
"""
# The minimum we can return is a box which is just corners, there are no
# other legal characters which would be su... |
d12a8bfb26f69be8fb058327cd841ad16bc35687 | crypticsy/Toolbox | /Pathfinding/dijkstra's_shortest_path.py | 1,040 | 3.515625 | 4 | class dijkstra_shortest_path():
graph, distance, final_dist = {},{},{} # attributes
def __init__(this, graph, distance): this.graph, this.distance = graph, distance
def findmin(this,dict): return min(list(dict), key = lambda x:this.final_dist[x])
def find_path(this, start):
thi... |
dc33703a88fb9eac165937e71a230558e39b91b6 | troyAmlee/cs-module-project-algorithms | /single_number/single_number.py | 635 | 3.859375 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr):
# Your code here
output = []
for i in range(len(arr)):
for j in range(len(arr)):
if(i != j):
if ((arr[i] == arr[j])):
output.append(... |
1f0059ea05b3ab661d888dccd919b84b0c3e4473 | akyerr/Codewars-Examples | /order_of_brackets.py | 1,256 | 4.4375 | 4 | """
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => t... |
6984e50499e977257847467b242495d6f73b6e73 | akyerr/Codewars-Examples | /human_readable_format.py | 1,974 | 4.625 | 5 | '''
Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.
The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minute... |
319e1e7bce942f82237d1e56ed38e23b07680721 | jabuckle26/Directory-find-and-replace-Python- | /Directory-Find-and-Replace.py | 1,061 | 3.890625 | 4 | import os
################################################################################
############################### Functions ######################################
def recursiveReplace(my_base_dir,o,c):
folder_list = os.listdir(my_base_dir)
for item in folder_list:
new_name = item.replace(o, c)
... |
0fedc7c43d5fade2ffe46c14756b9d4f52ffddfa | seoyeon0413/Algorithm | /CodingTest/5-10 (DFS,BFS - 음료수 얼려 먹기).py | 1,398 | 3.5625 | 4 | # 1. 특정한 지점의 주변 상,하,좌,우를 살펴본 뒤에 주변 지점 중에서 값이 '0'이면서 아직 방문하지 않은 지점이 있다면 해당 지점을 방문한다.
# 2. 방문한 지점에서 다시 상,하,좌,우를 살펴보면서 방문을 다시 진행하면, 연결된 모든 지점을 방문할 수 있다.
# 3. 1~2번 과정을 모든 노드에 반복하며 방문하지 않은 지점의 수를 센다.
# 3.에서 방문하지 않은 지점이란, 코드 상에서 "if dfs(i, j) == True:"
n, m = map(int, input().split())
graph = []
for i in range(n):
graph... |
b7c334ca7e4fd399d5ad4e5ca2aeb6e172803a15 | mwnDK1402/4COSC00W-1 | /shiftcipher/__init__.py | 2,778 | 4.0625 | 4 | program_name = "Shift Cipher"
program_version = '0.2.0'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def print_version():
print(program_name + ' version ' + program_version)
def print_operation_prompt():
print("Input 'e' to start encoding")
print("Input 'd' to start decoding")
print("Input 'q' to quit")
... |
50a2cd022e09de3c3e8708ae7a68154b90c96e41 | matte6288/Game-of-Stick-AI- | /gameofstick.py | 4,125 | 3.796875 | 4 | import random
import turtle
sticks=20
bot1moves=[[1],[1,2]]
bot2moves=[[1],[1,2]]
player=True
bot1roundmoves=[]
bot2roundmoves=[]
tortellini = turtle.Turtle()
learningRounds=0
explaination=["Above is a visual of the player 1 AI learning","Numbers above each box represents the amount of sticks left in the game","The mor... |
405ad6db63d5d6196c27a8539df83b2b7151602e | Guirguis87/SmartDict | /RMC_Dic.py | 2,112 | 3.609375 | 4 | import json
from difflib import SequenceMatcher
from difflib import get_close_matches
data = json.load(open(r"D:\Courses - Trainings\Programming\Projects\Dict\data.json","r"))
while True:
print(" Welcome to RMC Soft for Engineering Solutions , Your dream became a code " + "\n")
user_input = input (" Please E... |
86e2c3656e378b39961f7f38d2c8233635276ace | Vish1203/Codes | /KNN_BreastCancer_1.py | 1,376 | 3.5 | 4 | import numpy as np
from sklearn import preprocessing, neighbors
from sklearn import model_selection
import pandas as pd
df = pd.read_csv('breast-cancer-wisconsin.data') #Reading the data file(csv) from local directory
df.replace('?', -99999, inplace=True)
#Replacing the ? (missing) values with -99999.
#We re... |
4f56ff1bbc69ec9e104ef5ed05336d70fb707425 | jkkim74/autoTrade_new | /project/step-4/test9.py | 2,004 | 4 | 4 | """
Présentation du module threading
http://docs.python.org/3.3/library/threading.html
"""
import time
import threading
class BankAccount():
def __init__(self, initial_money=0, owner='Anonymous'):
self.money = initial_money
self.owner = owner
# We will keep each write access to money in a... |
12ebff9127351880383916e47e85aac753b9051a | muhil77/Project-One | /prime_check.py | 314 | 4.1875 | 4 | # this function checks if a number is prime
def prime_checker(num):
flag = True
for divisor in range(2, num / 2):
if num % divisor ==0:
flag = False
return flag
return flag
number_to_check = int(raw_input("Enter number to check "))
print prime_checker(number_to_check)
|
b106c08b94dc7434cf5067a1b4b8696da3e480bc | philalexeev/pcs | /tuples.py | 1,002 | 4.09375 | 4 | # tuples
# tuples are immutable
tup = (1, 2, 3) # tuple sample
type(tup) # <class 'tuple'>
empty_tuple = ()
one_el_tuple = (1,)
# create tuple from any sequence type -> ('p', 'y', 't', 'h', 'o', 'n')
tup = tuple('python')
# methods
# length of the tuple
len(tup) # 3
tup[3] # h
# slicing
tup_slice = tup[:3]
p... |
10e406799040234d2a0cdd742b2b70a566f77729 | cryoyan/DeeplabforRS | /basic_src/timeTools.py | 2,234 | 3.703125 | 4 | #!/usr/bin/env python
# Filename: timeTools
"""
introduction: functions and classes to handle datetime
authors: Huang Lingcao
email:huanglingcao@gmail.com
add time: 29 December, 2020
"""
import os,sys
import basic_src.basic as basic
from datetime import datetime
from dateutil.parser import parse
import re
def get_... |
31d9d75a20d843c66b80f9c1e52bcda8682bbf1e | karades/SudokuSolver | /horizontal.py | 3,552 | 3.8125 | 4 | import pprint
import copy
def create_dummy_horizontal_line(dummy_board,row):
#create dummy list with possible values for the horizontal line
dummy_h_line = [0,0,0,0,0,0,0,0,0]
for column in range(9):
dummy_possible_numbers = dummy_board[row-1][column]
dummy_h_line[column]= copy.deepcopy(dum... |
97f0381ec8641ccbf8491ef95e5be4e7ef599568 | udacity/DSND_Term2 | /lessons/ObjectOrientedProgramming/JupyterNotebooks/5.OOP_code_inheritance_clothing/answer.py | 1,249 | 3.9375 | 4 | class Clothing:
def __init__(self, color, size, style, price):
self.color = color
self.size = size
self.style = style
self.price = price
def change_price(self, price):
self.price = price
def calculate_discount(self, discount):
return self.pr... |
864f207e140d341c4fe3f1e47bf1f106d4cd3ded | udacity/DSND_Term2 | /lessons/CRISP_DM/CatVar.py | 2,903 | 4.1875 | 4 | import pandas as pd
import numpy as np
from collections import defaultdict
import CatVarSolns as s
## Categorical Variables
# Question 1
def cat_df_check(cat_df):
'''
INPUT
cat_df - a pandas dataframe of only the categorical columns of df
Prints statement related to the correctness of the d... |
2b8eb17f1b9ced0e3fc0709ebf723b60ad9cb9a0 | udacity/DSND_Term2 | /lessons/CRISP_DM/solution1.py | 9,818 | 3.5625 | 4 | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
df = pd.read_csv('./survey_results_public.csv')
schema = pd.read_csv('./survey_results_schema.csv')
## A Look at the D... |
418f0dfd41e5f9d8ce286476e8b319abd9934263 | udacity/DSND_Term2 | /lessons/CRISP_DM/HowToBreakIntoTheField.py | 4,308 | 3.96875 | 4 | import pandas as pd
import numpy as np
from collections import defaultdict
import HowToBreakIntoTheFieldSolns as s
## How To Break Into the Field
# Question 1
def check_description(descrips):
'''
INPUT:
descrips - should be a set of all descriptions in the dataset - each description should be a string. Y... |
5a09221be921ad1d692daee7553a978bde3da1fd | eduardoaze/paciencia | /jogo.py | 9,435 | 3.734375 | 4 | print ('Paciência Acordeão')
print ('==================')
print('')
print ('Seja bem-vindo(a) ao jogo de Paciência Acordeão! O objetivo deste jogo é colocar todas as cartas em uma mesma pilha.')
print('')
print ('Existem apenas dois movimentos possíveis:')
print ('1. Empilhar uma carta sobre a carta imediatamente a... |
8d158b8a1b3766fbc5c56767e9371e81558d15eb | cwivagg/s_and_p | /scrape_example.py | 1,545 | 3.65625 | 4 | """Download morningstar.com company director listings.
Requires a companion file entitled "constituents.csv" with company ticker
symbols in a column headed "Symbols".
Requires the directory stored_websites.
This code downloads a series of websites, in this case, a simple set of
data about each of the S and P 500 c... |
c0b96c7d22c456e0d55ae70bd06c88b8a92dbb06 | Rikeld0/my_project | /db.py | 2,938 | 3.796875 | 4 | import sqlite3
from sqlite3 import Error
def create_conn():
conn = None
try:
conn = sqlite3.connect("my.db")
except Error as e:
print(f"The error '{e}' occured")
return conn
def create_table(conn):
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS мосэнерго_2020(
id text ... |
b5d1beaffcd4442f1e3dcb253c90e1f5887bbb20 | karar-vir/python | /class13.py | 1,073 | 4.59375 | 5 | #Abstract Class
#we can't create the object directly of any abstract class,if we want to create the object of abstract class then before
#we need to inherit that abstract into another class after that we can create it object othwise it will not possible
#**********Python can't be directly allow to abstract class b... |
5022f0f1ed6f2c3730c4918c7502c1f242c25c6c | karar-vir/python | /hackerEarth_funtion.py | 456 | 4.0625 | 4 | def string_multiplier(string_arg, number):
'''takes the string_arg and multiplies it with one more than the number'''
return string_arg * (number + 1)
# passing string_arg and number and in that order...
print(string_multiplier('a', 5)) #aaaaaa
langs = ["haskell", "clojure", "apl"]
la... |
d6c26436e411416950b70de29faf9aecdfcd4f6b | karar-vir/python | /lambda.py | 313 | 3.640625 | 4 | def cube(y):
return y*y*y
d=lambda x:x*x*x
print(d(4))
print(cube(3))
li=[3,3,3,4,3,54,43,65,65,5,3,2,42]
final_lst=list(filter(lambda x:(x%2!=0),li))
print(final_lst)
final_lst2=list(map(lambda x:(x%2!=0),li))
print(final_lst2)
final_lst2=list(map(lambda x:x*x,li))
print(final_lst2)
|
791b193b845071dc460aaa5798f6566eb25192de | karar-vir/python | /file_handling_remove_funtion.py | 263 | 3.859375 | 4 | #we will remove the file from the directory
import os
namefile=open('openfile.txt','w')
namefile.write('hello your file is created')
namefile.close()
if os.path.exists('openfile.txt'):
os.remove('openfile.txt')
else:
print('your file not exits')
|
9da86dd74f4316c6751be15129361150c03605a0 | karar-vir/python | /c5.py | 296 | 3.625 | 4 | class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def print_student_details():
print(self.name, end=" ")
print(self.age)
@staticmethod
def isTeen(age):
return age>16
a = Student.isTeen(18)
print(a)
|
8dd85506945c981e48604109b53f361fc0074b57 | karar-vir/python | /enumeration.py | 184 | 3.953125 | 4 | #program with enumeration
lst=['apple','mango','grapes']
for index,i in enumerate(lst):
print('%s is on index %s'%(i,index))
print("---------------------------")
print()
|
db25a85e188b1598fcf9889b7ccfd2f3ac082992 | karar-vir/python | /has_key().py | 325 | 4.3125 | 4 | #has_key() method is used to check the boolean result if the key in dictionary is present then it will return the True othewise if will return False
diction={'a':'apple','d':'banana','c':'cat'}
print(diction)
diction['b']="Dog"
print(diction)
call = {'sachin': 4098, 'guido': 4139}
call["snape"] = 7663
print(ca... |
52b5c4ed87652f5c4e532dc12a3bb932a62f21c0 | sdpython/mlstatpy | /mlstatpy/ml/matrices.py | 12,127 | 3.5 | 4 | import warnings
import numpy
import numpy.linalg
from scipy.linalg.lapack import dtrtri # pylint: disable=E0611
def gram_schmidt(mat, change=False):
"""
Applies the `Gram–Schmidt process
<https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process>`_.
Due to performance, every row is considered as a v... |
30191a476fd56ee7e9519b186273dddb342939c5 | sdpython/mlstatpy | /mlstatpy/nlp/completion_simple.py | 22,745 | 3.5625 | 4 | from typing import Tuple, List, Iterator, Dict
from .completion import CompletionTrieNode
class CompletionElement:
"""
Definition of an element in a completion system,
it contains the following members:
* *value*: the completion
* *weight*: a weight or a position, we assume a completion with
... |
2775105f7a87e5c55a4379254d67d49700db13cb | sdpython/mlstatpy | /mlstatpy/garden/poulet.py | 4,288 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import math
import random
def factorielle(x):
"""
Calcule :math:`x!` de façon récursive.
"""
if x == 0:
return 1
else:
return x * factorielle(x - 1)
def profit(N, X, p, q, s):
"""
Calcule le profit.
:param N: nombre de poulets vendus
:par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.