blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
825b4222911020af48e4aac79d9a3cdd219ee97a | diksha12p/Data-Structures-ALgorithms---Spring-19 | /Assignment_1/Q4/farthestPair_Revised.py | 1,006 | 3.84375 | 4 | import time as t
def farthestPair(arr): # Function defined to calculate the farthest pair
if len(arr) == 0: # Ensuring that the array isn't empty
print('Operation can\'t be performed on NULL ARRAY!')
else:
current_min = current_max = 0
for i in range(0, len(arr)):
if arr[i] <= ... |
bdb75ca2ca15e0ed6d95da941c8d76f3ae68c1e0 | LingyeWU/unit3 | /Week28/q4.py | 393 | 3.828125 | 4 | # This script creates a class with two methods - get string and print string
class String():
def __init__(self):
pass # not sure if pass is the right one to use here
def getString(self):
self.string = input("Enter a string")
def printString(self):
return (self.string.upper())
# F... |
291f5e8911db593683bac0b86b95e0e20f634e7b | BR95ST/Python-Exercises | /stack.py | 650 | 3.84375 | 4 | class Stack:
def __init__(self):
self.stack = []
self.len_stack = 0
def push(self, n):
self.stack.append(n)
self.len_stack += 1
def pop(self):
if self.len_stack > 0:
self.stack.pop(self.len_stack -1)
self.len_stack -= 1
def top(self):
if self.len_stack > 0:
return self.stack[-1]
r... |
49e206c58a07526769d45368e2bfa1d037800978 | EdikCarlos/Exercicios_Python_iniciante | /ex_Tabuada3.0.py | 330 | 3.875 | 4 | while True:
n = int(input('Digite um número para ver sua tabuada (Digite 0 para finalizar): '))
print('-='*20)
if n == 0:
break
for c in range(1, 11):
mult = n * c
print(f'{n} x {c} = {mult}' )
print('-=' * 20)
print('\033[33mPrograma finalizado com sucesso! Obrigado por usar... |
39fd9fac8def1c3dc62650a02e6fac765e2da595 | lindaspellman/CSE111 | /W03 Calling Functions/scene.py | 7,075 | 3.671875 | 4 | import tkinter as tk
import random
import math
def main():
# The width and height of the scene window.
width = 800
height = 500
# Create the Tk root object.
root = tk.Tk()
root.geometry(f"{width}x{height}")
# Create a Frame object.
frame = tk.Frame(root)
frame.master.title("Scen... |
c4bb271df1cf83e4c07b728a5c95f12cafa79408 | daviemediato/Genetic-Algorithm | /Population.py | 1,423 | 3.53125 | 4 | from Chromosome import Chromosome
class Population:
def __init__(self, population_size=10, chromosome_length=2, chromosomes=None):
self.population_size = population_size
self.chromosome_length = chromosome_length
if(chromosomes == None):
self.population = [Chromosome(chromosome_... |
7d5ad7b009330ca51ab881a8cf6fab4b3a7cc10e | Debdisha/HACKTOBERFEST-2021 | /HealthMS/LifestyleRegister.py | 890 | 3.53125 | 4 | import datetime
def getdate1():
date=input(datetime.date)
return(date)
print("Welcome to Anik's Daily Directory")
list1={1:"Academic Activities",2:"Food Consumed",3:"Procrastinating"}
inp7=getdate1()
print("Date:-",inp7)
def getdate():
import datetime
return datetime.datetime.now()
print("Press 1 to ... |
57232365765772f11606534bee97f44310a3a78e | aegis-katoh/IoT | /Pulse/4.GentleChange_ex.py | 1,604 | 3.640625 | 4 | # This program is written in Python3
# Library to use GPIO
import RPi.GPIO as GPIO
# Library to get date
from datetime import datetime
import signal
import time
import csv
from os import path
# initial setting
# sampling frequency [Hz]
sampling_freq = 5
# show interval [sec]
interval = 10
wait_time = 1. / sampling_... |
c07a7be4d13ecf1ea33bdaa3610dad1b3d6e7815 | birune/learning-py | /やさしいpython/lesson9/sample3.py | 210 | 3.765625 | 4 | word0 = input("plz input First word")
word1 = input("plz input Second word")
word2 = input("plz input Third word")
print("一つ目の単語は{0}、二つ目は{1}、最後は{2}".format(word0, word1, word2)) |
f396d5a423b90b8ce1db486a9a0e2aea1fab86e2 | yurimalheiros/IP-2019-2 | /lista4/roberta/questao3.py | 530 | 3.78125 | 4 | #Função: "a partir do código 2",menor e maior valor da lista criada
#Autor: Roberta de Lima Ribeiro
while True:
lista = []
num = int(input('Digite um número: '))
while num != 0:
lista.append(num)
num = int(input('Digite um número: '))
print(lista)
menor= 9999
ma... |
e5aa04957c1bb3e07fa9fb7c8fe500acebc14ed9 | geektime-selfstudy/FromZeroToLearnPython | /src/func_test3.py | 154 | 3.5 | 4 | # 使用闭包函数求解线性方程
def a_line(a, b):
def arg_y(x):
return a * x + b
return arg_y
line = a_line(3, 5)
print(line(10)) |
9799c7b9e74107527c67bc7ae1f555a4f30225c8 | carolLiborio/python-fundamentos | /estruturas-dados/tuplas/tupla.py | 386 | 4.0625 | 4 | #criação de uma tupla com as categorias dos Jedi
categorias = ("Youngling", "Padawan", "Knight", "Master")
#exibir a tupla inteira
print(categorias)
#exibir o segundo item da tupla
print(categorias[1])
#usar um índice negativo para exibir o último item da tupla
print(categorias[-1])
#exibir cada item da tupla us... |
b5c2440692ac332dec512e930d8a8cb88c38d8bb | jennyChing/leetCode | /21_mergeTwoLists.py | 1,059 | 4.09375 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
param is two lists
return a ListNode
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
... |
593ba9dd6905a3eae15f43414ea0b37027f1d98c | wangJmes/PycharmProjects | /pythonProject/pythonStudy/chap2/demo6.py | 251 | 3.828125 | 4 | # 练习
# 开发者:汪川
# 开发时间: 2021/3/4 17:42
f1 = True
f2 = False
print(f1, type(f1))
print(f2, type(f2))
# 布尔值可以转为整数计算
print(f1 + 1) # 1+1的结果为2 True表示1
print(f2 + 1) # 0+1的结果为1 False表示0
|
8012414b6f43d53b28d10384b58e743d7cf50952 | dan30github/CMPSC-132 | /merge_sort.py | 1,462 | 4.25 | 4 | #LAB 13
#Due Date: 11/18/2018, 11:59PM
########################################
#
# Name: Daniel Melo Cruz
# Collaboration Statement: I asked for help in the recursive function mergeSort.
#
########################################
def merge(list1, list2):... |
defa7a6905a1fe7995148a320fd0ef03226df28f | jorgeruiz11/GenomicaComputacional | /jruiz_p02/AreaTriangulo.py | 387 | 3.890625 | 4 | class AreaTriangulo(object):
def calcula_area(b, h):
area = (b * h)/2
return area
if __name__ == '__main__':
print("\nEscribe la longitud de la base: ")
b = float(input())
print("\nEscribe la longitud de la altura: ")
h = float(input())
area = calcula_... |
265b2a477c414ddd30eeed60c8801ee1b1d4abb4 | Delaunay/mlbaselines | /olympus/layers/differential.py | 1,586 | 3.5 | 4 | import torch
import torch.nn as nn
class Differential(nn.Module):
"""Compute a 1d convolution with a default filter of [1, -1]. It is used to compute
log returns in finance.
Parameters
----------
out_channel: int
Number of output, if != input it means the network will create buckets of as... |
85abfc35941d288fcad3048e49aed3fbd7c698b7 | Lmuxin/pythonTest | /pythontestprogramming/listbox.py | 198 | 3.5625 | 4 | from tkinter import *
master =Tk()
thelb=Listbox(master,selectmode=EXTENDED,height=11)
thelb.pack()
for item in range(11):
thelb.insert(END,item)
# thelb.delete(1) 删除
mainloop()
|
a8e41823c0fa0be4822cdcf6db426e109d117377 | raymondanythings/MyLittleSmartCalc. | /tttt.py | 377 | 3.625 | 4 | import datetime
today_data = datetime.datetime.now()
year = today_data.year
if int(today_data.month) < 10:
month = f"0{today_data.month}"
else:
month = today_data.month
if int(today_data.day) < 10:
day = f"0{today_data.day}"
else:
day = today_data.day
start_today = f"{year}{month}{day-1}"
end_today = f"... |
93faa69e684e92822a2b1dd01ac9367bff7e266d | jory-wen/yagni | /puzzle/src/puzzle/petals.py | 1,510 | 4.15625 | 4 | NUMBER_OF_CORRECT_ANSWERS_IN_ROW = 2
def petals():
import random
def roll():
dices = [random.randrange(1, 7) for _ in xrange(5)]
answer = sum(d - 1 for d in dices if (d % 2) != 0)
return dices, answer
info = ["Let's play 'Petals Around The Rose.'",
"The name of the game ... |
b5cd5ad1dda411d4b8099563ef55815cd0faea28 | cnkumar20/LeetCode | /python/reverse_k_group.py | 338 | 3.515625 | 4 |
#Reverse the array elements by group of k
#([1,2,3,4,5,6,7,8,9],3)
#[3, 2, 1, 6, 5, 4, 9, 8, 7]
def reverse_k_group(nList,k):
a = []
for x in range(0,len(nList),k):
temp = nList[x:x+k]
temp.reverse()
a.extend(temp)
# a.append(nList)
return a
print(reverse_k_group([1,2,3... |
61f9cab5d946765e88fed1ad2f749d9e132483b7 | dogppatrick/python | /basic_class/c0214_class2.py | 328 | 3.71875 | 4 | class G:
def m1(self):
print("G1.m1")
class P1(G):
def m2(self):
print("P1.m2")
class P2:
def m2(self):
print("P2.m2")
def m1(self):
print("P2.m1")
class C(P1, P2):
def m3(self):
print("C.m3")
def main():
c = C()
c.m1()
c.m2()
c.m3()
... |
b112469c2b9992695c1f64ab621ad2fa4304108d | EllieHachem/Some-projects | /mail-merge-project-start-mail-project/main.py | 902 | 3.90625 | 4 | #TODO: Create a letter using starting_letter.txt
#so alwways use ./ from now on easier
PLACE_HOLDER = "[name]"
with open("./Input/Names/invited_names.txt") as names_file:
names = names_file.readlines() #replaces each line in a data.txt as a list there is readline method so be careful and this is read variation ... |
b601700bedda9e851b19e535541507e62e9afcee | vaneEmy/Algorithms | /Python/factorial.py | 203 | 3.9375 | 4 | def factorial(n):
# test for a base case
if n == 0:
return 1
#make a calculation and a recursive call
else:
f= n*factorial(n-1)
print(f)
return(f)
factorial(4)
|
d1138fd8a5c548e66b6f1bbfe37f9db7244a992b | ocean20/Python_Exercises | /exceptions/arg.py | 326 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 19:51:56 2019
@author: cawang
"""
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print(Argument)
# call function
temp_convert('xyz')
# Argument: invalid literal for int() with base 10: 'xyz'
... |
6aca43524920101e503e48f345b39d0bc7e1393e | patwater/PA_GA_DS_Work | /traveling_salesman_play.py | 3,180 | 3.625 | 4 | # random and nearest neighbor reqs
# sample.tsp -- 709 random, 669 nearest neighbor, 550 letter of rec
# https://github.com/ga-students/DS-LA-03/wiki/Lesson-02-Assignment-Traveling-Salesman-Problem
# Manhattan salesman
import sys, getopt
import random
import networkx as nx
import matplotlib.pyplot as plt
with open(sy... |
523b8ce3648cf8f06bd00e4b1a8f1d2c20493b75 | hieuvp/learning-python | /learn-the-basics/classes-and-objects/access_object_function.py | 205 | 3.609375 | 4 | class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
my_object_x = MyClass()
# Access a function inside of an object
my_object_x.function()
|
cc6978390db4bda087fc4f92753204604f8858dd | pgularski/snippets | /python/algorithms/fibonacci.py | 890 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def cached(fun):
cache = {}
def wrapped(arg):
if arg not in cache:
cache[arg] = fun(arg)
return cache[arg]
return wrapped
@cached
def fib(n):
if n < 2:
return n
return fib(n - 2) + fib(n - 1)
def fib_counted(n):
... |
3eb2d618cd93494af34a787659d0e22b04fb13d5 | skdonepudi/100DaysOfCode | /Day 34/CyclicShifts.py | 1,154 | 3.828125 | 4 | '''
You are given a number represented as a binary representation of bits. You are also given a number and a character .
Determine a number that is generated after cyclically shifting the binary representation of by positions either left if or right is .
Input format
The first line contains an integer represe... |
412e40fb16133e510e45ad705ee802fbeeb4b345 | endy-see/AlgorithmPython | /SwordOffer/40-FindFirstCommonNode.py | 4,766 | 3.828125 | 4 | """
两个链表的第一个公共节点
题目:输入两个链表,找出它们的第一个公共节点。
思路:
1. 两条链表都是单向无环链表
2. 一条有环, 一条无环
3. 两个链表都有环时:
1)入环节点相同时,需要从头找到两条链表相交的第一个节点
2)两个链表的入环节点不同时(各自为环),可能根本不相交,也可能角点出现在环上
"""
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def GetIntersec... |
af8d20b8cca87fda203746aa994c3ad447e6b18a | SmallGreens/python_cookbook | /src/Basic/2ControlFlow.py | 2,659 | 4.34375 | 4 | if __name__ == '__main__':
'''
link: https://docs.python.org/3.8/tutorial/controlflow.html
python 中的流程控制语句:
- if: if- elif -else 。
- for: for xx in xx, range() 场合 for 配合使用,规定一个范围, e.g. for i in range(10) 。
- while。
- 与 for 和 while 搭配使用的 else:当 for 和 while 正常结束时,会执行 else 语句,... |
58d9017b35d611f6f590b6ab2a6acf2f8cebe13d | mcriqui/event_scripts | /csv_to_var_notes.py | 2,041 | 3.890625 | 4 | import csv
def attendees_for_var(filename):
#opens the file
with open(filename, 'r') as csv_file:
#splits each line in to a string
csv_lines = csv_file.read().split('\n')
#creates a list to store the first name (content in column A) and a list to store the last name (content in column... |
e428d1382aa5442e233a21d81a252e3ee8761dfb | ed04rdo/PythonForEverybodyUM | /Fundamentals/strings.py | 1,418 | 3.953125 | 4 | def slicing(s):
print(s[0:3]) # second number "up to but not including"
print(s[-1]) # last value
print(s[0:500]) # second number is beyond the end of string, stops at the end
print(s[:4]) # from beginning to 4
print(s[4:]) # from 4 to end
print(s[:]) # all string
def inOpera... |
c02bfcc32eb42448c9e67fc9f24f62fc9c6652f9 | lauraverhoeven/sudoku_game | /code/main_program.py | 38,368 | 3.5 | 4 | import tkinter as tk
class sudoku:
def __init__(self, parent):
self.parent = parent
logo_image = tk.PhotoImage(file="logo.png")
self.image = logo_image
self.logo_frame = tk.Frame(
self.parent, width=700, height=700, highlightcolor="white", highlightbackground="white",... |
15ed7082fdc232693446f5f2bdb3ae6fe4b6d47e | soumi444/Introduction-to-programming-using-python-by-Y.-Daniel-Lang | /11.20 | 4,008 | 3.65625 | 4 | import sys
def dropADisc(player, board):
done = False
while not done:
print("Drop a", "red" if player == 'R' else "yellow", end=" disk at column (0-6): ")
column = eval(input())
if placeADisk(board, column, player):
done = True
else:
print("This column... |
5db5a6e4c086a021b5c57ebbdfc9e978bf060c03 | shayroy/ChamplainVR | /Week 3/Class 2 20181115/arrays.py | 102 | 3.78125 | 4 | # adding to arrays
a1 = [1, 2, 3]
for x in a1:
print(x)
a1 = a1 +[4,5]
for x in a1:
print(x)
|
8a895827fe2b01643e53a6da165eb582342959f1 | JaydeepKachare/Python-Assignment | /Assignment2/Assignment2_4.py | 308 | 3.890625 | 4 |
def main() :
num = int(input("Enter number : "))
sum = 0
factor = 1
while factor < num :
if (num % factor == 0) :
sum = sum + factor
factor = factor + 1
print("sum offactor of {} is {} ".format(num,sum))
if __name__ == "__main__" :
main() |
83009ed3dbac750329c660d895af41fd5634c106 | ainult1/krestik-nolik.igor | /krest-nol.py | 1,557 | 3.8125 | 4 | board = list(range(1, 10))
jek_pots = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)]
def draw_board():
print('-------------')
for i in range(3):
print('|', board[0 + i * 3], '|', board[1 + i * 3], '|', board[2 + i * 3], '|')
print('-------------'... |
f56931121e98b9859dc7a029abf33abac32d32ee | Tomgauld/python-year11 | /worldcup.py | 245 | 3.875 | 4 | team = input("Please enter a team:")
teams = ["Columbia","England","Croatia","Germany","Spain","Portugal","France","Mexico","Denmark",
"Iceland","Costa Rica","Japan","South Korea","Egypt","Iran"]
print(team, "is a valid option!")
|
d147373d453387224b601b0304d4302d56dd68f7 | markv27/MyFirstRepo | /list_MV.py | 836 | 3.984375 | 4 | name = "Mark Vollmer"
subjects = ["English","Math","Chinese","Science","History"]
print("Hello " + name)
for i in subjects:
print("One of my classes is " + i)
characters = ["Luke","Han","Vader","Chewy","Leia"]
for i in characters:
if i == "Vader":
print(i + " is the villan in Star ... |
5b726e0b894b1f733485f9947c53c40f36974ae5 | tandiawanedgar/EdgarTandiawan_ITP2017TugasPAKBAGUS | /Tugas 4/Tugas 4-2/4-2.py | 122 | 3.75 | 4 | data=['shark','whale','fish']
for name in data:
print(name,'live in the sea')
print('they all need something to eat')
|
068db952f9ffce5ec33e9e028d9ad439f34bff34 | barrysheppard/DBSDataAnalysis | /ProgrammingEssentials/Week1_Exercise1/04Sum.py | 133 | 3.875 | 4 | # Tutorial 01 - 4. Write a program to calculate the sum of two integers values
num1 = 14
num2 = 4
sum = num1 + num2
print(str(sum))
|
4f9af3576dd02e5b6117a30bbd2c392ba36ebf44 | ArionDeno/inteligencia-artificial | /labirinto.py | 2,567 | 3.640625 | 4 | #!/usr/bin/env python3
from pprint import pprint
with open('maze01.txt') as fp:
dados = fp.readlines()
pprint(dados)
labirinto = []
for linha in dados:
aux = []
for coluna in linha.strip():
if coluna == ' ':
aux.append(0)
elif coluna == 'E':
aux.append(1)
... |
cd2d84ee0c0e99513b3b8361ff2d7effef90cd7d | Dplo1514/ploaistudy | /1-2주차 복습/210821 list 함수 3.py | 516 | 3.953125 | 4 | print('#list.extend 메서드를 이용하여 다른 리스트를 병합할 수 있다.')
a_list = list(range(1,11,2))
b_list = list(range(1,11,5))
a_list.extend(b_list)
print(a_list)
sep="\n"
print('#append 메서드를 이용하면 리스트안에 또다른 리스트가 생성된다.')
c_list = list(range(10,21,2))
d_list = list(range(10,21,4))
c_list.append(d_list)
print(c_list)
print(... |
1ed58bce9b455addf5e0ac302c2634c85c457b7e | YusrilAgisha12/python | /grade_nilai.py | 1,349 | 3.828125 | 4 | while True:
nama_siswa = input ("masukan nama anda : ")
nilai_harian = float (input("masukan nilai :"))
nilai_uts = float (input("masukan nilai uts :"))
nilai_uas = float (input("masukan nilai uas :"))
nilai_akhir = float (((nilai_harian*40)/100)+((nilai_uts*30)/100)+((nilai_uas*30)/100))
if ni... |
150c8c48c2579988147ad03e89103c3e919b3d2c | jsmlopz1991/learning-python | /pruebas_for/prueba_for_9.py | 373 | 3.8125 | 4 |
numero = input("Dime un numero (FIN para terminar)")
lista = []
valor = 0
while numero != "FIN":
while not numero.isdigit():
numero = input("Tiene que ser un numero (FIN para terminar)")
lista.append(numero)
numero = input("Dime un numero (FIN para terminar)")
for recorrer in lista:
valor +... |
bf3fef239977ddf1eae2ff07404d8c9b33f8b217 | AkhileshManda/learngit | /prb4.py | 421 | 3.640625 | 4 | nc=int(input("Enter no. of computer "))
nt=int(input("Enter no. of Table "))
ns=int(input("Enter no. of chairs "))
cc=float(input("Enter cost of 1 computer "))
ct=float(input("Enter cost of 1 table "))
cs=float(input("Enter cost of 1 chair "))
nw=int(input("Enter no. of hours worked "))
wh=int(input("Enter wages... |
55323a1a71f83b41d6cf1a314be6ceeb17928af7 | abhishek-987/PersonalAssistant | /demo.py | 153 | 3.84375 | 4 | def add(x,y):
return x+y
print(eval("add")(5,6)
num='hello'
print("so the num is "+num+" and tell me what you are going to do with it")
|
a70d78014b553b3cc44b3eaa91eeb03e8288a59c | edge555/Online-Judge-Solves | /UVA/10940 - Throwing cards away II.py | 246 | 3.640625 | 4 | while(True):
n=int(input())
if(n==0):
exit(0)
if(n==1):
print("1")
continue
i=1
m=n
while(2*i<n):
i*=2
n%=i
if(n==0):
print(m/2)
else:
print(2*n)
|
19ce6fcb73e242e4acc0f2cfc79128f791f14f15 | nirvidya8147322767/vidya-python | /30python.py | 173 | 3.859375 | 4 | while True:
a=(input("click r to print banglore temp: "))
if(a=="r"):
import random
r=random.randint(25,30)
print("banglore temp =",r)
else:
print("bye")
break |
15539bb6002db494d2732ff74f2cc8958ef7ce02 | GustavoGarciaPereira/Topicos-Avancados-em-Informatica-I | /pythoFuncional/exer1.py | 185 | 3.65625 | 4 | #1. Calcular a soma dos n primeiros números inteiros maiores que zero
#soma = list(map(lambda x:))
soma = lambda n: 0 if n < 0 else n + soma(n-1)
print(soma(3))
#somatorio = lambda |
d480cc4e7a99793f2b970c99e8c1ca24c9d8c704 | Aravindrajee/geeksforgeeks | /src/main/python/geeksforgeeks/arrays/hashing/Key Pair.py | 397 | 3.546875 | 4 | """
https://practice.geeksforgeeks.org/problems/key-pair/0
"""
def fun(arr, n, x):
s = set()
for element in arr:
if (x-element) in s:
return 'Yes'
s.add(element)
return 'No'
if __name__ == '__main__':
for _ in range(int(input())):
n, x = map(int, input().split())... |
e248b7268da77605e7753a05c8875526f7dc50d3 | ShaikMohammadUsman/QuantumComputing | /QuantumComputing with Cirq.py | 1,260 | 3.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
pip install cirq
# In[2]:
import cirq
# In[3]:
print(cirq.google.Sycamore)
# In[4]:
#Defining the Qubits using ##NamedQubit## method
a=cirq.NamedQubit('a')
b=cirq.NamedQubit('b')
# In[6]:
##Creating a quantum circuit using #CIRCUIT# method
circuit=cir... |
be07986874237edaaa280f9aed07ffa7061d4bd6 | pydevjason/Python-VS-code | /iteration_with_conditional_logic.py | 610 | 4.25 | 4 | # create a add_odd_numbers function that accepts a list of numbers and have it return the total sum
def add_odd_numbers(num_list):
total = 0
for i in num_list:
if i % 2 == 1:
total += i
return total
print(add_odd_numbers([1, 2, 3, 4, 5, 6]))
# create a greatest_number function that accepts a lis... |
6401b2311bae5f51f0a61bb1e94a25cb2c0a678f | VictorWiedemann/PythonCourse | /firstClass/main.py | 3,526 | 3.890625 | 4 | import random
import sys
# print ("hello world")
# print ('what is your name')
#myName = input()
#if myName:
# print ('hello you')
#else:
# print('what are you')
#print ('It is good to meet you, ' + myName)
#print ('The length of your name is: ' + str(len(myName)))
#print ('What is your age?')
#myAge = input(... |
d7d6f2318eae34c1bd58e38f7ef0c8782c1af0cf | tayyabmalik4/ML_Algo_With_Tayyab | /05_Multiple_Regression_ML.py | 632 | 3.828125 | 4 | # (05)***************Multiple Linear Regression***************
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
path = r'datasets/M_Regression.csv'
dataset = pd.read_csv(path)
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,3].values
# ---for spliting the data
from sklearn.model_selection imp... |
f1936e569e6e945eacc85f173cebc3293b189b8c | jessicameira/python | /lista.py | 341 | 4.0625 | 4 | bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[1].title())
print(bicycles[-1].title())#ao informar o indice -1 é informado o ultimo indice contido,
# - 2 penultimo, -3 antepenultimo e assim sucessivamente.
print('My first bicycle was a ' + bicycle... |
95dc7b4c05a6fb6db054a15793c243643bff584f | Dshree217/Ticketing-System | /ticket.py | 449 | 3.671875 | 4 | class Ticket:
def __init__(self, age, car_number):
self.age = age
self.car_number = car_number
def get_age(self):
"""
To get the age of driver of a ticket
:return: age of the driver
"""
return self.age
def get_car_number(self):
... |
219ffa90544e680d65fcccc6b8284e5b070306cc | javaDeveloperBook/python-learn | /base/fibonacci_test.py | 103 | 3.703125 | 4 | a,b=0,1
# 两个元素的总和确定了下一个数
while b < 100:
print(b,end=",")
a,b=b,a+b
|
bbeec83a668a1af3778782ce7d6edbafec0dc76f | Pi-hils/cgf-week2 | /python_basics_104.py | 742 | 4.15625 | 4 | # Lists (aka arrays)
#defining a list
xmas_list = []
print(type(xmas_list))
#index [ 0 , 1 , 2 , 3 , 4 ... ]
xmas_list = ['ballons', 'stars', 'IWC Portugieser Perpetual Calendar', 'sleep', 'chocolates' ]
# lists are organized with indexes
# indexes start at 0
#extracting data you u... |
d618d87461376e9d7d1ed246ea705ec0ba6d016d | NiallS4/CA117 | /lab_8.1/gaa_mult_081.py | 2,062 | 3.796875 | 4 | class Score(object):
def __init__(self, goals=0, points=0):
self.goals = goals
self.points = points
def __gt__(self, other):
return (self.goals*3 + self.points) > (other.goals*3 + other.points)
def __ge__(self, other):
return (self.goals*3 + self.points) >= (other.goals*3 + other.points)
def __lt__(se... |
8ffdf477bef5ae147a6af9da3ce689d3ae7617bc | hgirish/ud120-projects | /decision_tree/quiz10.10.py | 457 | 3.828125 | 4 | def featureScaling(arr):
mindata = min(arr)
maxdata = max(arr)
scaled = [0.5,0.5, 0.5]
if mindata == maxdata:
return scaled
for i in range(0,3):
x = float(arr[i])
print("i: {0}, x: {1}".format(i,x))
scaled[i] = (x - mindata)/(maxdata - mindata)
print... |
d679e49c34bac13bfecd4d7a032c315f365e74c4 | joahn3/fmi | /AN3/AWP - Optional/lab/HW2.py | 6,312 | 3.59375 | 4 | # coding=utf-8
"""
Ex. 1
Definiți clasa DateRange care primește la inițializare o valoare start și o
valoare end, ambele fiind obiecte datetime.date.
Adăugați proprietatea:
- days - returnează numărul de zile din intervalul [start, end]
Adăugați metoda:
- contains - primește un obiect date și returnează True da... |
d5fdfcacd68a3fbd34f306970672a44d15bd4c7c | dingchaoz/pythonLeetcode | /longestCommonPrefix.py | 584 | 3.5625 | 4 | """
abcabc st1
abcdabcd st2
abc st3
res = ''
for i in range(len(st1)
if st1[i] == st2[i] == st3[i]
res += (st[1])
else:
return (res)
return(res)
"""
class Solution:
def lcprefix(self,arrStr):
res = ''
for i in range(len(arrStr[0])):
for j in ran... |
23d762f416bfc61ccca2b4028523741205792203 | sharmaji27/InterviewBit-Problems | /Trees/Symmetric Binary Tree.py | 897 | 4.3125 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Example :
1
/ \
2 2
/ \ / \
3 4 4 3
The above binary tree is symmetric.
But the following is not:
1
/ \
2 2
\ \
3 3
Return 0 / 1 ( 0 for false, 1 for true ) for thi... |
dedd6dc94b8083602909f67f26d4b5ab5b66a61a | ImranAvenger/uri-python | /1985.py | 323 | 3.53125 | 4 | x = input()
t = 0
for i in range(x):
y, z = (raw_input()).split(' ')
if y == '1001':
t += 1.5 * int(z)
elif y == '1002':
t += 2.5 * int(z)
elif y == '1003':
t += 3.5 * int(z)
elif y == '1004':
t += 4.5 * int(z)
else:
t += 5.5 * int(z)
print ('{:.2f}').format(t... |
b6169b04fbfead2b25969092dd311b9c318caf7b | Alfran007/Internet-Of-Things | /Experiments/pi/on_off.py | 646 | 3.6875 | 4 |
# to import the RPi.GPIO module
# by doing it this way, you can refer to it as just GPIO through the rest of your script
import RPi.GPIO as GPIO
# library to add delay
import time
# instantiate GPIO as an object
GPIO.setmode(GPIO.BCM)
# define GPIO pin
powerPin = 4
# setup channel [GPIO.setup(channel, GPIO.IN/OUT]... |
36d0cfe17103bead01997e6c432f318adfd05396 | StonecutterX/DataStructureAndAlgorithm | /LeetCode/P3_longest_substr_without_repeating.py | 779 | 3.5625 | 4 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if s is None:
return 0
is_exist = set()
str_len = len(s)
rk, ans = -1, 0
for i in range(str_len):
# while中会一直加只到存在一样的,那么这时候就把最开始的重复的删除掉
if i != 0:
... |
74345f4e8c9a3900ce89862792ba15f6cb1e59b4 | LoveEatCandy/leecode | /arithmetic/多线程-哲学家吃面.py | 1,825 | 3.5625 | 4 | """
import threading
class DiningPhilosophers:
def __init__(self):
self.l = threading.Lock()
def wantsToEat(self, philosopher, *actions):
self.l.acquire()
[*map(lambda func: func(), actions)]
self.l.release()
作者:tuotuoli
链接:https://leetcode-cn.com/problems/the-dining-philosop... |
32386fc023551684875c2b01da07ef430a07668d | CoreyGaunt/rccp_script | /3_Old_Scripts/rccp_scripting_archived.py | 8,919 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import os
import csv
from itertools import chain
import shutil
# In[ ]:
# This code reads in your file, creates a dataframe, and removes all rows with missing data
# IMPORTANT - ensure your csv file does not have any unneccesary bl... |
844cfad725a3dc2e1a197c7cec9598a3521dd279 | Seanghor/Bootcamp-2020 | /Ex 35.py | 1,393 | 3.625 | 4 | # My Code
def dict_shopping(ent):
error = 0
l = []
t = []
if len(ent) == 2: # ent = [{}, {}]
for dc in ent: # dc = {}
for i in dc: # i = key
x = dc[i] # dc[i] = value
l.append(x)
a = l[0]*l[1] + l[2]*l[3]
# total =... |
13b84d9752e4f2327806e649c7c595aba710ab4c | we1are1adc/leetcodeRecord | /35.搜索插入位置.py | 349 | 3.5 | 4 | #
# @lc app=leetcode.cn id=35 lang=python3
#
# [35] 搜索插入位置
#
# @lc code=start
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l = len(nums)
if target > nums[-1]:
return l
for i in range(l):
if target <= nums[i]:
return i
... |
1f4ffece568d12559756468b736d354598ca4815 | code-in-public/leetcode | /decode-string/solution.py | 1,526 | 4.03125 | 4 | #!/usr/bin/env python3
class Solution(object):
def decodeString(self, s):
decoded = ''
# True when inside an encoded strings
reading_encoded = False
# Index of the number for the encoded string
encoded_start_idx = None
# A count of open brackets
open_bracket... |
c7bd95f6d2f06c9bd43ead27cef4e08b617f5bbd | smileyoung1993/Posco_Bigdata | /AI_bigdata_class/class_homework/homework4/day4_Q3.py | 819 | 3.9375 | 4 | # 천 단위마다 쉼표(,) 추가하는 함수 정의하기(완료)
def add_comma(val):
lst_val = list(str(val))
cnt = 0
for i in range(len(lst_val) - 1, -1,-1):
try:
cnt += 1 # 천단위의 갯수를 센다 (3의 배수개)
if len(lst_val) > 3:
if cnt % 3 == 0:# 3의 배수일때
lst_val[i] = ',' + ... |
f2da644fab16238dc54024fa30a14b0ba3c683fe | Toruitas/Python | /Practice/Daily Programmer/DP37 - count number of lines.py | 581 | 3.828125 | 4 | __author__ = 'Stuart'
"""
http://www.reddit.com/r/dailyprogrammer/comments/rzdwq/482012_challenge_37_easy/
write a program that takes
input : a file as an argument
output: counts the total number of lines.
for bonus, also count the number of words in the file.
"""
def count_lines(filename):
lines = 0
words = 0... |
7b9ac6347ea27189e9d3a225916e7d4952205498 | shyamsaran/sam | /sam.py | 185 | 3.75 | 4 | a=str(input("enter the user name="))
b=str(input("enter password="))
if a=="stc" and a=="123":
print("welcome to stc")
else:
print("welcome to cts")
print("shyam")
print("sam")
|
989983a4b1d1694e68ab1c4f9eeae96a90317360 | Tribruin/AdventOfCode | /2017/Day7/main.py | 3,061 | 3.609375 | 4 | #!/Users/rblount/.pyenv/versions/AdOfCode/bin/python
import sys
import os
import re
from AOC import AOC
testing = False
def parse_input(code_input):
programs = dict()
for line in code_input:
temp_split = line.split(" -> ")
temp = temp_split[0]
if len(temp_split) > 1:
d... |
31c204d6130677cd67a33650e4f914c1fec1f160 | dbconfession78/interview_prep | /leetcode/292-nim_game.py | 1,496 | 3.859375 | 4 | class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return (n % 4 == 0) == 0
def main():
print(Solution().canWinNim(1))
print(Solution().canWinNim(2))
print(Solution().canWinNim(3))
print(Solution().canWinNim(4))
print(Solution().can... |
d738bba772acc1ed8d970cd1f01ee5674795092e | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4367/codes/1613_2425.py | 115 | 4.0625 | 4 | d=float(input("escolha um numero"))
CG=float(input("escolha um numero"))
CM= d/CG
print(round(CM, 3))
print("km/l") |
cf1d49d41e2ff1c3d81f51b23932567b1e693ff1 | shivakumar96/SVD-dimensionality-reduction | /dataGen.py | 961 | 3.5 | 4 | import csv
def getZeroRowMatrix(n) :
l = []
i=0
while(i<n) :
l.append(float(0))
i+=1
return l
file1 = open('u1.base','r') #file to read train data
file2 = open('u1.test','r') #file to red test data
file3 = open('u.item','r') #file to read movie names
people = [] # to s... |
4e6868eebfabdeb7e52ee6771293da2deb8c90e1 | sxiang1983/logic | /practice/1.9.py | 202 | 3.71875 | 4 | # Import the math library
# This line is done only once, and at the very top
# of the program.
from math import *
# Calculate x using sine and cosine
x = sin(pi) + cos(pi)
print(x)
print(pi)
|
32e29522797cf64d5ea1978d09062f0db75fff96 | KennyIT3/Python_Scipts-Automating-Sysadmin | /Scripts/bmi.py | 647 | 4.21875 | 4 | def bmi():
try:
height=input("Enter in your height in feet and inches. Make sure to put comma between feet and inches: ")
feet,inches=map(int,height.split(","))
weight=input("Enter in weight: ")
weight=float(weight)
total_height=(feet * 12) + inches
calc=round((weight * 703) / (total_height *... |
69b25d73a6d5ab92cea43176355d9acc40fc7b73 | agentc13/round_robin_tournament | /round_robin_tournament/tournament.py | 2,901 | 3.890625 | 4 | """
This defines a round robin 'Tournament' object.
"""
import math
import itertools
from round_robin_tournament.match import Match
from round_robin_tournament.participant import Participant
class Tournament:
"""
This is a round-robin tournament where each match is between 2 competitors.
It takes in a lis... |
9c9c1581ee9ee987c03c54805bccaa5610add79c | zopefoundation/Products.CMFCalendar | /Products/CMFCalendar/skins/zpt_calendar/getDaysClass.py | 512 | 3.671875 | 4 | ##parameters=day, month, year, event=None
# Is the date given today?
# If so we want to return a class of 'todayevent' so that the event gets the
# today border around it.
# If not we want to return just 'event' so the event gets the proper shading.
import DateTime
current = DateTime.DateTime()
if current.year()==y... |
ffb0d29982b02b32a55982d5646449375b4d6ff4 | alvaro-root/pa1_2021 | /wk11_in_class.py | 842 | 4.15625 | 4 | my_dict = {}
my_other_dict = dict()
my_3rd_dict = {'a': 1, 'b': 2, 'c': 3}
my_3rd_dict['d'] = 99
print(my_3rd_dict['a'])
print(my_3rd_dict.keys())
for k,v in my_3rd_dict.items():
print(f"key: {k}, value: {v}")
headers = ("h1", "h2", "h3")
body = ((1,2,3),(4,5,6), (7,8,9))
for row in body:
my_4th_dict = d... |
e400173706c725a41632bc8fab578844f65a19e6 | EunjinLim-78/test1 | /tasks_5_1.py | 378 | 3.5625 | 4 | '''
-- 0, (n=1)
f()n-- 1, (n=2)
-- f(n-2) + f(n-1), (others)
'''
def fib(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-2) + fib(n-1)
for i in range(1,11,1):
print(i,fib(i))
'''
[0, 1]
.append(-1, -2)
-> [0, 1, 1]
'''
'''
l = [0, 1, 1]
for i in ra... |
feae67978a09cb869e38cb3c728d46c54006dd4c | laiqjafri/LeetCode | /problems/00977_squares_of_a_sorted_array.py | 625 | 4.09375 | 4 | # 977. Squares of a Sorted Array
# Easy
#
# 2220
#
# 114
#
# Add to List
#
# Share
# Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
#
#
#
# Example 1:
#
# Input: nums = [-4,-1,0,3,10]
# Output: [0,1,9,16,100]
# Explanation: After... |
7ebc7b6f18d3beaca8ec58b486f78ac661f46ec0 | Methuselah96/aoc-2019-python | /02_1/solve.py | 778 | 3.59375 | 4 | def add(state, index):
state[state[index + 3]] = state[state[index + 1]] + state[state[index + 2]]
def multiply(state, index):
state[state[index + 3]] = state[state[index + 1]] * state[state[index + 2]]
def solve(state):
index = 0
op_code = state[0]
while op_code != 99:
if op_code == 1:
... |
f7b103d6dd516fc52d8a2b9988b59918d493ad8b | dsc-vast/Algorithms | /Python/func prime number.py | 170 | 3.9375 | 4 | def primen(x):
n=0
for i in range(1,x+1):
if x % i == 0:
n=n+1
if n==2:
print("It prime number =",x)
else:
print("It not prime number =",x)
|
defd72e6572332141cd58332c9b7eab7e1b4e58c | busrayasar/python | /fonsiyonlar.py | 2,075 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 12:15:23 2020
@author: busra
"""
# ?fonksiyon_adı yazarsan o fonkun dökümantasyonunu gösterir
print("a", "b", sep="_") # a ve b elemanlarını "_" ile birleştirir ->a_b
def square(x):
print( x**2)
square(9)
#bilgi notu üreten fonksiyon
def squar... |
1a1127abbee939a107dd5f7aa79d34bc108806b8 | ngutro25/csf | /quiz2.py | 152 | 3.59375 | 4 |
from lab2 import n
if (n > 50):
print 'n is greater then 50'
if (n < 50):
print 'n is less then 50'
else:
print 'n is equal to 50'
|
2409085161366c855265bd2149707c1cba32ac08 | Donal-Flanagan/CyberdyneCollective | /tutorials/Intro to Computer Science with python_NUIG/Python Programs/gradespercent.py | 352 | 3.96875 | 4 | # gradespercent.py
# a program to calculate the grades of a test
#
# by Dnal
def main():
n = input("Please input the percentage mark:")
if 100>=n>=90:
print "A"
elif 89>=n>=80:
print "B"
elif 79>=n>=70:
print "C"
elif 69>=n>=60:
print "D"
elif n<60... |
7e46bd44e72ac92c16274b1f2f583942f4f422ec | giant-teapot/adventofcode-2020 | /aoc/day8.py | 2,213 | 3.78125 | 4 | #!/usr/bin/env python3
"""
Day 8: Handheld Halting
https://adventofcode.com/2020/day/8
"""
from dataclasses import dataclass, field
from typing import Set, Optional
@dataclass
class Instruction:
op: str
param: int
def flip(self):
if self.op == "nop":
self.op = "jmp"
elif se... |
4669702d9f687c8c191abe514641851b1012c710 | AshishGupta1992/OCR-App | /Regex Practice.py | 201 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 16:52:02 2019
@author: Ashish.Gupta
"""
import re
x='234jguj'
print(len(x))
regex = '\w[0-9]'
y = re.search(regex, x)
print(y[1]) |
fdeedcc1d85c0623e5d87feef26a8407381d5a01 | neyhartj/bioinformatic-utils | /tassel2fastPHASE.py | 3,235 | 3.625 | 4 | #!/usr/bin/env python
## This python script will convert a TASSEL hapmap to a file input
# used by fastPHASE
# Import libraries
import argparse
#####
# Define the arguments
#####
# Description
DESC = """A Python program to convert a TASSEL-encoded hapmap file to the input
file used by fastPHASE.\n"""... |
8bd048a3021b60cc22dc924a91f4adee99402287 | Luckyaxah/leetcode-python | /二叉树_将二叉搜索树转换为累加数.py | 924 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
if not root:
return []
self.t = 0
def process(root):
... |
b3bbceda9f820cb3ef7e14a8c2d831a5d13d9c7d | MiaZhang0/Learning | /models_practice/demo02.py | 2,044 | 3.5 | 4 | #多元线性回归模型,相当于求多元函数的系数即向量。此处涉及线性代数矩阵、向量、秩、矩阵的逆、矩阵的转置
from sklearn import model_selection
import pandas as pd
import statsmodels.api as sm
#导入数据
path = r'E:\workspace\testdatas\Predict to Profit.xlsx'
Profit = pd.read_excel(path)
#将数据集拆分为训练集和测试集
train,test=model_selection.train_test_split(Profit,test_size=0.2,random_sta... |
93e01a00b43b0dec3010d0ca3b33294c11ca7b96 | msaldeveloper/python | /pythonBook/starting_to_program.py | 345 | 3.921875 | 4 | ##input
input("introduce el precio de una manzana")#entrada de datos que combierte la misma en string
eval(input("introduce el precio de una manzana"))#eval convierte el string en dato numerico
manzana = eval(input("introduce el precio de un manzana"))#guarda el dato introducido en la variable manzana
print(manzana)#im... |
cfb2926c8d0a8253c09b6930afcc2f0f899da5a2 | vikramjit-sidhu/algorithms | /hacker_rank/greedy/priyanka_toys.py | 1,362 | 3.84375 | 4 | """
Hacker Rank - Priyanka and Toys
https://www.hackerrank.com/challenges/priyanka-and-toys
"""
def sort_list(list_tosort):
""" Returns a sorted list """
return sorted(list_tosort)
def calculate_toys_obtained_for_free(weight_list, index, num_toys):
"""
The toy in list at 'index' position has been boug... |
b7184b8295f5b95059905a8e295496d90388a06c | EhODavi/curso-python | /exercicios-secao13/exercicio05.py | 397 | 4.0625 | 4 | nome_arquivo = input('Informe o nome do arquivo: ')
caractere = input('Informe um caractere: ')
with open(nome_arquivo) as arquivo:
conteudo = arquivo.read()
quantidade_caractere = 0
for letra in conteudo:
if letra == caractere:
quantidade_caractere += 1
print(f"O caractere '{car... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.