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 |
|---|---|---|---|---|---|---|
16de6f9083bf208b6daad0ea8796f978c744c4e3 | hauselin/psychopy_modules | /extra/psychopy_test/scripts/s1.py | 1,249 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#"""
#Demo: show a very basic program: hello world
#"""
#from __future__ import absolute_import, division, print_function
# Import key parts of the PsychoPy library:
from psychopy import visual, core
# Create a visual window:
win = visual.Window(size=(900,900), color='b... |
81c7853ded72efe4e963c0700ddb6139d1b21be6 | rushabhshah341/Algos | /leetcode202.py | 927 | 3.5 | 4 | class Solution(object):
def sumOfSquares(self, num):
sum = 0
while (num > 0):
last = int(num % 10)
sum += pow(last, 2)
num /= int(10)
return sum
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
slow = fas... |
4cbc8fddcb32ba425cbcbb2ff96f580384c8ddbb | rushabhshah341/Algos | /leetcode38.py | 1,397 | 4.21875 | 4 | '''The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the co... |
79b5a9131c2c6f3c347cecb3967917fdd323861f | rushabhshah341/Algos | /leetcode14.py | 410 | 3.734375 | 4 | def longestCommonPrefix( strs):
"""
:type strs: List[str]
:rtype: str
"""
l = len(strs)
if l == 0:
return ""
pre = strs[0]
for x in range(1, len(strs)):
if strs[x].startswith(pre):
continue
else:
while not strs[x].startswith(pre):
... |
16a1c534cb151a7274d4152eb6789d9e277f662e | ericm1024/econ136 | /vai_econ136/rolldice/rolldice.py | 3,565 | 3.59375 | 4 | # rolldice.py in PyGo\PyFTR
# This is the experimental model for integrating a stock distribution.
# Designed in Python 2.7.11 for Econ 136
# Dated March 1, 2017 Professor Gary R. Evans
#
import math
import numpy as np
import matplotlib.pyplot as plt
#
# Establish the testing values of our stock price (stp)... |
53fe8e0f769381b98196c1b36d3c9c4d052e742d | RaaviSindhu/Hashing-1 | /49.py | 482 | 3.953125 | 4 | Time Complexity : O(n)
Space Complexity : O(n)
Runs on LeetCode : Yes
Doubts : # Should we include space complexity as O(n) even though we use it to print to output?
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict1={}
for i in strs:
... |
d34a9ffadd466ed56a6ae344e5434205f9c9a218 | caseybackes/python-design-patterns | /factory_pattern.py | 3,144 | 4.5625 | 5 | '''
The Factory Method Design Pattern
The central idea in Factory Method is to provide
a separate component with the responsibility to decide
which concrete implementation should be used based on
some specified parameter.
In this exercise, that parameter is "person_type" - ie: "Student" or "Teacher".
A different ... |
be4182cd2794ae9091356bd998747abdc04b4fde | toksan/python3_study | /database/alchemy.py | 6,617 | 3.640625 | 4 | """
SQLAlchemy によるデータベース操作
Website
https://www.sqlalchemy.org/
Document
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
"""
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc impo... |
84f8573cede1e8401d223c7eed929ff9e2a4faea | toksan/python3_study | /class/example_basic_1.py | 3,594 | 3.828125 | 4 | """
Python のクラスとオブジェクト学習用 基本サンプル
"""
class Item:
"""
商品クラス
"""
"""
商品リスト
Pythonではメソッド外で定義した変数は「クラス変数」になる点に注意しましょう。
クラス変数はこのクラスから生成したすべてのインスタンスで共有されます。
商品リストをクラス変数にする必要はありませんが、サンプルのためクラス変数にしてみました。
"""
item_list = [
{'name': 'None', 'price': 0},
{'name': 'pencil'... |
d059fa267c0dbba725a6e5a25dad2ec4d57b54e9 | hemarani5/lab4 | /task1updated.py | 391 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#Task1
import string
book = open("book2.txt","r")
punct = string.punctuation
for line in book:
bookline = book.readline()
bookllow = bookline.lower()
bookstrip = bookllow.strip()
for word in bookstrip:
if word in punct:
bookstrip = bookstrip.replace(wo... |
eab48b5f99aac73da0c4d3d1960e19dc56f15592 | frclasso/Formacao_Cientista_de_Dados_Python_R | /Python/13_visualizacao_de_dados/script9.py | 2,069 | 3.609375 | 4 | #90 Histograma e Densidade com Seaborn
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as srn
file_path = "C:/Users/fabio.classo/Downloads/fabio/estudos/R_lang/formacao_cientista_de_Dados/Python/13_visualizacao_de_dados/"
os.chdir(file_path)
base = pd.read_csv("./dados/trees.csv")
print(b... |
e2bf5e359b7cf8317254fbd1e7d46f5005a28b99 | AndrewEdgers/TALabs | /Lab3.py | 6,031 | 4.09375 | 4 | class Node:
def __init__(self, data):
self.item = data
self.ref = None
self.nref = None
self.pref = None
class LinkedList:
def __init__(self):
self.start = None
def traverse_list(self):
if self.start is None:
print("List has no element")
... |
b79cd27af7601a56d59e941b2889cd7aa6e1d6d4 | danieldymondnz/ENSE810-Assignment2-2021S2 | /app/MatrixDriver.py | 4,249 | 3.546875 | 4 | '''
MatrixDriver
Matrix driver class contains the methods to display various data
on the LED Matrix on the senseHAT module as required
Kyle Mendonca 2021
'''
import threading
class MatrixDriver(threading.Thread):
def __init__(self, senseHAT, matrixQueue):
threading.Thread.__init__(self)
... |
c9d26fb176941f3e05aef3214757a2d3982a90ee | vishnun-aa/Vishnu-Level-O-coding | /Vishnu Naidoo Level 0 Coding/Task2.py | 358 | 3.71875 | 4 | x = (1 + (1 * 2))
y = (1 + (1 * 2))
z = (1 + ( 1 * 2 ))
a = (1 + 1 * (2 / 2))
b = (1 + 1 * (2 / 2))
W = (x + y + z + a + b)
print (W)
###Just Printout off all Variables after BODMAS
x1 = 1 + 1 * 2
y1 = (1 + 1) * 2
z1= 1 + ( 1 * 2 )
a1 = 1 + 1 * 2 / 2
b1 = (1 + 1 * 2 ) / 2
print(x1)
print(y1)
pri... |
7559455e8c1ae79ac57c8bf35c50d51c8047d028 | R-Manning/CodeCademy-Path-ComputerScience | /Veneer_Marketplace.py | 1,963 | 3.671875 | 4 | class Art:
def __init__(self,artist,title,medium,year,owner):
self.artist = artist
self.title = title
self.medium = medium
self.year = year
self.owner = owner
def __repr__(self):
return '{artist}. "{title}". {year}, {medium}. {owner}, {location}.'.format(artist = self.artist, title =... |
f831a5469e92648e798bc8e6a7f4dec69ae34295 | trkwyk/Python-Data-Structure | /Chapter1/Projects/3.py | 244 | 3.703125 | 4 | def totalTravel(initialHeight, timeOfBounce):
sum = 0
height = initialHeight
for number in range(timeOfBounce):
sum+=1.6*height
height=0.6*height
return sum
if __name__=="__main__":
print(totalTravel(10,2)) |
01f9db8e846da162243d96374f027cbfda7b19d7 | trkwyk/Python-Data-Structure | /Chapter1/TypeConversion.py | 70 | 3.90625 | 4 | radius = float(input("Radius: "))
print("The area is", 3.14*radius**2) |
547323e6b8ee6adea2470154065cf9cfdb7a40ba | trkwyk/Python-Data-Structure | /Chapter1/Projects/4.py | 256 | 3.921875 | 4 | def GetPi(iteration):
sign = 1
sum = 0
for number in range(iteration):
sum+=1/(2*number+1)*sign
sign*=-1
return sum*4
if __name__ =="__main__":
iteration = int(input("How many iterations?"))
print(GetPi(iteration))
|
4eec0322cd663d91038a12c76e549878d12aef87 | trkwyk/Python-Data-Structure | /Chapter3/counting.py | 325 | 3.5625 | 4 | problemSize = 1000
print("%12s%15s" % ("ProblemSize","Iterations"))
for count in range(5):
number = 0
work = 1
for j in range(problemSize):
for k in range(problemSize):
number+=1
work+=1
work-=1
print("%12d%15d" % (problemSize, number))
problemSiz... |
176e8909aaa7368d5fe23e80ff9e8e92748b3f2c | Simochenko/ProgPython | /3.0.0.py | 27,997 | 4.1875 | 4 | '''Напишите функцию f(x), которая возвращает значение следующей функции, определённой на всей числовой прямой:
f(x)=⎧⎩⎨⎪⎪1−(x+2)2,−x2,(x−2)2+1,при x≤−2при −2<x≤2при 2<x
Требуется реализовать только функцию, решение не должно осуществлять операций ввода-вывода.
Sample Input 1:
4.5
Sample Output 1:
7.25
Sample Inp... |
ec4d628e0eb4f41614b41d527245e4a836660aad | gciruelos/imagenes-practicas | /practica1/ej04.py | 583 | 3.796875 | 4 | '''
Fraccionamiento de los planos de bits: hacer un programa que separe una imagen
en los 8 planos de bits y mostrarlos cada uno por separado
Modo de uso:
python3 ej04.py <img1>
'''
import numpy as np
import side_by_side
from PIL import Image
from sys import argv
im1 = np.asarray(Image.open(argv[1]).convert('L'))
i... |
10d414c6c7ab33475960a2f7dd9c02e4782b20a0 | JeterG/Post-Programming-Practice | /CodingBat/Python/List_1/reverese3.py | 173 | 4.34375 | 4 | #Given an array of ints length 3, return a new array with the elements in reverse order, so {1,2,3} becomes {3,2,1}.
def reverse3(nums):
return [nums[2],nums[1],nums[0]] |
ba01a9888ddaf5d9193a2ce4c969d1e3fba7d62f | JeterG/Post-Programming-Practice | /CodingBat/Python/List_1/make_pi.py | 130 | 3.6875 | 4 | #Return an int array length 3 containing the first 3 digits of pi, {3,1,4}.
def make_pi():
return [3,1,4]
print make_pi()
|
d387fccc48a7648632a6871dfac15f0e44cf1587 | JeterG/Post-Programming-Practice | /CodingBat/Python/Warmup_2/front_times.py | 413 | 3.9375 | 4 | #Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front.
def front_times(str, n):
if len(str)>=3:
x=""
y=str[:3]
for i in range(n):
x+=y
r... |
f2c1c902e1c88ffa31ddde2fe8be0b50aca02cb8 | JeterG/Post-Programming-Practice | /CodingBat/Python/String_2/cat_dog.py | 556 | 3.703125 | 4 | #Return True if the string cat and dog appear the same number of times in the given string.
def cat_dog(str):
cDog=0
cCat=0
temp=""
for char in str:
if char=="c":
temp=char
elif char=="d":
temp=char
elif char=="a" and temp=="c":
temp+=char
... |
ca9c82e87d639e70de2ce6b214706617fb8f6a71 | JeterG/Post-Programming-Practice | /CodingBat/Python/String_2/end_other.py | 458 | 4.125 | 4 | #Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string
def end_other(a, b):
lA=len(a)
lB=len(b)
if ... |
d424f6ccd79b78ccf3c37e68005968cc0d188c22 | JeterG/Post-Programming-Practice | /CodingBat/Python/List_2/big_diff.py | 370 | 3.796875 | 4 | #Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1,v2) and max(v1,v2) functions return the smaller or larger of two values.
def big_diff(nums):
small=10000000000000000
big=0
for num in nums:
big=max(big,num)... |
7190d64b0b1eeff59576e82b7506c23f8f740d6c | LauRivero150920/PygameTutorial | /Pygame2/main.py | 1,304 | 3.8125 | 4 | import pygame, sys
pygame.init()
# Definir colores
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
SIZE = (800, 500)
# Crear ventana
WIN = pygame.display.set_mode(SIZE)
pygame.display.set_caption("Tutorial Pygame2: Intro")
# Controlar frames per second
CLOCK = ... |
1188e9276fd461da36caf8882c3fa01e59b0a363 | theblueskies/Algos | /AP.py | 215 | 3.75 | 4 | def missing_num():
arr = [1,3,5,9]
summation=0
for x in arr:
summation+=x
act_sum = int(.5*(len(arr)+1)*(arr[0]+arr[len(arr)-1]))
diff = act_sum-summation
print diff
missing_num() |
f2a33d336730825712dee1d5a0d52d9947cc36d0 | theblueskies/Algos | /anagrams.py | 803 | 4.03125 | 4 | def anagram(word):
if len(word) <2:
return word
else:
for i in range(len(word)):
ana = []
character = word[i]
for j in anagram(word[:i] + word[i+1:]):
print j + character
# ana.append([anagram(word[:i]),word[i],anagram(word[i+1:])]... |
320460fb06c7a5172b54d473e461d77341d16efe | theblueskies/Algos | /linkedlist_experiments.py | 1,097 | 4.09375 | 4 | from codes import linked_list
from codes import node
a = linked_list()
b = linked_list()
a.add_node(-2)
a.add_node(0)
a.add_node(2)
a.add_node(4)
b.add_node(1)
b.add_node(3)
b.add_node(5)
def linklength(a):
curr = a.heado
count = 0
while curr is not None:
count+=1
curr=curr.next
retur... |
c33567bc32acd51538ed01c511a25d543222e959 | vpereira06/PS-25-06 | /PS.py | 2,058 | 3.890625 | 4 | #Ex. 1
texto = "Numa terra fantástica e única, chamada Terra-Média, um hobbit recebe de presente de seu tio o Um Anel, um anel mágico e maligno que precisa ser destruído antes que caia nas mãos do mal. Para isso o hobbit Frodo (Elijah Woods) terá um caminho árduo pela frente, onde encontrará perigo, medo e personage... |
ff2adf89663cb061ad210150e596ea8de8ae1216 | Ehsanmrtz/Pyhton-Traning | /Set-Intersection-01(Finds Vowels).py | 176 | 3.9375 | 4 | while True:
word = input ('input word = ')
vowels = set ('aeiou')
i = vowels.intersection(set(word))
vi = list(i)
print('vowel word in your word are =',vi)
|
beff09625b197da98077c6e74c830bc139cc630a | Ehsanmrtz/Pyhton-Traning | /Function_1.py | 217 | 3.53125 | 4 | def welcome (name):
print ('Dear Mr/Ms', name)
print ('Thnaks for your email, We will check and answer your question as soon as possible')
print ('Best Regards,')
n = input ('Enter The Name: ')
welcome (n) |
86621426f02146de4844c914a0c9660b29abaab2 | Ehsanmrtz/Pyhton-Traning | /print bigger number.py | 126 | 3.96875 | 4 | n1 = int (input ('Enter Number One: '))
n2 = int (input ('Enter Number Two: '))
if n1 > n2:
print (n1)
else:
print(n2) |
b034746526df3aef5eab65dc44f371961793d291 | KrystianGrabowski/University | /Python Rozszerzony/L2/PRL2Z1.py | 1,017 | 3.65625 | 4 | class Wyrazenie:
pass
class Stala(Wyrazenie):
def __init__(self,x):
self.x = x
def oblicz(self,zmienne):
return self.x
class Zmienna(Wyrazenie):
def __init__(self,x):
self.x = x
def oblicz(self,zmienne):
return zmienne[self.x]
class Dodaj(Wyrazenie):
def __init__(self,a,b):
self.a = a
self.b = b
... |
f8b9bd890548a5d2b5fd2b60e23f68053b282097 | duongtran734/Python_OOP_Practice_Projects | /ReverseString.py | 625 | 4.5625 | 5 | # Class that has method that can reverse a string
class ReverseString:
# take in a string
def __init__(self, str=""):
self._str = str
# return a reverse string
def reverse(self):
reverse_str = ""
for i in range(len(self._str) - 1, -1, -1):
reverse_str += self._str[i... |
95d318e188b6f3ffb4568829e3c4ca6df10d013f | abcjamesjordan/100_projects_python | /100_python_projects.py | 7,599 | 4.21875 | 4 | #!/usr/bin/env python3
# imports
# reminder to add required imputs to requirements.txt file_name
import numpy as np
import matplotlib as plt # need to add to requirements.txt
import random
import math
# Global Variables
mydata = [1, 2, 3, 4, 5, 6, 7, 8]
mydata2 = [1, 8, 2, 3, 4, 5, 6]
myrand = [random.ran... |
653021c484358ba60b21bccf1d27c254f10664f2 | chenyuxiang0425/Computer-Networking-A-Top-Down-Approach | /lab03/SMTPClient.py | 2,226 | 3.671875 | 4 | from socket import *
import my_account
msg = "\r\n I love computer networks!"
endmsg = "\r\n.\r\n"
# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = "smtp.qq.com"
# Create socket called clientSocket and establish a TCP connection with mailserver
#Fill in start
def do_with_email(opera... |
062de56f655f699402b4029ed1d69fdd378998b0 | GrodVidar/AdventOfCode19 | /Third/third.py | 4,820 | 4.1875 | 4 | class Lines:
def __init__(self, x, y):
self.x = 0
self.new_x = x
self.y = 0
self.new_y = y
self.horizontal = False
self.vertical = False
self.steps = 0
def print_values(self):
print(f'x: {self.x}, new_x: {self.new_x}\ny: {self.y}, new_y: {self.new... |
ca432f83fb5d3db84cc96c2ceac725709ac30c64 | LolaWei/-----1 | /找出敏感词汇.py | 371 | 3.5625 | 4 | def replace_words(temp):
l=[]
with open(r"C:\Users\hp\Desktop\filtered_words..txt") as f:
for each in f.readlines():
l.append(each.strip())
for i in l:
if i in temp:
print(temp.replace(i,"**"))
def main():
temp=input("请输入:")
replace_words(temp.str... |
dc27f3d8f78a113e3f3dda6d273b3a6ec23df44e | LolaWei/-----1 | /满天星.py | 2,068 | 3.90625 | 4 | from bs4 import BeautifulSoup
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-... |
30442bb74aea8fcd7c4f0856158697449a34bd10 | isullivan/LSST-DCR | /DCR test code/calcRefractiveIndex.py | 4,394 | 3.546875 | 4 | from __future__ import print_function, division, absolute_import
import numpy as np
def refraction(wavelength, zenith_angle, atmospheric_pressure, temperature, humidity=10,
latitude = -30.244639, altitude = 2663.):
"""
input pressure is in atmospheres
wavelength and zenith_angle may be supplied as numpy vectors
... |
b771d4e5db5ae66e32168b8f33543b6f19f2515a | freude/NanoNet | /nanonet/tb/aux_functions.py | 18,362 | 3.609375 | 4 | """
The module contains a set of auxiliary functions facilitating the tight-binding computations
"""
from __future__ import print_function
from __future__ import absolute_import
from itertools import product
import numpy as np
import yaml
def accum(accmap, input, func=None, size=None, fill_value=0, dtype=None):
"... |
90bd46ef800eb69e25491e6bbc7d0424e84a6bf2 | freude/NanoNet | /nanonet/tb/orbitals.py | 5,640 | 3.6875 | 4 | """
Module contains the class `Orbitals` that allows to generate any user defined basis set based on
the linear combination of atomic orbitals (LCAO). Also, the module contains a set of predefined basis sets
`SiliconSP3D5S`, `HydrogenS`, `Bismuth`.
"""
import sys
from nanonet.tb.aux_functions import print_table
class... |
bd12113e4ca9a48b588c74d151d21373cdc9cfa1 | pwittchen/learn-python-the-hard-way | /exercises/exercise45.py | 875 | 4.25 | 4 | # Exercise 45: You Make A Game
'''
It's a very simple example of a "text-based game",
where you can go to one room or another.
It uses classes, inheritance and composition.
Of course, it can be improved or extended in the future.
'''
class Game(object):
def __init__(self):
self.kitchen = Kitchen()
self.livi... |
909e04e6aa1d9f0d72be4b8cb17a3cb2f4435f85 | dpro7026/numpy-neural-network | /fnn.py | 4,417 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# import data from csv
df = pd.read_csv('loan.csv', nrows=100)
# print out list of all headers
headers = df.columns.values.tolist()
print(headers)
# print count for values for each 'grade'
print(df['grade'].value_counts())
# CLEAN DATA
# Choo... |
05f44c60a7e589fc58cd7aef8837819d6cc08393 | zachbrennan/GPX_Parser | /maxPower.py | 442 | 3.65625 | 4 | def maxIntPow(steps, interval):
maxInt = 0
tempInt = 0
for k in range(0, interval):
tempInt += int(steps[k].text)
for i in range(interval,len(steps) - (interval - 1)):
tempInt -= int(steps[i-interval].text)
tempInt += int(steps[i].text)
if (tempInt > maxInt):
... |
d0b632d49331bab03608072df07f463165960107 | XuHuaXH/Cryptopals | /src/c15_pkcs7_padding_validation.py | 610 | 3.953125 | 4 |
def unpad(padded):
if len(padded) == 0:
raise ValueError("no padding found")
padding_length = int(padded[len(padded) - 1])
if len(padded) < padding_length:
raise ValueError("padding is invalid, padded string not long enough")
padding = padded[-padding_length:]
if padding != bytes([... |
46a1a1d8c2f29dadd26dd1c303a8ac48631dd16e | CodePythonGuaratingueta/aulas | /aula_listas/ex11.py | 184 | 3.5625 | 4 | notas = []
for i in range(4):
notas.append(float(input("Digite a nota: ")))
soma = 0
for i in notas:
soma = soma + i
print("Nota: ", i)
print("média: ", soma / 4)
|
cc384b822bbb0a86070fac762dd1b571bc0355b1 | dotrungkien/viblo-code-contribution | /stranger-fibo/test/testcases.py | 2,096 | 3.78125 | 4 | from math import sqrt
from random import randint
import unittest
test.describe("Basic tests")
test.it("Verifying that fib(0) == 0")
test.assert_equals(fib(0), 0)
test.it("Verifying that fib(1) == 1")
test.assert_equals(fib(1), 1)
test.it("Verifying that fib(2) == 1")
test.assert_equals(fib(2), 1)
test.it("Verifying... |
1304b5f36f65e60137d7fcdae9fc76f6f531f120 | hmurraydavis/MCM2015 | /smallWorld3.py | 28,644 | 3.953125 | 4 | '''Graph is set up as a list of dictionaries of form:
graph = [ {'gender':0, #0 is female, 1 is male
'inContact':[[n1,weightn1],[n2,weightn2],[n3,weightn3]], #list of the people they're connected with --> outer list is the connected verticies, nested list's 0th element is the connected vertex. 1st element is the ... |
ece22b4f48a64a0a75ff353a8c176cebad3ae2a6 | Athira-manu/pycharmprojects | /pythonProject1/while.py | 192 | 3.875 | 4 | # c=0
# while c<=5
# print (c)
# c+=1
# i=0
# while i<=6:
# i+=1
#
# if i==3:
# continue
# print(i)
i=0
while i<6:
print(i)
if i==3:
break
i+=1 |
bda9f49ac05635ee3a9140f6bf6f5a770e667707 | Athira-manu/pycharmprojects | /pythonProject1/codechallenge7.py | 191 | 3.96875 | 4 | dic={"soap":50,"shampoo":70,"kajal":75}
c=input("enter a product name:")
for i in dic:
if i==c:
print("price of the item is:",dic[i])
break
else:
print("not found")
|
43ce02ae0be4223e4169d06c0729b02c2f99a355 | Athira-manu/pycharmprojects | /pythonProject1/codechallenge2.py | 151 | 3.640625 | 4 | for i in range(0,5):
print("I am a programmer")
i+=1
for i in range(1,10):
def square(i):
return i
print(square(i*i))
i+=1
|
b3e761b64d353c33f92e45d315c937295368807a | nogasayag/this | /lunapark.py | 305 | 4.0625 | 4 | f_name = input("Enter your first name: ")
l_name = input("Enter your last name: ")
h = int(input("Enter your height in cm: "))
age = int(input("Enter your age: "))
if 12 > age > 6 and 150 > h > 120 :
print("you can go on the roller coaster!")
else:
print("you can't go on the roller coaster :( ")
|
e285906bb29ffc65cae6fadcfd0d0a7cdacd7b70 | fermosc24/SXTOPOLOGY | /mygraph.py | 10,969 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
import networkx as nx
import numpy as np
from itertools import combinations
from random import sample,choice
import re
def Adjacency(graph,digraph=False):
"""
Computes adjacency matrix for a graph. To be used instead of NetworkX's
native function.
:graph: Networ... |
8d1662a783bc9ec57c9ca5ccec22a857fbe4cad7 | SpiralBL0CK/AoC2020 | /advent_of_code/second/correct_yourself_third.py | 615 | 3.609375 | 4 | import re
def s():
z = 0
i = 0
f = open("input","r")
for line in f.readlines():
mina = int((line).split()[0].split('-')[0])
#print((line).split()[0].split('-')[0])
maxa = int((line).split()[0].split('-')[1])
letter = line.split()[1].split(":")[0]
text = line.split... |
4b5fc937dcc767452a7f5390191094b893ebc3e7 | RoodrigoRoot/tests_selenium | /project/user.py | 1,983 | 3.78125 | 4 | import random
class User:
def __init__(self, name, last_name, email, phone):
self.__name = name
self.__last_name = last_name
self.__email = email
self.__phone = phone
self.__code = 0
def __str__(self):
return f"Full name: {self.name} {self.last_name} \nCode: {... |
7e888e32add506ae9ba33925b2709fa4d86adb5c | sumaiya-antara/Relational-DB-Notes-by-princebillyGK | /Python-fake-data-generator/schema.py | 10,935 | 3.53125 | 4 | from json import load as json_loader
from PyInquirer import prompt
with open('datatypes_faker.json') as datatype_file:
datatypes = json_loader(datatype_file)
class DBItems:
def input_unique_obj_index(self, ls_name):
"""Get column index from prompt"""
if getattr(self, ls_name):
qu... |
f034fe8b86d59fae0b167905b1431bdc308754fe | mestrella3602/turtle-pencil | /colors/mypolygon.py | 176 | 3.65625 | 4 | def polygon (t,sides,distance):
angle=360/sides
t.begin_fill()
for times in range(sides):
t.forward(distance)
t.left(angle)
t.end_fill()
|
25377da95678171c8bb69352f8ca4032e0d71c1c | thepghimire/internship-basics | /edge.py | 598 | 3.5 | 4 | # Canny Edge Detection
""" Multi stage algorithm.
- Noise Reduction using 5x5 gaussian filter.
- finding the intensity gradient of the image
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("data/monkeys.jpg")
edges = cv2.Canny(img, 0, 150) #Source, minVal, maxVal
plt.subplot(121)... |
5cbaf0e35f522e7dc5563ccb789c91bd41a1f294 | jwebber1/PythonPowerSet | /prg2.py | 1,697 | 3.84375 | 4 | '''
Sept 29, 2019
CSC246, Programming Languages
Dr. Kendall-Morwick
Jonathan Webber
Functional Programming
'''
def allsubsets(newSet):
#convert the input set into a list
tempList = list(newSet)
#create a newList to return
newList = []
#get the length of the input set/li... |
60c4619d9ca486115461339d0d6ae274e06f09f9 | shubham-ram/currency-converter | /converter.py | 580 | 3.609375 | 4 | import requests
api_key = '###############'
from_currency = "USD"
to_currency = "INR"
amount = input('Enter the amount: ')
baseurl = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE'
main_url = baseurl + '&from_currency='+from_currency+ '&to_currency='+to_currency+'&apikey='+api_key
respo... |
154953eb3e7c96a9ede597d94b296a8679f05ce4 | Jackrifleman/CS-362-HW4 | /name.py | 520 | 3.53125 | 4 | #Jackson Eubank
#CS362
#HW4 - Full Name
def getFullName(first,last):
if (len(first) == 0):
raise ValueError("Recieved an empty array for a first name!");
if (len(last) == 0):
raise ValueError("Recieved an empty array for a last name!");
for x in first:
if(first.isdigit()):
... |
468accaa54ae38334b678e5bc21d2f7f2a6f7771 | sgangopadhyay/Python-String-Randomized | /random_string.py | 338 | 3.96875 | 4 | # PROGRAM : Python program for randomizing a String / Jumble_Word
# CODED BY : Suman Gangopadhyay
# DATE OF CODING : 10-Sept-2018
# CAVEATS : Using Python 3.5.2
# Email ID : linuxgurusuman@gmail.com
import random
def Jumble_Word(word):
word = list(word)
random.shuffle(word)
return ''.join(wor... |
936733664465f3e441717731240fb7e72927df10 | PiyuGandhi/InterviewPractice | /InterViewBit/flip.py | 1,921 | 3.828125 | 4 | '''
You are given a binary string(i.e. with characters 0 and 1) S consisting of characters S1, S2, …, SN. In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters SL, SL+1, …, SR. By flipping, we mean change character 0 to 1 and vice-versa.
Your aim is to perform ATMOST... |
0fef35a579b26bf45b59abc2d4b63004094bf233 | PiyuGandhi/InterviewPractice | /GeeksForGeeks/Amazon/howManyX.py | 1,468 | 3.78125 | 4 | """
Given an integer X within the range of 0 to 9, and given two positive integers as upper and lower bounds
respectively, find the number of times X occurs as a digit in an integer within the range, excluding
the bounds. Print the frequency of occurrence as output.
Input:
The first line of input is an integer T, de... |
5ff3304ca4cec7f6cd386d2c0e02c10d29a93de2 | PiyuGandhi/InterviewPractice | /GeeksForGeeks/Amazon/positiveNegativePairs.py | 1,587 | 3.65625 | 4 | """
Given an array of distinct integers, print all the pairs having positive value and negative value
of a number that exists in the array.
NOTE: If there is no such pair in the array , print "0".
Input:
The first line consists of an integer T i.e number of test cases. The first line of each
test case consists of a... |
0e5e4e0da6d1cbf28f0ff7a90b799f7f7b45977e | sushmithasuresh/Python-basic-codes | /p13.py | 159 | 3.796875 | 4 | r=input("enter range")
os=0
es=0
for i in range(r+1):
if(i%2==0):
es+=i
else:
os+=i
print "odd sum=",os
print "even sum=",es
|
7b979b62e0828aae93811ff6b9c39fd5bca83ec5 | sushmithasuresh/Python-basic-codes | /p9.py | 228 | 4.28125 | 4 | n1=input("enter num1")
n2=input("enter num2")
n3=input("enter num3")
if(n1>=n2 and n1>=n3):
print str(n1)+" is greater"
elif(n2>=n1 and n2>=n3):
print str(n2)+" is greater"
else:
print str(n3)+" is greater"
|
7cb2f9e307ca1943d803fd2a8556393382f9bcf7 | Lirhhack/Problemas | /La paradoja del cumpleaños.py | 436 | 3.578125 | 4 | import random
def generar_cumpleaños():
mes = random.randint(1, 12)
dia = random.randint(1, 31)
return dia, mes
n = int(input('Ingrese la cantidad de personas que desea probar : '))
List = []
for x in range(0, n):
List.append(generar_cumpleaños())
if len(List) != len(list... |
8502b04b587297c0ca54964e6eccdaeb5b2f87a7 | barueri-alunos/revisao-oo | /classes.py | 762 | 3.5 | 4 | from random import randint
class Cliente:
def __init__(self, nome, cpf):
self.nome = nome
self.cpf = cpf
class Conta:
def __init__(self, cliente):
self.titular = cliente
self.numero = self._gerar()
self.saldo = 0
def extrato(self):
print(f'Numero da conta:... |
c2af420480107b11682c33dec2cd1725c11652e9 | mkogerd/EE379K-Lab1 | /problem3.py | 864 | 3.515625 | 4 | # Michael Koger Darden (mkd788)
# EE 379K Lab 1 - Problem #3
# Check for numpy and pyplot
try:
import numpy as np
except ImportError:
print("numpy is not installed")
try:
import matplotlib.pyplot as plt
except ImportError:
print("pyplot is not installed")
# Generate 25,000 samples fro... |
0e19181e632a6ba984b220deaa16c443cfbbcfc5 | nivethasathiya/nivetha15 | /nivetha15.py | 264 | 3.84375 | 4 | lowerlimit = input()
upperlimit = input()
lowerlimit = int(lowerlimit)
upperlimit = int(upperlimit)
num = lowerlimit
while num <= upperlimit :
p = list(str(num))
count = 0
for a in p:
count += int(a)**3
if count == num :
print("Armstrong Number = " , num)
|
d9246e3feafc1c99275e6b0460e8e30d12b5db76 | youkochan/youko-leetcode | /py/367. Valid Perfect Square.py | 410 | 3.578125 | 4 | class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
l = 1
r = num
while l <= r:
m = (l + r) / 2
n = m ** 2
if n == num:
return True
elif n < num:
... |
30744f1fa9531ef452bdde8d420aa3851730062a | gar0u/mutualInformation | /scripts/dna.py | 6,775 | 4.125 | 4 | DEBUG = False
class dna:
"""
This class implements the DNA alphabet.
"""
PADDING_CHAR = 'A'
SYMBOLS_PER_WORD = 4
WORD_SIZE = 8 # bits
# String representation of bits
alphabet = {'A': '00', 'C': '01', 'G': '10', 'T': '11'}
encoding = {'00': 'A', '01': 'C', '10': 'G', '11': 'T'}
... |
95216d283b72505841f9c8b7457d9d9332306635 | GingerNinja23/controller-framework | /svpn/ControllerModule.py | 1,249 | 3.546875 | 4 | from abc import ABCMeta, abstractmethod # Only Python 2.6 and above
"""
Defining an abstract class which the controller
modules will implement, forcing them to override
all the abstract methods
"""
class ControllerModule(object):
__metaclass__ = ABCMeta
def __init__(self):
self.pendingCBT = {}
... |
4186b70a8f55396abe0bbd533fe61b7e8819f14e | mprior19xx/prior_mike_rps_game | /functions.py | 919 | 4.34375 | 4 | # EXPLORING FUNCTIONS AND WHAT THE DO / HOW THEY WORK
#
# EVERY DEFINITION NEEDS 2 BLANK LINES BEFORE AND AFTER
#
def greeting():
# say hello
print("hello from your first function!")
# this is how you call / invoke a function
greeting()
def greetings(msg="hello player", num1=0):
# creating another func... |
53fcbf43171cfb5a3c38e05ee1c1d77d6b89a171 | jhmalpern/AdventOfCode | /Puzzles/Day5/Day5Solution.py | 2,238 | 4.1875 | 4 | # Imports
import time
from re import search
# From https://www.geeksforgeeks.org/python-count-display-vowels-string/
# Counts and returns number of vowels in a string
##### Part 1 functions #####
def Check_Vow(string, vowels):
final = [each for each in string if each in vowels]
return(len(final))
def Check_r... |
8d89bdc7ba25eb4d3dcd8567d88c1c13eb062348 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Malvika is peculiar about color of balloons.py | 211 | 3.84375 | 4 | for _ in range(int(input())):
s=input()
if 'a' and 'b' in s:
if s.count('a')>s.count('b'):
print(s.count('b'))
else:
print(s.count('a'))
else:
print(0) |
b05f852b275f5d4cfc8df1a3352c9da69acde78f | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Uniform Strings.py | 169 | 3.53125 | 4 | for _ in range(int(input())):
s=input()
if s.count('01')+s.count('10')+int(s[0]!=s[len(s)-1])<=2:
print("uniform")
else:
print("non-uniform") |
708641417e2b98d8e682bc697089f514aed07297 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Secret Recipe.py | 245 | 3.515625 | 4 | for _ in range(int(input())):
x1,x2,x3,v1,v2=map(int,input().split())
dx1=abs(x3-x1)
dx2 = abs(x3 - x2)
t1,t2=dx1/v1,dx2/v2
if t1<t2:
print("Chef")
elif t2<t1:
print("Kefa")
else:
print("Draw") |
984c4c81839fd93312c78722d683e525dfea1ec6 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Area or perimeter.py | 303 | 3.78125 | 4 | '''l=float(input())
b=float(input())
p=2*(l+b)
a=l*b
if a>p:
print("Area")
print(int(a))
elif a<p:
print("Peri")
print(int(p))
else:
print("Eq")
print(int(a))'''
a, b=int(input()), int(input())
a, b=a*b, 2*(a+b)
print("Area"*(a>b)+"Peri"*(b>a)+"Eq"*(b==a),a+(b>a)*(b-a),sep='\n') |
6799a6d8282f829c7f7faed225e6bd8a21ed1315 | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Play Piano.py | 193 | 3.546875 | 4 | for _ in range(int(input())):
s=input()
n=len(s)
g=['AB','BA']
if n%2==0 and all(s[i:i+2] in g for i in range(0,len(s)-1,2)):
print("yes")
else:
print("no") |
1a605ecbac3e3f9b758169ed3904c83f020a119f | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Chef and Cook-Off Contests.py | 408 | 3.75 | 4 | for _ in range(int(input())):
n=int(input())
mydik = {"cakewalk": 0, "easy": 0, "simple": 0, "easy-medium": 0, "medium": 0, "medium-hard": 0, "hard": 0}
for _ in range(n):
mydik[input()]+=1
if mydik["cakewalk"] and mydik["easy"] and mydik["simple"] and (mydik["easy-medium"]+mydik["medium"]) and ... |
1ccd112f2d72ca0ddac7622bd55ea998a09b075f | S-C-U-B-E/CodeChef-Practise-Beginner-Python | /Chef and Glove.py | 489 | 3.625 | 4 | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
g=list(map(int,input().split()))
front,back=True,True
for i in range(n):
if l[i]>g[i]:
front=False
break
g.reverse()
for i in range(n):
if l[i]>g[i]:
back=False
... |
b96030688aaf13967ac704af3ea45d2ed4046c07 | priyadharshini18996/bankaccount | /bankaccount.py | 786 | 3.9375 | 4 | balance=2000.32
print(" welcome to No.1 ATM ")
print("""
1)Balance
2)Withdraw
3)Deposit
4)Quit
""")
Option=int(input("Enter Option: "))
if Option==1:
print "Balance:",balance
if Option==2:
print "Balance : ",balance
Withdraw=float(input("Enter Withdraw amount : "))
if Withdraw>0:
currentbalan... |
feaa3913d95e590845ff4bd0ab785bfdf216d546 | xqhl/python | /03.threeday/04.fileIO.py | 801 | 3.6875 | 4 | # 文件读写
file = open(file='./train', mode='r')
# content = file.read() # 读取文件通篇内容
# print(content)
# content = file.readline() # 逐行读取
# print(content)
# content = file.readline()
# print(content)
# content = file.readline()
# print(content)
# content = file.readline()
# print(content)
# content = file.readline()
# ... |
2bbc62def0409391e8d077114b6d001c95acd12b | xqhl/python | /04.function/03.function_return.py | 802 | 4.1875 | 4 | # 函数返回值
string = 'hello world'
string = string.replace('o', '0')
print(string)
# 具备返回值的函数
def add(a=0, b=0):
c = a + b
return c
def odd(c=1, d=1):
e = c * d
return e
# result_add = add(2, 3)
# result_odd = odd(c=result_add, d=6)
# print(result_odd)
result = odd(c=add(2, 3), d=6)
print(result)
# yie... |
d715451059376a082f81f0264cbb42f6147fd945 | xqhl/python | /01.oneday/01.helloworld.py | 430 | 3.828125 | 4 | # usage: println 'hello world'
# date: 2019/11/18
# filepath: cloud1908/01.oneday/01.helloworld.py
import os # 引入模块->俗称的轮子
def funcName(params): # 定义一个函数, 通常用来节约代码
pass
print('hello world')
for i in range(10):
print(i)
n = 0
while n < 10:
print(n)
n += 1
if 1 < 2:
print('1 < 2')
eli... |
3df8c49130b7cac51617a3b99e97123061d58972 | xqhl/python | /04.function/02.function_param.py | 672 | 3.90625 | 4 | # 函数参数: param
# 在函数中传入多个参数:
def cj(a, b, c):
print(a * b * c)
cj(1, 2, 3)
# 设定函数参数的默认值
def cjs(a=1, b=1, c=1):
print("a: {}".format(a))
print("b: {}".format(b))
print("c: {}".format(c))
print(a * b * c)
cjs(1)
# 传入指定的参数值
# cjs(a=1, b=3, 4)
cjs(1, b=3, c=1)
# 不定长度的参数
# print(1, 2, 3, 4, 5)
def pr... |
8fb2bb573484627a476bc7d751304a1a20ec581c | ag300g/learnpy | /leecode/MaxRepeatSubstr.py | 1,370 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
给出一个字符串, 返回一个最长的子串, 要求这个子串中元素都连续且相同
e.g. input: dacccccjgkbbbbklajaaa
output: cccccc
'''
class Solution:
# @param, a list of char
# @return an string
'''
思路:
(1) 记录上一个字符, 当下一个字符和上一个字符一样时, 这个字符的重复次数+1
(2) 当下一个字符与上一个字符不一致时, 更新上一次字符的内容, 并且重新... |
40a97e4dca75ef8b0855185e7ad2718b61ef5d7b | aidanwalk/ASTR260_HW08 | /AidanWalk_HW08_2.py | 2,232 | 3.78125 | 4 | #Aidan Walk
#ASTR 260-001
#Homework 08 Problem 2
#24 March 2021, 17:00
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
def f(x, y):
'''f(x,y) = 5 * exp( -1*(x-1)**2 - 2*(y-3)**2 ) + 3 * exp( -2*(x-4)**2 - (y-1)**2
takes in values of x and y
returns f(x,y)... |
fbd1224017d0248dbd66d80a2df9d7e56d025650 | lczen/learnPython | /未整理/YanghuiTriangle.py | 399 | 3.5 | 4 | n = int(input('请输入三角形高度:'))
layer = 1
values = [1]
while layer <= n:
new_values = [1]
index = 0
while index < len(values):
print('%d ' % values[index], end='')
if index < len(values) - 1:
new_values.append(values[index] + values[index + 1])
index += 1
new_values.ap... |
e4a32a9f47b01257b9d25f4544c1087f0789a485 | lczen/learnPython | /回溯法/组合数之和2.py | 1,247 | 3.515625 | 4 | '''
已知一组数(其中有重复元素),求这组数可以组成的所有子集中,子 集中的各个元素和为整数target的子集,结果中无重复的子集。
例如: nums[] = [10, 1, 2, 7, 6, 1, 5], target = 8
结果为: [[1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]
'''
class Solution:
def combinationSum2(self, candidates, target):
def generate(i, nums, item, result,res_set,sum,target):
if i>=len(num... |
8b59b558b9d5fd34a1d2b7851bf77982893de3ef | lczen/learnPython | /排序算法/堆排序(正月).py | 1,251 | 3.5625 | 4 | '''
parent = (i-1)/2
c1 = 2i+1
c2 = 2i+2
'''
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def heapify(tree, n, i):
if i >= n:
return
c1 = 2 * i + 1
c2 = 2 * i + 2
max = i
if c1 < n and tree[c1] > tree[max]:
max = c1
if c2 < n and tree[c2] > tree[ma... |
345a68200f491579021c3c1afcbcc279363eaa48 | lczen/learnPython | /回溯法/电话号码的字母组合.py | 879 | 3.59375 | 4 | """
时间复杂度:3^M*4^N(M代表三个字母的数量,N代表四个字母的数量)
"""
class Solution:
def letterCombinations(self, digits):
if not digits:
return []
phone = {'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n... |
9aca2bbbd3aac4359d2fe834d72d2dfaf1bc907c | lczen/learnPython | /链表/链表排序.py | 1,769 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# class Solution:
# def insertionSortList(self, head: ListNode) -> ListNode:
# if not head:
# return head
# cur, nxt = head, head.next
# dummy = ListNode... |
226aa19c96e12ff3ee34508e770daeff399e9ceb | lczen/learnPython | /未整理/堆.py | 1,392 | 3.84375 | 4 | import heapq
graph = {
"A": {"B": 5, "C": 1},
"B": {"A": 5, "C": 2, "D": 1},
"C": {"A": 1, "B": 2, "D": 4, "E": 8},
"D": {"B": 1, "C": 4, "E": 3, "F": 6},
"E": {"C": 8, "D": 3},
"F": {"D": 6}
}
class Dijkstra:
def init_distance(self, graph, start):
distance = {start: 0}
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.