blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
484eaf560e26b64352a7a3ebdc664e053badff3e | weiguxp/pythoncode | /ProblemSets/swampy/Exercise7.py | 256 | 3.875 | 4 | import math
import random
def sqrt(a):
b =20
y = 30
while abs(y-b)>0.01:
b = y
y = (b + a/b)/2.0
return y
def test_sqrt(n):
for i in range(n):
y = random.randint(1,100)
print i, " ", sqrt(y), " ", math.sqrt(y), " ",
test_sqrt(5)
|
718f43113c772e059cf23cf53f610d55b0e5171b | robnee/async | /async3.py | 635 | 3.5625 | 4 | #! /usr/bin/env python3
import time
import asyncio
# Borrowed from http://curio.readthedocs.org/en/latest/tutorial.html.
async def countdown(number, n):
start = time.time()
while n > 0:
print(f'{start:.4f} {time.time():.4f} {time.time() - start:.4f} {number} T-minus {n}')
await asyncio.slee... |
9f6d57830faf04eb31262271bbb7f9ddbe372f8b | sourcecodenight/finance-plan | /utility/reducingemi.py | 749 | 3.96875 | 4 | # Formula for Bank EMI
# EMI = [P x R x (1+R)^N]/[(1+R)^N-1]
# take R = R/1200 instead of R/12
print("Let's calculate your Bank's EMI!")
principal_amount = float(input("Enter your principal amount: "))
annual_rate_of_interest = float(input("Enter your annual rate of interest: "))
loan_tenure = int(input("Enter the nu... |
c7684b3a0b9c5f62c3d418fcf7c0e5cf1707f548 | jlicht27/cmps1500 | /Templates from class/bst.py | 3,034 | 4.0625 | 4 | class TreeNode:
def __init__(self, data):
self.data=data
self.left=None
self.right=None
def print_tree(T, indent=0):
if T != None:
print_tree(T.right, indent+4)
print (indent*" ", T.data)
print_tree(T.left, indent+4)
# find the minimum... |
7b53d5253fd6a6cbfd04d6bce68704ae469612a5 | jlicht27/cmps1500 | /lab6/timexample.py | 734 | 4.1875 | 4 | import time #import a module for working with time
#START THE PROGRAM
t = time.time() #read current time, in seconds since the begining of time
print(t)
t_nice = time.ctime(t) # convert time reading into human format
print(t_nice)
time.sleep(1) #pause execution for 1 second, just for the sake of examp... |
75ae69e13c4ed443ac4b165bdf2ae4b99a0d273f | jlicht27/cmps1500 | /lab4/lab4pr0.py | 1,161 | 4.28125 | 4 | '''Jonathan Licht
'''
majors = {'Harry': 'Computer Science','Hermoine': 'Mathematics', 'Ron': 'English'}
def look_up(d): #input a name and prints major
name = input('Enter a name: ')
if name in d.keys():
print(d.get(name))
else:
print('Not found.')
def add(d): ... |
e09bdea1956b6247944874adae2414b199685c30 | jlicht27/cmps1500 | /Templates from class/queue.py | 814 | 4.03125 | 4 | class QueueNode:
def __init__(self, data = None, nextNode = None):
self.data = data
self.nextNode = nextNode
class Queue:
def __init__(self):
self.head = None
self.tail = None
def append(self, x):
n = QueueNode(x)
if(self.head == None):
self.head ... |
61f487e5f2dda846924cffa90cc745cc13decc77 | jlicht27/cmps1500 | /Midterm practice/test4.py | 189 | 4.03125 | 4 | string = 'qwertyuiop'
def find(s):
letter = input('Please input character: ')
if letter in string:
return s.index(letter)
else:
return -1
print(find(string))
|
e737d97d81b9c23838ff43016f261245dab4d87a | jlicht27/cmps1500 | /lab1/lab1pr3.py | 1,648 | 4.1875 | 4 | initial_date = str(input('Please enter date in MM/DD/YYYY format: '))
if initial_date[5] != '/': #if days or months is messed up
if initial_date[2] != '/': #if months is 1
month = initial_date[0:1]
month = '0' + month
if initial_date[4] != '/': #if months is 1 and day is 1
day =... |
e8f85a7220a637f88aaee6ed7a7546a687a80fe8 | Alex-Villa/Lab2 | /Lab2Final.py | 6,071 | 4.09375 | 4 | def merge(arr, l, m, r): #merge sorts the converted linked list now a python list and applys merge sort to sort from big counter value to small counter value
n1 = m - l + 1
n2 = r - m
# create temp arrays
L = []
R = []
# Copy data to temp arrays L[] and R[]
for i in range(0, n1):
L.a... |
63e51a0d78d74cb44aab57b025a4fd59ea65d520 | bellabf/basicalgebraanalysis | /tp1_baa.py | 3,135 | 4.5625 | 5 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 10:09:08 2020
@author: b20030461
"""
import numpy as np
import matplotlib.pyplot as plt
def tutorial():
#first steps with matrices in python
a = np.array([1, 2, 3]) # just a simple vector
print("This is just a simple vector", a)
b = np.a... |
a3c4fee7604383d11ae5bc8fd4f8a290b5f2b1e5 | marrem96/macke | /main2.py | 512 | 3.640625 | 4 |
def yrange(n):
i = 0
while i < n:
yield i
i += 1
mygenerator = (x*x for x in range(3))
for i in mygenerator:
print(i)
print(i)
print("****")
for i in mygenerator:
print(i + i + i)
#ADDED SOME DUMMY CODE HERE
#ADDED SOME SECOND DUMMY CODE HERE
#CHANGED THIRD DUMMY DATA ROW
#A... |
790cf94e42001afdaabbe9dc31d1eb7fa8c4973f | vrushal2000/Teletrivia | /Teletrivia/z3.py | 2,558 | 4.0625 | 4 | x = 0
score = x
print("COME ON! You can do it last level to go...ALL THE BEST!")
# Question One
print("An oscillator for an AM transmitter has a 100μH coil and a 10nF capacitor. If a modulating frequency of 10 KHz modulates the oscillator, find the frequency range of the side bands.")
answer_1 = input("a)149 KH... |
bd67f61767f880ea24fe725e745749f0dd420981 | vrushal2000/Teletrivia | /Teletrivia/x2.py | 2,598 | 3.84375 | 4 | x = 0
score = x
# Question One
print("A modulating signal m(t)=10cos(2π×103t) is amplitude modulated with a carrier signal c(t)=50cos(2π×105t). Find the modulation index, the carrier power, and the power required for transmitting AM wave")
answer_1 = input("a)1.5\nb)0.2\nc)1.8\nd)1\n:")
if answer_1.lower() == "... |
96e746cbaae8b3acb575f963ba4bc2d43fda57c0 | michelle294/dictionary.py | /dictionary.py | 2,146 | 4.28125 | 4 | #colllection which is unordered
#changable and indexed
student={
"name" : "James",
"email" : "james@gmail.com",
"phone_no" :"0700707722",
}
print(student)
#accessing items
x=student['email']
print(x)
print(student['name']
#get() Returns the value of the specified key
y=student.get('email')
p... |
14050320d61c7a8aa40faef7d31cc88c9d3bedd1 | sixsGod/study | /python/打印小星星.py | 267 | 3.9375 | 4 | row = 1
# 循环小星星
while row <= 5:
print("*" * row)
row += 1
# 循环嵌套打印大星星
row = 1
# 循环行
while row <= 5:
col = 1
# 循环列
while col <= row:
print("★", end="")
col += 1
print("")
row += 1
|
5961d0a6cd302c835c1760507b08009ab9f1b109 | androidlz/rs | /myroot/basedcf/ItemBasedCF.py | 4,524 | 3.984375 | 4 | import math
from operator import itemgetter
'''
性能:适用物品数明显小于用户数的场合(预算不足的情况)
1.计算物品之间的相似度
2.根据物品之间的相似度和用户历史行为给用户生成推荐列表
'''
# 基于物品的协同过滤
class ItemBasedCF:
def __init__(self, train_file, test_file):
# 训练数据
self.train_file = train_file
# 测试数据
self.test_file = test_file
self.read... |
90e270a7b7d97cb2c2119d1930c9823b53a2688b | androidlz/rs | /myroot/tensorflow/linear_movie.py | 3,753 | 3.578125 | 4 | """ Simple linear regression example in TensorFlow
This program tries to predict the number of thefts from
the number of fire in the city of Chicago
Author: Chip Huyen
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
cs20si.stanford.edu
"""
from __future__ import absolute_import
from __future__... |
5358984f873c527e839d9739045632d4388bdd8a | pashupati123/coding-challenge | /weekly/cwc1/image_matcher.py | 2,252 | 4.125 | 4 | #!/bin/python3
import os
#
# Complete the 'countMatches' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING_ARRAY grid1
# 2. STRING_ARRAY grid2
#
def search_grid(grid1, grid2, i, j):
"""
Searches the grid horizontally and vertically to... |
6698decdbd89b79c4c9b5de5366b7c691b8abe36 | mawxder/project_euler | /problem2.py | 509 | 3.796875 | 4 | # By considering he terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
a, b = 0, 1
storage = 0
# FIbonacci sequence using multiple assignent:
# https://stackoverflow.c... |
2db35e932760ff22e2e51b0117972ab996d12cb4 | marcduby/MachineLearningPython | /Introductions/Socratica/so202primeNumbers.py | 407 | 4 | 4 | import time
def is_prime_v1(n):
"""function to indicate if a number is prime"""
if n == 1:
return False
for divisor in range(2, n-1):
if n % divisor == 0:
return False
return True
# get start time
time0 = time.time()
for n in range(1, 30):
print(n, is_prime_v1(n))
tim... |
f72d8066694c7bf907444802916ac5fd40433b32 | archie-casey-8/recruitment_platform | /archive/cv_uploader2.py | 2,823 | 3.515625 | 4 | import tkinter as tk
from tkinter import filedialog
from tkinter import *
class MyWindow(tk.Frame): # NP - Better naming
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.first_name=Label(self, text = '... |
5c76b08dc3c875091720dbf733be9a7f395d59dc | paolithiago/LivroPythonParaAnaliseDados | /USandoDateTimesPg70.py | 1,890 | 4.21875 | 4 | **Inicio Subtema Datas e Horas**
Tabela de Horas
<img alt="Colaboratory logo" width="40%" src="https://user-images.githubusercontent.com/54008103/92027902-9233ab80-ed39-11ea-9808-54ee71cf56de.jpg">
A partir da pagina 70 do livro de Python temos o sub tema Data e Horas - que refere-se ao modulo embutiod chamado da... |
3d020b9f396321316a1b40a51ca053a5f6419456 | VivianVriezekolk/GameYahtzee | /players.py | 1,462 | 3.53125 | 4 | class Player():
def __init__(self):
self.name = ''
self.amount_of_throwns = 0
self.player_number = 0
self.total_score = 0
self.UPPER_SECTION = {
'ones': None,
'twos': None,
'threes': None,
'fours': None,
'fives': No... |
39d647d1f06126bbf9faa82d13f48ec3eae1a5db | satyamverma95/Python_Interview_Perp-DS-and-Algo- | /Graph/Graph_Adj_Matrix.py | 1,074 | 3.765625 | 4 | class Graph:
def __init__( self, size ):
self.adjMatrix = []
#Initializing the adjacency matrix in Python
for i in range ( 1, size + 1 ):
self.adjMatrix.append( [0] * size )
#Stroing the size for futhter reference
self.size = size
def addE... |
3b371932684f57248385e516f595118c6deeb10f | satyamverma95/Python_Interview_Perp-DS-and-Algo- | /Sorting/MergeSort_implementation.py | 1,177 | 4.09375 | 4 | import math
def mergeSort ( array ):
if ( len ( array) == 1):
return ( array )
lenght = len(array)
middle = math.floor ( lenght / 2)
leftArray = array [:middle]
rightArray = array [middle:]
#print ( "Left Array", leftArray )
#print ( "Right Array", rightArray )
return ( megre( mergeSort(... |
cac801a0128ea83aa290609716b8d515cd71e009 | satyamverma95/Python_Interview_Perp-DS-and-Algo- | /Hash Tables/HashTables_Implementation.py | 1,457 | 3.875 | 4 |
class HashTable :
def __init__ ( self, size ):
self.array = [ None ] * size
def _hash ( self, key ): #private Property of class
hash = 0
for index in range ( len ( key ) ):
hash = ( hash + ord( key[index] ) * index ) % len( self.array )
return hash
def set ( self, key, value ):
... |
0b37e029762b42236d443c058efd8fe3806095cb | dschonholtz/ARC | /src/models/Groups/Grouper.py | 5,974 | 3.671875 | 4 | """
This class is the base class for all grouping algorithms
With the data that one of the sub classes of this class produces one should be able to layer groups over a frame
and display that to the user
To do this, this class will create several frames relating to each type of possible group.
Each of those frames wil... |
059b280684505326b52f062ff47d8e359edefa8d | p8858xp/portfolio | /python/assignment6/ParkPaul_assign6_part2.py | 6,163 | 4.125 | 4 | #Paul Park
#Assignment 6
#part 2a
#Intro to Programming
import myfunctions
import random
while True:
attempts = int(input("How many problems would you like to attempt? "))
if attempts <= 0:
print("Invalid number, try again\n")
else:
break
while True:
size = int(input("How wide do you w... |
c958cf38c1781d853846229b026de334f1087d81 | p8858xp/portfolio | /python/assignment4/ParkPaul_assign4_problem1.py | 2,094 | 4.15625 | 4 | #Paul Park
#Assignment 4 problem 1
#Intro to Programming
import random
#prompt the user to enter the number of sides of the first die
die_number = int(input("How many sides on your dice (4-20)? "))
#if the user enters an invalid number keep asking the user to choose a valid size value
while die_number < 4 or die_num... |
226f5bc56223a945703555810d391abd41768776 | p8858xp/portfolio | /python/assignment8/ParkPaul_assign8_part3.py | 4,732 | 3.84375 | 4 | #Paul Park
#Assignment8part 3
#Intro to Programming
import random
cards = ['10 of Hearts', '9 of Hearts', '8 of Hearts', '7 of Hearts', '6 of Hearts',
'5 of Hearts', '4 of Hearts', '3 of Hearts', '2 of Hearts', 'Ace of Hearts',
'King of Hearts', 'Queen of Hearts', 'Jack of Hearts', '10 of Diamon... |
f096ad8bdaeedc6eba86eeaaf98da9696f211629 | p8858xp/portfolio | /python/assignment3/ParkPaul_assign3_problem3.py | 5,283 | 4.34375 | 4 | #Paul Park
#Assignment 3 problem 3
#Intro to Programming
#ask user to enter a month and a date
month_number = int(input("Enter a month (1-12): "))
day_number = int(input("Enter a day (1-31): "))
#if the month or day entered if not within the range possible print it's not a valid date
if month_number > 12 or month_num... |
b3ddcb8a3cd07e5481978772c418af010c1739f2 | guodunyu/it_shop | /hm_syou.py | 282 | 3.609375 | 4 | class person(object):
def __init__(self):
self.name = "guo"
self.__age = 25
def __run(self):
print("我爱你")
def eat(self):
self.__run()
print(self.__age)
guo = person()
print(guo.name
)
guo.eat()
print(guo._person__age)
|
4be3ec26f523b21b3c424317cc8058674dc45625 | masterfung/RocketU-Exercises | /Week 1/w1d4.py | 3,177 | 4.21875 | 4 | __author__ = '@masterfung'
#Today is about OO Programming
# Not Great Code:
# class Car(object):
# speed = 0
# direction = 'left'
# color = 'red'
#
# some_car = Car()
# print Car()
# print some_car.direction
# other_car = Car()
# other_car.direction = 'right'
# print other_car.direction
#Improving
# class Car(o... |
c6a51d1f16aff6a4dbd4101c5358699f6737fc8e | masterfung/RocketU-Exercises | /Week 2/w2d3.py | 2,005 | 3.640625 | 4 | import os
import re
import csv
__author__ = '@masterfung'
# def create_directories(dirname):
# for name in dirname:
# os.mkdir(name)
#
# def create_nested_directories(dirname):
# for name in dirname:
# os.mkdir(name)
# os.chdir(name)
#
#
#
# dirnames = ['happy', 'brave', 'energy']
# create_directories(dirname... |
4781ff1dfe8eba5a480acac98d9b441c034ef6b9 | masterfung/RocketU-Exercises | /Week 1/Building Take 2/apartment.py | 727 | 3.6875 | 4 | from renters import Renter
__author__ = 'htm'
class Apartment(object):
def __init__(self, building, unit, rent, sqft, num_bed, num_bath):
self.building = building
self.unit = unit
self.rent = rent
self.sqft = sqft
self.num_bed = num_bed
self.num_bath = num_bath
self.renters = []
self.building.apartm... |
7ccbc88dfc8622fbcbf842333ac29e7eb4dbbbe4 | boy07132004/CS50 | /orm_api/classes0.py | 1,262 | 3.703125 | 4 | class Flight :
counter = 1
def __init__(self,origin,destination,duration):
self.id = Flight.counter
Flight.counter +=1
self.passengers = []
self.origin = origin
self.destination = destination
self.duration = duration
def print_info(self):
print(f"Flig... |
afaaacef3865e38963416185ad3eeae37d65da33 | jodaruve/PreInformeConAcum | /do while 100_1.py | 97 | 3.875 | 4 | ## numeros de 100 a 1 de 3 en 3
num=100
while True:
print (num)
num=num-3
if num < 1:
break |
b5839e439769b6e7fb55934d209afa0052e74659 | jodaruve/PreInformeConAcum | /while 1_30.py | 113 | 3.734375 | 4 | ## nmeros pares de 1 a 30
print("Los nmeros pares de 1 a 30 son:")
sum=0
while sum<30:
sum=sum+2
print(sum) |
a84ca6e08322bbbe0c698e040753d08ddf3d4a67 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 1st/page 59.py | 350 | 4.03125 | 4 | import turtle
#function to create a square
def draw_square(side_length):
for i in range(4):
turtle.forward(side_length)
turtle.left(90)
counter=0
while counter<90: #creating 90 squares
draw_square(100) #calling function
turtle.right(4) #moving to 4 degree angle of the prevous square
c... |
8364e26a78986829a72b9b5714fffc11c147f401 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 1st/Prime number.py | 432 | 4.1875 | 4 | def is_prime1(n):
if n<2:
return False
prime=True
for x in range(2,n):
if n%x==0:
print(n,"is divisible by",x)
prime=False
return prime
while True:
number=int(input("Please enter a number "))
if number==0:
break
prime=is_prime1(number)
if ... |
c9642ce432feaca1d86e5851deaf45d53c2975e9 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 3rd/Page 62.py | 389 | 4.03125 | 4 | def is_balanced(input_str):
s=list()
for ch in input_str:
if ch=='(':
s.append(ch)
if ch==')':
if not s:
return False
s.pop()
return not s
if __name__=="__main__":
input_str=input()
if is_balanced(input_str):
print(input_st... |
437dc2d4421ddc8a3d78c72762bac99925f1cf0e | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 2nd/Page 37.py | 808 | 4.4375 | 4 | class Car: #creating a class
#variables defined
name="" #this are of no use
color="" #this is of no use
def __init__(self,n,c):#when any object is created , this __init__ method is called
self.name=n #here "self.name" object is assigned with "n' attribute value
self.color=c #here "self.... |
7ce1af66577db721253ef3fed46cb76fbf1929a0 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 3rd/Page 101 fibonacci.py | 259 | 4.25 | 4 | def fibonacci(n):
print("Trying to find fibonacci for",n)
if n==1 or n==2:
return 1
return fibonacci(n-2)+fibonacci(n-1)
if __name__=="__main__":
x=int(input("Check with a number"))
print(x,"th fibonacci number is ", fibonacci(x)) |
52148d2d90ca8aadeb526b0110f12c056786e777 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 2nd/Page 67.py | 700 | 4.0625 | 4 | class Vehicle:
"""Base class for all vehicles"""
def __init__(self,name,manufacturer,color):
self.name=name
self.manufacturer=manufacturer
self.color=color
def drive(self):
print("Driving",self.manufacturer,self.name)
def turn(self,direction):
print("Turning",s... |
b216de1ac9c2abc0956b94630809cacc01549934 | mitul3737/My-Python-Programming-Journey-from-Beginning-to-Data-Sciene-Machine-Learning-AI-Deep-Learning | /Python diye Programming sekha 3rd/Bubble sort.py | 281 | 4.03125 | 4 | def bubble_sort(L):
n=len(L)
for i in range(0,n):
for j in range(0,n-i-1):
if L[j]>L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
if __name__=="__main__":
L=[6,1,4,9,2]
print("Before sort:",L)
bubble_sort(L)
print("After sort: ",L)
|
37dc43601f18dd80ea6b82dc5c62f3064880b0ed | kennyxue/PythonAllStack | /A_1_/1.2.3.py | 101 | 3.578125 | 4 | #coding:utf-8
h = " hello "
print(h.strip())
s = 'you need python'
print('*'.join(s.split())) |
13007a7d29c4632dd7f4e2d9e6ff96e18f923c2b | sine69/password_generator | /main.py | 810 | 3.9375 | 4 | """Password generator"""
import random, string
from os import system
from time import sleep
CHARACTERS = string.hexdigits + string.punctuation
def generate_password(length: int, chars: string):
"""Generate password, return string"""
arr = [random.choice(chars) for _ in range(length)]
... |
5fffd1ab2048e0308d7903d2e42fc7ffae1fb86d | Answer1994/Code-Exercise | /python基础教程笔记/note_3使用字符串.py | 1,356 | 3.65625 | 4 | # -*- coding: utf-8 -*-
#基本字符串操作(所有标准的序列操作对字符串同样适用如索引,分片,乘法成员资格,长度,最值,但字符串是不可变的,所以不能进行分片赋值)
#字符串格式化
formation = 'hello,%s,%s,enough fpr ya?'
values = ('world','hot')
print formation%values
#find用于在较长字符串中查找子字符串
#join用于添加元素
seq = ['1','2','3','4','5'] #这里不能用seq=[1,2,3,4,5]因为需要添加的元素必须是字符串
sep = '+'
print sep.join(seq)... |
9cfb94ca602fab6da28d9d098323d9e029d8c7f7 | ZaneWarner/Algorithms-I | /2-QuickSort/Quicksort.py | 2,089 | 4.40625 | 4 | #This is the second coding assignment for Algorithms I from Stanford Lagunita
#The task is to implement quicksort using three different pivot selection schemes
#With the partition subroutine implemented as specified in the lecture
#And count the number of comparisons made for each choice of pivot
#when sorting a provid... |
6bfe238ad35fe6510e03d256d6f8ba94611d9421 | leongjinghao/JourneyPlanner | /PriorityQueue.py | 5,346 | 4.15625 | 4 | class PriorityQueue:
# binary heap implementation for priority queue
heap = []
# constructor for priority queue class
def __init__(self, start):
# reset on every construct
self.heap = []
# insert dummy node on the first index, to facilitate subsequent math operations
se... |
765b742ff26b4490118159a35fc98896bf4a42d4 | TGathman/Codewars | /6 kyu/Row of the Odd Triangle/Row of Odd Triangle.py | 212 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 9 February 2020
def odd_row(n):
if n == 1:
return [n]
if n > 1:
a = n * (n - 1) + 1
return [a + i for i in range(0, 2 * n, 2)]
|
52d8556ff505985f947a9c031245bc103ab3c469 | TGathman/Codewars | /7 kyu/String Doubles/String Doubles.py | 512 | 3.609375 | 4 | # Pyhton 3.8, 26 September 2020
from itertools import groupby
def doubles(text):
if len(text) == 0:
return ''
if len(text) == 1:
return text
if len(text) == 2:
return '' if text[0] == text[1] else text
else:
new_text = ''
for key, group in groupby(text):
... |
9d032e3ee136b6f04d41c0631cf85a168887d778 | TGathman/Codewars | /7 kyu/Shortest Word/Shortest Word.py | 174 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 18 March 2020
def find_short(s):
temp = set()
for i in s.split():
temp.add(len(i))
return min(temp)
|
697ba78a4fcf8b4b7d779c5156ecb4ad69f00a80 | TGathman/Codewars | /5 kyu/Moving Zeros to End/Moving Zeros to End.py | 348 | 3.796875 | 4 | # Python 3.8, 20 March 2020.
def move_zeros(array):
zeros = 0
new_array = []
for i in array:
if i is False:
new_array.append(False)
elif i == 0 or i == 0.0:
zeros += 1
else:
new_array.append(i)
zeros_array = [0 for i in range(zeros)]
ret... |
47cae569596f193c6a89972afcb8630eb35fce48 | TGathman/Codewars | /8 kyu/Area or Perimeter/Area or Perimeter.py | 158 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 9 February 2020
def area_or_perimeter(l , w):
if l == w:
return l * w
return 2 * l + 2 * w
|
158b0e11c22069eb4e87ee4841b77dfa9928adf9 | TGathman/Codewars | /7 kyu/Sum of Numbers/Sum of Numbers.py | 186 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 20 March 2020
def get_sum(a, b):
if a == b:
return a
return sum(range(b, a + 1)) if a > b else sum(range(a, b + 1))
|
8da3892dffd558070e62e2af50e3c1098f85d53e | abhijeetpnwr/Python_GUI | /pulldownmenu.py | 729 | 3.71875 | 4 | # Pull down menu are attached to a parent menu (using add_cascade), instead of a toplevel window.
from Tkinter import *
root = Tk()
def hello():
print "hello!"
def save():
print "Ohk"
# create a toplevel menu
menubar = Menu(root)
pulldownmwnu = Menu(menubar)
pulldownmwnu.add_command(label="open", command=he... |
93c58266f19fed678675caf6f8e2d9ac3484a073 | Ervizal/Ervizal-Buana_I0320035_Andhika_Tugas3 | /I0320035_Soal2_Tugas3.py | 1,263 | 3.8125 | 4 | print("==========================================")
print("==== Identitas Diri dengan Dictionary ====")
print("==========================================")
#Pembuatan dictionary
My_identity = {"Nama":"Ervizal Buana", "Hobi 1":"Berenang", "Hobi 2":"Bermain gitar", "Hobi 3":"Memanah",
"Sosmed 1":"instagram @eb_putr... |
a92687822f6a2c1994c6ad3d24739e39e6bb24d8 | jhbecares/chromophonia | /histogram/compare_histograms_1D.py | 5,395 | 3.75 | 4 | # -*- coding: utf-8 -*-
# cv2.calcHist(images, channels, mask, histSize, ranges)
# images: This is the image that we want to compute a histogram
# for. Wrap it as a list: [myImage].
# channels: A list of indexes, where we specify the index of the
# channel we want to compute a histogram for. To co... |
3bfa23aa7241fed931571abe725fe77de5b1c422 | jhbecares/chromophonia | /histogram/color_histogram_1D.py | 3,026 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# cv2.calcHist(images, channels, mask, histSize, ranges)
# images: This is the image that we want to compute a histogram
# for. Wrap it as a list: [myImage].
# channels: A list of indexes, where we specify the index of the
# channel we want to compute a histogram for. To co... |
b4f3b2830c44b374b5d6baca47a9d73b3378850f | Ekedani/My-Labs-Python | /Lab-6/Lab_6.py | 914 | 3.8125 | 4 | def func_g(param):
sum_n, sum_d = 0, 0
for k in range(0,11):
num_n = param**(2*k + 1)
den_n = factorial(2*k + 1)
sum_n = sum_n + num_n / den_n
for k in range(0,11):
num_d = param**(3*k)
den_d = factorial(3*k)
sum_d = sum_d + num_d / den_d
result = sum_n / ... |
e53eeec266effa1acadc0e953c0f53831099a489 | Iranox/masterthesis | /workbench/copy_checker/src/image_processing/templatematching.py | 1,813 | 3.90625 | 4 | import cv2
import numpy as np
import os
"""It has mainly three parts.
Image pre-processing
segmentation and feature extraction
recognition
In case of Image pre-processing , you have to undergo the image through different processes to remove noises, for skew-correction and binarization.
It mainly involve... |
206b1dba5f03ec3edb38c0a9ccf051422e84bdf9 | DouweRaat/python3 | /Functies, n x hello world.py | 108 | 3.5 | 4 | def helloworld(n, string):
for i in range(n):
print(string, i)
helloworld(int(input()), input()) |
71bc5d12e9dcf144a070441f9709dfcdf391e069 | p83218882/270201032 | /lab2/example4.py | 142 | 3.890625 | 4 | # F = C * 1.8 + 32
Celcius = float(input('write any Celcius degree:'))
Fahrenheit = float(Celcius) * 1.8 + 32
print(str(Fahrenheit) + " F") |
e224b440c2bff5a1f14a82e0dc5b63886068e11b | p83218882/270201032 | /lab8/example4.py | 508 | 3.90625 | 4 | # lab8 ex4.1
def binary_to_dec(a):
k = 0
a = str(a)
for i in range(len(a)):
k += int(a[-len(a) + i])*(2**(len(a)-i-1))
print(f"{a}'s binary to decimal demonstrated state is\n{k}")
a = str(input("enter binary number >>> "))
binary_to_dec(a)
# lab8 ex4.2
def dec_to_binary(a):
c = ""
whil... |
e3ba323f94745f35e6e5b4890e9049b851a5d856 | p83218882/270201032 | /lab4/example1.py | 180 | 3.546875 | 4 | if 0 <= a < 10:
print(a)
elif a == 10:
print(1)
elif 10 < a <= 99 :
print((a % 10) + ((a - (a % 10)) / 10))
elif a >= 100:
print((a % 10) + ((a - a % 10) / 10) % 10) |
9579366d450f626b1fd6953e919bd557b4fb585f | p83218882/270201032 | /myownexamples/ex3.py | 363 | 3.921875 | 4 | promise_book_number = int(input("plz say books number with dsc: "))
promise_book_price = int(input("promise book price: "))
total_cost = float(input("total cost: "))
without_dsc_book_price = (total_cost - promise_book_price)
without_dsc_book_number = (without_dsc_book_price)/19.99
print("withour discount book num... |
08de95257e627e90a72b063d3326e3ce8d188f4c | tanthanadon/HandChallenge | /game.py | 3,647 | 3.59375 | 4 | import random
from player import Player
class Game(object):
# Initial Game object
def __init__(self):
self.user = Player()
self.ai = Player()
self.predictor = Player()
self.non_predictor = Player()
self.ending = False
# Validate left and right hand from the l... |
6ba8ef5bc22f1d51f215f9275ce109cbbed6ee8f | jwsadler58/pythonista | /tictactoe/tictactoe2.py | 9,775 | 3.625 | 4 | import random
import json
# This game engine is based on Q Learning (a form of Reinforcement Learning)
#
# TicTacToe basics
# The board is numbered
# 123
# 456
# 789
# and represented as a list of length 10, where the zeroth entry is unused
# where 0 is an empty square, 1 is a computer-held square, and -1 is a player-... |
e4fd438b18bf11baf6c39dd7eee31ce3b61bffc9 | btrevizan/pybtree | /pybtree/pysearch.py | 2,307 | 4.3125 | 4 | """Search algorithms adapted from https://github.com/btrevizan/ordernsearch.git."""
def def_key(x):
"""Return the element to compare with.
Keyword arguments:
x -- object of any kind
"""
return x
def search(sequence, n, key=def_key, how='binary'):
"""Search an element n in a sequence.
... |
4fe310450742fcda49c3d75293c5f8e8fd5b3424 | ydodeja365/LabWork | /Sort/quick.py | 429 | 3.65625 | 4 | def quicksort(l,s,e):
if s<e:
ind=partition(l,s,e)
quicksort(l,s,ind-1)
quicksort(l,ind+1,e)
return
if s==e:
return e
def partition(l,s,e):
pivot=l[e]
index=s-1
for i in range(s,e):
if l[i]<=pivot:
l[i],l[index+1]=l[index+1],l[i]
index+=1
l[e],l[index+1]=l[index+1],l[e]
return index+1
def main... |
f74f5f65044c8e7df9e967668ee27fbed3f8b3aa | green-fox-academy/ithomas91-1.0 | /Else/python/python_tutorial/guess_game.py | 305 | 4 | 4 | secret_word = "developer"
user_guess = ""
user_HP = 5
while user_guess != secret_word:
user_guess = input("Enter a guess!")
user_HP -= 1
print("Wrong answer, guess again! You have ", user_HP, "HP left.")
if user_HP == 0 :
print("Sorry, you DIED!!!")
break
print("U WON") |
2bdb9017285d9d6d12583097e8b701e8930eb822 | DigitalPresales/Cloud-Computing | /Python4.py | 313 | 4.09375 | 4 | ##Create a file (samplefile.txt) on your machine manually and note the path of the file.
file = open("<file path of samplefile.txt>", "a")
file.write("New customer Bank of London was added successfully")
file.close()
#open and read the file after the appending:
f = open("samplefile.txt", "r")
print(f.read())
|
f51223b076f8ae68822cab8e1c9facd1a27b814d | ivanedo00/2BATX | /github2ivanmartinez.py | 363 | 3.828125 | 4 | rectangulo = []
def rectangulo ( param1,param2,caracter):
for i in range(param1):
for g in range(param2):
print caracter,
print ""
altura = int(input("introduce la anchura del rectangulo"))
anchura = int(input("que altura tiene el rectangulo"))
caracter = raw_input("en que caracter quiere realizar el rectangulo... |
61babd5c2eeed691957cf2e7e574e3293558c45f | taorui666/test | /for7.py | 355 | 3.875 | 4 | """ZZ
"""
s=int(input("请输入:"))
w=int(0)
for j in range(s):
a = 0
for i in range(s):
a += 1
print("%5d" % int(a + w),end="")
w +=1
print(end="\n")
#s=int(input("请输入:"))
#a = 0
#for j in 0 1 2 :
# a += 1
# for i in 0 1 2:
# a += 1
# print("%2d" % a,end=""... |
bc2960caa0b0928da585bd6e220d8b13f6e7ad5c | taorui666/test | /for6.py | 127 | 3.96875 | 4 | c=int(input("请输入"))
for j in range(c):
for i in range(1,c+1):
print("%3d" % int(i + j) ,end="")
print()
|
1551006c0ba0d704031ecf178ee4e50b23e82bb0 | taorui666/test | /int.py | 124 | 3.78125 | 4 | #!/usr/bin/python3
s=input("Please Input Int:")
if isinstance(s,int):
print(chr(s))
else:
print("请输入整数")
|
f6ccc3a37c3841acfcd56206ccb9e74b3b39d78e | koushikruidas/interviewbit | /array/diagonal_array.py | 708 | 3.640625 | 4 | class Solution:
def diagonal(self, A):
n = len(A[0])
res = []
row = []
# k = 0
# m = len(A)
row.append(A[0][0])
res.append(row)
for k in range(1,n):
row = []
for i in range(k, -1, -1):
for j in range(i, -1, -1):
... |
f3eded379941546753a5d803bc8aa8689212e930 | koushikruidas/interviewbit | /math/decimal_to_binary.py | 361 | 3.8125 | 4 | import math
class Solution:
# Takes an Integer number A
# Returns a list
def __init__(self):
self.list = []
def int_to_binary(self, A):
if A == 0:
return
self.list.append(str((A % 2)))
self.int_to_binary(A // 2)
sol = Solution()
sol.int_to_binary(9)
sstr ... |
793fd2fc1aaf3039831f7e521f40f355aaacb598 | rahulcode22/Worldcodesprint-9-hackerrank- | /Grading Student.py | 270 | 3.609375 | 4 | #!/bin/python
import sys
n = int(raw_input().strip())
for a0 in xrange(n):
grade = int(raw_input().strip())
# your code goes here
y=(grade//5+1)*5
diff=y-grade
if diff<3 and (grade+diff)>=40:
print grade+diff
else:
print grade
|
8214b9082323f1b407ad0cbef25b22937f75479e | purepython/lpthw | /ex21/ex21ec4.py | 457 | 4.03125 | 4 | # Exercise 21
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
pri... |
e6abddd6990f34349d7b8f9dfd1fa2e38c8c8900 | gvitorguimaraes/CEV-Python | /CEV-Python/ex061.py | 261 | 3.828125 | 4 | print("============ PA ============")
x = int(input(">> Digite primeiro termo: "))
r = int(input(">> Digite a razão: "))
pa = x
i = 1
print("============================\n")
while i <= 10:
print(f" {pa} → " ,end='')
pa += r
i += 1
print("FIM")
|
3d749e54b29be0b224e0987911a9e05fb94b4799 | gvitorguimaraes/CEV-Python | /CEV-Python/ex040.py | 353 | 4.0625 | 4 | #Media de notas
nota1 = float(input("> Digite a primeira nota: "))
nota2 = float(input("> Digite a segunda nota: "))
media = (nota1+nota2)/2
print(f"> Sua média foi de {media} pontos")
if media >= 7:
print("> Você foi APROVADO!")
elif 6.9 >= media >= 5:
print("> Você está de RECUPERAÇÃO!")
else:
print(">... |
024113c6f456f17aaf596735c0f65a3a01829a93 | gvitorguimaraes/CEV-Python | /CEV-Python/ex058.py | 884 | 3.84375 | 4 | #Jogo Advinhação 2.0
from time import sleep
from random import randint
print("=-=-=-="*6)
print("= Jogo da advinhação 2.0 =")
print("=-=-=-="*6)
usuario = int(input("=> Tente adivinhar o número de 1 a 10: "))
print("=-=-=-="*6)
sleep(0.5)
maquina = randint(1,10)
tentativas = 1
if usuari... |
0ac6fdb739a0a46641b7785618bcbec697edac72 | gvitorguimaraes/CEV-Python | /CEV-Python/ex008.py | 251 | 3.640625 | 4 | #Conversor de distâncias
dMetro = float(input('Digite uma distância em metros: '))
print(f'{dMetro/1000}km')
print(f'{dMetro/100}hm')
print(f'{dMetro/10}dam')
print(f'{dMetro/0.1}dm')
print(f'{dMetro/0.01}cm')
print(f'{dMetro/0.001}mm')
|
dd7b7dc25f62ce490d5a9a2c6d0f1b64f17040ac | gvitorguimaraes/CEV-Python | /CEV-Python/ex055.py | 351 | 4 | 4 | #Ler o peso e indicar o maior e menor
maior = 0
menor = 0
for entrada in range(0, 5):
pesos = float(input(f"> {entrada+1}° peso: "))
if entrada == 1:
maior = pesos
menor = pesos
else:
if pesos > maior:
maior = pesos
if pesos < menor:
menor = pesos
print(f"\n> Maior peso {maior}Kg")
prin... |
95f02f203163f603d908cf867620df4b4605427c | gvitorguimaraes/CEV-Python | /CEV-Python/ex016.py | 153 | 3.859375 | 4 | from math import trunc
num = float(input('Digite um número real: '))
print(f'O numero digitado foi {num} e a sua porçao inteira é {trunc(num)}')
|
a4f791c1276af7d677cf1aff4cdaee6b0393960a | gvitorguimaraes/CEV-Python | /CEV-Python/ex062.py | 666 | 3.953125 | 4 | print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print("= GERADOR DE PA =")
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n")
pa = int(input(">> Digite o termo inicial: "))
r = int(input(">> Digite a razão: "))
i = 1
termos = 10
while i <= termos:
print(f" {pa} →", end='')
pa += r
i += 1
print(" Pausa!")
... |
60cb957d333b6d144db206fbe77e3305e33127c1 | gvitorguimaraes/CEV-Python | /CEV-Python/ex068.py | 1,073 | 3.65625 | 4 | from random import choice
print("==============================")
print("= Par ou Ímpar =")
print("==============================")
vitoria = 0
opUsuario = "x"
while True:
numUsuario = int(input("\n> Valor: "))
while opUsuario not in "PI":
opUsuario = str(input("> Par ou ímpar[P/I]: ")).upp... |
252e09826a9304e78a9f1f00726d29c125129b0c | gvitorguimaraes/CEV-Python | /CEV-Python/ex056.py | 758 | 3.765625 | 4 | #Analisador completo
femSub20 = 0
idadeTotal = 0
idadeAnt = 0
nomeVelho = 0
for x in range(0, 4):
print(f"\n=-=-=-=-= {x+1}° Pessoa =-=-=-=-=\n")
nome = input("=> Nome: ").strip()
idade = int(input("=> Idade: "))
idadeTotal = idadeTotal + idade
sexo = input("=> Sexo [M/F]: ").strip().upper()
if... |
71eb1cc6288553fa228653275321ee17cd1d6a35 | RguezElias/curso_python | /dc_acceder.py | 284 | 4.125 | 4 | #acceder a valores del diccionario
pizza = {'tipo':'vegetariana', 'costo':150, 'caliente':True}
print pizza['tipo']
print pizza['costo']
#acceder a todos los valores de un diccionario
print pizza.values()
#iterar valores en el diccionario
for valor in pizza:
print valor |
e49be12bf3416f50fedca6a05beb7d591e97134f | RguezElias/curso_python | /listas_eliminar.py | 293 | 3.515625 | 4 | #eliminar valores de listas por index
zoologico = ['tigre', 'rinoceronte', 'hipopotamo']
del zoologico[0]
print zoologico
#eliminar valores de listas por su valor
zoologico.remove('rinoceronte')
print zoologico
# determinar el longitud de la lista
print len(zoologico) |
f1d5b0f52c80faea6c8e109242bbe8105a1461f8 | RguezElias/curso_python | /strings.py | 368 | 4.09375 | 4 |
#string
animal = 'cocodrilo'
#numero de caracteres
print len(animal)
#primer caracter por medio de index
print animal[0]
print animal[1]
print animal[2]
print animal[3]
print animal[4]
print animal[5]
print animal[6]
print animal[7]
print animal[8]
#slice para tomar porcion de string
print ani... |
654e5d62208734e0152b7fa7139a53c390275889 | Sbbarse/ML-MODEL | /Titanic.py | 5,410 | 3.53125 | 4 | """
<a href="https://colab.research.google.com/github/Sbbarse787/Titanic-Data-analysis-and-ML-prediction/blob/master/Titanic.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
i... |
5bb42a3bb21934f87d331c0e71ff641f55aa78b4 | Winterflower/python-finance | /orderbook/orderbook.py | 779 | 3.515625 | 4 | __author__ = 'winterflower'
"""
Main class for the orderbook project
"""
class OrderBookTable:
"""
Data structure for holding orderbook data
"""
def __init__(self):
self.ID=[]
self.type=[]
self.bidask=[]
self.time=[]
self.size=[]
self.status=[]
s... |
c96a21bbedf954a3e91285bd95f735c64ec92091 | cvhs-cs-2017/sem2-exam1-lucasrosengarten | /Encrypt.py | 824 | 4.0625 | 4 | """Write a code that will remove vowels from a string and run it for the sentence:
'Computer Science Makes the World go round but it doesn't make the world round itself!'
Print the save the result as the variable = NoVowels
"""
def novowels(anystring):
newstring = ""
for ch in anystring:
a = ord(ch)
... |
31146ba40a13decf4e51eab4aff4d97bd3c2557a | pingyourid/learnpython | /practice/3/demo.py | 867 | 3.9375 | 4 | dogs = ["yellow dog", "black dog", "white dog"]
message = f"I have a dog which is a {dogs[1].title()}"
print(message)
dogs[1] = "blue dog"
print(dogs)
dogs.append("black dog")
print(dogs)
#------del
del dogs[0]
print(dogs)
dogs.pop()
print(dogs)
poped = dogs.pop(0)
print(dogs)
print(poped)
#del足够
cats = ["yellow... |
8ced2d08208f83e781e69073f157b52184504677 | pingyourid/learnpython | /practice/11/survey.py | 424 | 3.71875 | 4 | class Survey:
def __init__(self, question):
self.question = question
self.responses = []
def insert_response(self, response):
self.responses.append(response)
# self.responses
def report(self):
print(f'\n------------------------------\nYour question is {self.question}:... |
f5d8e443b11058da8994bbd213f08b7c66ce58af | josephsmartinez/python | /Topics/Files_Directories/os_walker.py | 565 | 3.703125 | 4 | import os
def list_files():
path = '.'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.txt' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
def list_directories():
path = '.'
folders = []
# r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.