blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bc9d30b6e09e31792b8db87ab3599a0f41baa81d | sonymoon/algorithm | /src/main/python/geeksforgeeks/graph/floyd-warshall-shortest-path.py | 1,532 | 3.71875 | 4 | # Input:
# graph[][] = { {0, 5, INF, 10},
# {INF, 0, 3, INF},
# {INF, INF, 0, 1},
# {INF, INF, INF, 0} }
# which represents the following graph
# 10
# (0)------->(3)
# | /|\
# 5 | |
# | ... |
8c5f62408cd00e029468b4c39b70b22aa6d61991 | moneyDboat/offer_code | /25_复杂链表的复制.py | 1,153 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
# @Author : captain
# @Time : 2018/10/28 3:00
# @Ide : PyCharm
"""
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# wr... |
20f1285b5d94d9c314fe0316e2fa4a7a7b92024f | raberin/Sprint-Challenge--Computer-Architecture | /ls8/simple.py | 1,903 | 3.90625 | 4 | import sys
PRINT_BEEJ = 1
HALT = 2
PRINT_NUM = 3
SAVE = 4 # Save a value to a register
PRINT_REGISTER = 5 # Print the value in a register
ADD = 6 # ADD 2 registers, store the result in 1st reg
memory = [0] * 256
register = [0] * 8
pc = 0 # Program counter
def load_memory(filename):
try:
address =... |
81171cbfc61a46f8aa1a3a4a708c6b21c1eac30d | aaralh/AdventOfCode | /utils.py | 233 | 3.796875 | 4 | def readFile(fileName: str) -> str:
'''
Return contents of file with given name.
Arguments:
fileName -- Name of the file.
'''
with open(fileName, 'r', newline='') as inputFile:
return inputFile.read() |
6102f1fdb3bde9fcce0310f744726eba24ea1c83 | wyb2333/Computer-Vision-and-Pattern-Recognition | /Homework 3/test.py | 201 | 3.6875 | 4 | import numpy as np
a = range(27)
a = np.array(a)
a = a.reshape([3, 3, 3])
b = range(9)
b = np.array(b)
b = b.reshape([1, 3, 3])
print(a)
# print(a[0, :, :])
# print(np.sum(a, 0))
print(b)
print(a*b)
|
e715336b8fcc784c6d7a0b030ca9cf8be67a0bd2 | SudiLillian/Test-App | /questions.py | 951 | 4.25 | 4 | class Question(object):
"""This class models question objects."""
def __init__(self, question_text, answer, choices):
"""
Create a new Question object.
The method accepts:
question_text: The question itself
answer: The answer to the question
choices: ... |
91b54249d1afa6f77a1af371997d3e00aaaae34b | Nishith170217/Coursera-Python-3-Programming-Specialization | /num_chars.py | 309 | 4.15625 | 4 | # Write code to count the number of characters in original_str using the accumulation pattern and assign
# the answer to a variable num_chars
original_str = "The quick brown rhino jumped over the extremely lazy fox."
num_chars=0
for i in range(len(original_str)):
num_chars=num_chars+1
print(num_chars)
|
5df28ae56a8aeb4a588f348cd0ac0ecd3790c404 | dhbandler/Unit2 | /movie.py | 557 | 4 | 4 | #Daniel
#1/29/18
#movie.py prints most scandalous movie legal per age
age=float(input("What is your age? "))
if age<13:
print("You can watch either G or PG movies. The MPAA doesn't discriminate due to age in this category.")
elif 13<=age<17:
print("Watch PG-13 movies! The MPAA says you can watch this categor... |
550ced8d8369a8cfdc71ea01cb018b9fe973a4ff | enolan26/EGN3124 | /8-4.py | 236 | 3.6875 | 4 | import pandas as pd
url=r'https://thermo.pressbooks.com/chapter/saturation-properties-temperature-table/'
t_table = pd.read_html(url, header=0)
print(t_table)
userInput = str(input('Enter temperature in degrees C:').upper())
|
9560e49468398604596f2bfc1cb6653a78282cd0 | banashish/DS-Algo | /coding Ninjas/DS/LinkedList/basicCreation.py | 464 | 3.953125 | 4 | class Node:
def __init__(self,val = 0,next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def printList(head):
while head != None:
print(head.val,end = "\n")
head = head.next
ll = LinkedList()
node1... |
905121ed02664705aae6ee1eaf67e644334af252 | cjj1024/Mario | /sprite/coin.py | 981 | 3.5625 | 4 | import pygame
from tool.init import *
# 硬币类
# 当Mario撞击有硬币的砖块时, 出现在砖块的上方
# 硬币出现后, 旋转一定时间后消失
class Coin(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = coin_img[1]
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y ... |
71d36931d95c0ff17cb42b9884d931786e44dba8 | jhonnymonte/python-unsam | /Clase02/ejercicio 2.13.py | 538 | 3.59375 | 4 | import csv
with open('C:/Users/User2021/Documents/python/unsam/ejercicios python/clase 2/archivos/camion.csv', 'rt') as f:
filas= csv.reader(f)
next(filas)
fila=next(filas)
d={
'nombre' : fila[0],
'cajones' : int(fila[1]),
'precio' : float(fila[2])
}
print(d)
... |
17131147034f426721ada562c1e8194e2a0fe25c | shiveshsky/datastructures | /linked_list/merge_sort_linked_list.py | 1,091 | 3.828125 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def sortList(self, head):
pass
def merge(self, l, r):
if l is None:
return r
if r is None:
return l
result = None
if l.val < r.val:
... |
729f480605ecb385433ae6f3435e5f7276220133 | rrude/Exercise09 | /recursion.py | 3,187 | 3.875 | 4 | l = [1, 3, 2, 9, 17]
# Multiply all the elements in a list
def multiply_list(l):
if len(l) == 1:
return l[0]
else:
return l[0] * multiply_list(l[1:])
# Return the factorial of n
def factorial(n):
total = 1
if n == 1:
return 1
else:
total = factorial(n-1) * n
ret... |
747707c028e314a5eff983e4a9e35bede5aae0c0 | eklitzke/algorithms | /combinatorics/permutations.py | 621 | 4.09375 | 4 | """Implementation of permutations.
This uses the "interleaving" technique, which I find the most intuitive. It's
not the most efficient algorithm.
"""
def interleave(x, xs):
"""Interleave x into xs."""
for pos in range(len(xs) + 1):
yield xs[:pos] + [x] + xs[pos:]
def permutations(xs):
"""Gener... |
3838debe3c9ec2384e132d46a409ae5564b08d1c | itsjw/python_exercise | /python_book_exercise/exercise_two.py | 115 | 3.953125 | 4 | length = 5
breadth = 2
area = length*breadth
print('Area is',area)
print('Perimeter is', 2*(length + breadth))
|
11f3ca77adca9bee093fc89f0109e80051f6933c | AlessandroCorradini/MIT-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science | /5 - Stocastic Thinking/Exercise 3.py | 521 | 4.3125 | 4 | # Write a deterministic program, deterministicNumber, that returns an even number between 9 and 21.
# def deterministicNumber():
# '''
# Deterministically generates and returns an even number between 9 and 21
# '''
# # Your code here
import random
def deterministicNumber():
'''
Deterministical... |
474fe5aaf257910296f2789aa7805b8724a7e8c6 | ai-nakamura/adventofcode2020 | /day6.py | 2,109 | 3.609375 | 4 | # * * * * * * * * * * * *
# Setup
# * * * * * * * * * * * *
f = open("day6test.txt", "r")
test = f.read().split('\n\n')
"""
* * * * * * * *
* Part 1 *
* * * * * * * *
def process_one_yes(group):
yeses = [0 for _ in range(26)]
for respondent in group.split():
answers = respondent.split()
f... |
d36c3d26a1d9fbff45c8e8adca94f9e25be56a48 | DonaldMcC/Kite_ROS | /scripts/file_csv_out.py | 1,642 | 3.546875 | 4 | #!/usr/bin/env python
import os
import csv
class CSVDataWrite:
""" For logging CSV files to disk for further analysis
"""
def __init__(self):
self.file_ref = None
self.csvwriter = None
def open_output(self, file_name='testoutput.csv', path='', reset_file=True):
""" Opens a f... |
2ed93fbd60480382bf2d2d698e5fd4e108cf21e5 | PervykhDarya/laba4 | /hardlevel1.py | 205 | 3.890625 | 4 | a2 = int(input("Enter a2: "))
a1 = int(input("Enter a1: "))
b = int(input("Enter b: "))
c1 = (a1+b)%10
c2 = a2+(a1+b)/10
print("result number of tens %.f" %c2)
print("result number of units %.f" %c1) |
25c50d242171b364ec66b323f32e07eee6cb5acb | PaulinaSurazynska/Movie-Trailer-Website | /media.py | 873 | 3.71875 | 4 | """module with allows to open URLs in interactive browser applications."""
import webbrowser
class Movie():
"""class with defines variables: title, storyline, poster and youtube_trailer
with will be used by instances (objects) of this class created in
marvel_best_movies.py
"""
def __init__(
... |
33a118086b3d9c2a8f0ffce343ec3c7ef384f768 | ermkv98/Algorithms | /app/array/arrayDefs.py | 401 | 3.71875 | 4 | def average_value(array):
average = 0.0
for i in range(len(array)):
average += array[i]
return average/len(array)
def dispersion(array, average_vaue):
sqr_diff = 0.0
for i in range(len(array)):
sqr_diff += pow((float(array[i])-average_vaue), 2)
return sqr_diff/len(array)
def ... |
a09a808c6860c9718f8cd28e5d53ae3df5952ab2 | jack-robs/OOPatterns | /strategyPattern/pyStratPattern/message.py | 475 | 3.578125 | 4 | # class that holds the message uses to encrypt/decrypt
class Message:
def __init__(self, message, strategy):
self.message = message
self.strategy = strategy
#confirm I can access strategy class
def getStrat(self):
return self.strategy
def getMessage(self):
return self.... |
81ee62cf84ed95ffd6ae78a2eb8c62d013da32f8 | ihommani/code-elevator-webpy | /Elevator_prober.py | 4,044 | 3.703125 | 4 | #! /usr/bin/env python
import unittest
from Elevator import elevator
class TestElevator(unittest.TestCase):
def setUp(self):
self.elevator = elevator()
def test_elevator_should_be_closed(self):
self.assertTrue(self.elevator.isClosed())
def test_elevator_should_be_opened(self):
... |
ac5573705fda6daf26a00c81ff81082d38fff4ff | songokunr1/Learning | /sortowanie/sortowanie_numpy.py | 393 | 3.734375 | 4 | import numpy as np
dtype = [('name', 'S10'), ('height', float), ('age', int)]
values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
('Galahad', 1.7, 38)]
a = np.array(values, dtype=dtype) # create a structured array
np.sort(a, order='height')
np.sort(a, order=['age', 'height'])
#https://thispointer.c... |
0ef11fe30fd087f558f74c2b8bf6fc90216eaddb | henrique-voni/genetic-tsp | /genetic.py | 6,806 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Algoritmo Genético - Henrique Voni
"""
import numpy as np, random, operator, pandas as pd, matplotlib.pyplot as plt
## Classe de cidade
class City:
## Inicializa classe
def __init__(self, x, y):
self.x = x
self.y = y
## Calcula distância... |
021995fbba11c5c7a36dbc72dc3dad138963b248 | zhouwy1994/Notes | /yisiderui/study on python.py | 15,877 | 3.8125 | 4 | #=========================================python2.x=================================================================
#usr/bin/python
#coding=utf-8#֧ı,pythonĬֻ֧ASCII
pythonԲͬľ{}࣬ԼһЩж
pythonʹʾΣͬһȱҪͬ
if True:
print "true"
else:
print "flase"
Ȳһ»ʹõһܱIndentationError//
Ծʹͬոtab
if else:
ͬpythonʹ\Ϊдһ
а() {} []ͲûзҲdays = ... |
967be7d4e6ec559afa37a0e1265471c91324c900 | v-erse/pythonreference | /Science Libraries/Matplotlib/Object Oriented Matplotlib/animationexample.py | 732 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create figure with black background colour
fig = plt.figure(facecolor="black")
# Create ax with no frame, add to figure
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2), frameon=False)
fig.add_axes(ax)
# and no ticks
ax.set_xti... |
b7a9fd5df201d510c5c6af3d1f9ae8ea9f75b731 | conalryan/python-notes | /classes/inheritance.py | 1,861 | 4.53125 | 5 | #!/usr/bin/env python
"""
Inheritance
Specify base class in class definition
Call base class constructor explicitly
One or more base classes can be specified as part of the class definition
Default base class is object
Base class must already be imported
Classes may override methods of their ba... |
d8ebfc53bcccd66e971b4ffbf49c2ba11800df52 | itamar19-meet/meet2017y1mini-proj | /snake.py | 4,376 | 3.59375 | 4 | import turtle
import random
turtle.tracer(1,0)
#map size
SIZE_X=1000
SIZE_Y=700
turtle.setup(SIZE_X,SIZE_Y)
turtle.penup()
turtle.speed(0.5)
sq_size = 20
start_len = 7
#intialize lists
pos_list = []
stamp_list = []
food_pos = []
food_stamps = []
snake = turtle.clone()
snake.shape("circle")
turtle.hideturtle()
snake... |
ea9c26a98ab7d67ff4c11a95b2675bd7a2409293 | torch-msdi/SWMM | /section_feature.py | 5,660 | 3.640625 | 4 | import math
class SectionFeature(object):
"""
单个断面计算方法
"""
def __init__(self, data, depth):
"""
:param data: 断面数据 e.g {'data':1, 'type': 'circle'}
"""
self.data = data
self.depth = max(0, depth)
def section_area(self):
"""
... |
2df2a888c6d8b77b37132925f204c981c32281f7 | licup/interview-problem-solving | /Module 3/singleNum.py | 505 | 3.921875 | 4 | def single_number(integers):
integers.sort() #sorts all of the numbers in array
i = 0
while i < len(integers) - 1:
if integers[i] == integers[i+1]: #if first instance of number is equal to the next one it is not a single num
i += 2
else:
return integers[i]
return integers[-1] #returns last ... |
4eff0acc1f2f8e75a0ece1c17c65631d2bbfa4ac | bdrummo6/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 3,176 | 4.1875 | 4 | class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class LinkedList:... |
f0915014aaed09a8b7b937f39501caafde5b8218 | 1790113591/study | /python/20201022:Python第2天课后资料包/课堂示例代码/deffunc/prime/prt_prime.py | 238 | 3.671875 | 4 | # 组员A:
from deffunc.prime.util import isprime
print("=============== 打印500到800之间的素数 ==================\n")
for n in range(500, 801):
if isprime(n):
print(n, end=" ")
print("\n谢谢使用!")
|
16f43100e6b91757365690443007b373f80d54a9 | nervaishere/DashTeam | /python/HOMEWORK/6th_Session/Answers/Class/2/T2.py | 258 | 4.125 | 4 | a=int(input("Enter number of hour:"))
b=int(input("Enter number of minute:"))
if( b>=60 or a>24):
print("The number of hour or minute is nit valid")
else:
if a>12:
a=a-12
print(format(a, "0<2d"),":",format(b, "0<2d"))
|
397e742b1ddd0a151085b9436083a2588ea4d4d5 | fabriciovale20/AulasExercicios-CursoEmVideoPython | /Exercícios Mundo 3 ( 72 à 115 )/ex085.py | 575 | 4.1875 | 4 | """
Exercício 85
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que
mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente.
"""
numeros = [[], []]
for c in range(0, 7):
n = int(input(f'Digite o {... |
748e4ed6103eed08699f86d1a9744fb9213c6bec | inlike/Python-algorithm | /希尔排序.py | 521 | 3.9375 | 4 | # -*- coding:utf-8 -*-
def shell_sort(alist):
"""希尔排序"""
n = len(alist)
gap = n // 2
i = 1
while gap > 0:
for j in range(gap, n):
i = j
while i > 0:
if alist[i] < alist[i - gap]:
alist[i], alist[i - gap] = alist[i - gap], alist[i]
... |
d59bc12d7e649b4d3f962718bc10ce93dc86e26c | cccccyclone/Maleapy | /src/ex3/pictrans.py | 1,875 | 4.1875 | 4 | #!/usr/bin/python
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def imageToMatrix(filename):
im = Image.open(filename)
# im.show()
width,height = im.size
# L model means the picture will be convert to grayscale picture. And the following formula is used to convert RGB colo... |
54fa64f4b5ed2c223c5e76a5ffab9eec517fecc0 | pengwa1234/unbuntuCode | /thread/08锁的方式解决共享变量的问题.py | 574 | 3.796875 | 4 | from threading import Thread,Lock
import time
def main():
t1=Thread(target=test1)
t1.start()
t2=Thread(target=test2)
t2.start()
print("main----%s"%g_num)
mutex=Lock()
g_num=0
def test1():
global g_num
if mutex.acquire():
for i in range(1000000):
g_num+=1
mut... |
d3df6a9dfdf79fc9139878f23fbe84eb798f5c35 | spring-2018-csc-226/a03 | /a03_Horinet.py | 2,721 | 4.46875 | 4 | #######################################################
# Author: Tayttum Horine
# Purpose: To better understand turtles and incorporate new ideas
#######################################################
import turtle
def make_square (t): # creates bottom of house
"""
The function creates the base of the hous... |
515e1a116e38030f0911e56b2d53afde97e89466 | znelson/advent-of-code | /2015/day14.py | 3,080 | 3.71875 | 4 | #!/usr/bin/env python
data = """
Rudolph can fly 22 km/s for 8 seconds, but then must rest for 165 seconds.
Cupid can fly 8 km/s for 17 seconds, but then must rest for 114 seconds.
Prancer can fly 18 km/s for 6 seconds, but then must rest for 103 seconds.
Donner can fly 25 km/s for 6 seconds, but then must rest for 14... |
60f2897f3a07d8de9b6e96d896ba54e62c5772d6 | yuriy-lishchynskyy/NBANetworkAnalysis | /nba_network_draw_graph.py | 2,256 | 3.5 | 4 | import networkx as nx
import os.path
import matplotlib.pyplot as plt
# INPUT ANALYSIS YEAR
year = input("Please enter year (minimum 2013-14): \n")
team = input("Please enter team (e.g. GSW): \n")
game_type = input("Please enter game type (1 = regular season, 2 = playoffs): \n")
if game_type == "1":
game_s = "Regu... |
7dff8f54ba315b3fc408d409bb271b21e4b2380f | mtz99/GHDevOpsSurvey | /survey1.py | 513 | 3.65625 | 4 | fname = input(str("Enter your first name:"))
lname = input(str("Enter your last name:"))
dob = input("Enter your date of birth:")
email = input(str("Enter your email:"))
zcode = input("Enter your zip code:")
city = input(str("Enter your city:"))
state = input(str("Enter your state:"))
race = input(str("Enter your race:... |
4b686c6105f5cb212ff278dc10698033bb848898 | LeoVilelaRibeiro/opfython | /opfython/math/distribution.py | 834 | 3.890625 | 4 | import numpy as np
from opfython.math.random import generate_uniform_random_number
def bernoulli_distribution(prob=0.0, size=1):
""" Generates a bernoulli distribution based on an input probability.
Args:
prob (float): probability of distribution.
size (int): size of array.
Returns:
... |
ec7b5f363f3d0914136ec07f794f97b171d1fdec | underseatravel/AlgorithmQIUZHAO | /Week_06/438_find_all_anagram_in_a_string.py | 609 | 3.65625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 12:12
# @Author : weiyu
# @File : 438_find_all_anagram_in_a_string.py
import collections
class Solution:
def findAnagrams(self, s, p):
res = []
pdic = collections.Counter(p)
sdic = collections.Counter(s[:len(p) - 1])
... |
dac705193706434becc7c8bf9f8c719618d34f65 | PravallikaJuturu/Assignment3 | /starttomiddle.py | 247 | 3.875 | 4 | print('Enter list of elements')
list=input()
newList=list.split(' ')
midIndex=int(len(newList)/2)
print('all elements from the middle to end in list',newList[midIndex:])
print('all elements from the start till middle in
list',newList[:midIndex])
|
4fbbbeeb2689ef76ec53d707af9ca39a8c85f383 | alexxa/Python_Google_course | /03_wordcount.py | 3,248 | 4.46875 | 4 | #!/usr/bin/python
#PERFORMED BY: alexxa
#DATE: 19.12.2013
#SOURCE: Google Python course
# https://developers.google.com/edu/python/
#PURPOSE: Basics.
# The original course and exercises are in Python 2.4
# But I performed them in Python 3
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0... |
477aca3a366ff7509d6341c4a3179e7feb47d413 | prstcsnpr/Algorithm | /src/srm/598/ErasingCharacters.py | 994 | 3.734375 | 4 | import unittest
class ErasingCharacters(object):
def simulate(self, s):
while True:
result = s
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
result = s[0:i] + s[i+2:]
if result == s:
return result
else:
... |
515457751bf900c44ff0f925bff390ee768577f9 | dankarthik25/python_Tutorial | /UdemyTutorials/s05_01_input.py | 114 | 3.859375 | 4 | name = input("Give Input to python ")
print("Given input is : " + name)
for num in [1, 2, 3, 4]:
print(num)
|
ccdf2b64d909bb91839eff3d3940e2330144dd87 | billm79/COOP2018 | /Chapter07/U07_Ex11_LeapYear.py | 1,860 | 4.4375 | 4 | # U07_Ex11_LeapYear.py
#
# Author: Bill Montana
# Course: Coding for OOP
# Section: A3
# Date: 24 Oct 2017
# IDE: PyCharm Community Edition
#
# Assignment Info
# Exercise: 11
# Source: Python Programming
# Chapter: 7
#
# Program Description
# Function that calculates if a given year is a leap year. ... |
ba4ec9be19e027c6da1cd86921597862874d8d7e | enzoyoshio/Problemas | /problema1.py | 645 | 4.1875 | 4 | # lista de dicionario dado
listDict = [
{1 : 1, 2 : "oi", "nome" : "obrigado"},
{"Bolo" : "Cenoura", "Camarão" : "Verde", "nome" : "Sagrado"},
{1 : 10, "nome" : "oi", "caracol" : "obrigado"},
{"nome":"obrigado"}
]
# a chave que será procurada
nome = "nome"
# inicializando a lista vazia
lista = []
# ... |
ada748d900dda911919cd47340b0a0515df65490 | mrhoran54/basic_csv_splitter | /csv_splitter.py | 1,669 | 3.828125 | 4 | import os
def make_new_filename(row):
output_name='output_%s.csv'
x = './' + (output_name % row)
return(x)
def split(filehandler, num_of_rows, keep_headers):
"""
Splits a CSV file into x number of rows
"""
import csv
index = 1
#can specify the delimiter here
... |
0532a7f6077472c878e362508256222175d549da | sapscode/Code-Files | /Python test files/CSV/csv_parse.py | 1,813 | 4.4375 | 4 | import csv
### READING FORM A CSV
"""
with open('names.csv','r') as csv_file:
csv_reader = csv.reader(csv_file) #creating a reader to read from the files
for line in csv_reader:
print(line) #will give a list of all the values
print(line[2]) #to print the email column
"""
### WRITING TO A CSV... |
fa4b4776ca8e329698a58f3e4cb5d1cbba78ca45 | daniel-reich/ubiquitous-fiesta | /CzrTZKEdfHTvhRphg_20.py | 589 | 3.6875 | 4 |
def pgcd(num1, num2):
for val in range(min(num1, num2), 0, -1):
if num2%val == 0 and num1%val == 0 : return val
def mixed_number(frac):
up, down = list(map(lambda elm: int(elm), frac.split('/')))
if up == 0: return '0'
up = abs(up)
div = pgcd(up, down)
up, down = up//div, down//div
... |
c788c0621364acf2c4bd9be2693c1f534d5d2a10 | JMBoter/Euler-Problems | /5_SmallestMultiple.py | 336 | 3.546875 | 4 | import util
i = 11
found = False
while (found == False):
found = True
for j in range(1,11):
if i %j != 0:
found = False
break
i += 1
#print (i-1)
def smallest_multiple_upto(x):
n = 1
for i in range(1,x+1):
n = util.lcm(n,i)
return (n)
print (smallest_mu... |
f81126eac13f27633c0b7708db39b6c75fc683a3 | hiroshi415/pythonweek2 | /test/1_rpswith2players.py | 4,272 | 4.03125 | 4 | def rsp():
player1 = input('What is your name? ')
player2 = input('What is your opponent name? ')
player1choice = input(player1 + '! Rock, Scissors, or Paper? ').lower()
player2choice = input(player2 + '! Rock, Scissors, or Paper? ').lower()
if(player1choice == player2choice):
print("It's ... |
93eac8614c32ce9eb442fbab1169088b83f3d963 | liyunkuo/python | /0312-3.py | 358 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
1100312
作業三
一個整數:它加上100後是一個完全平方數,
再加上168又是一個完成平方數,請問它是多少?
"""
import math
for num in range(1,1001) :
n = math.sqrt(num + 100)
m = math.sqrt(num + 268)
if n == int(n) and m == int(m) :
print(num)
|
58ab7f4892dfff52a4988928dda61eae8eca2629 | ililiiilil/Algorithms-Python- | /BaekJoon/BOJ2751-1.py | 697 | 3.625 | 4 | import sys
n = int(sys.stdin.readline())
arr = []
for _ in range(n):
arr.append(int(sys.stdin.readline()))
def merge_sort(arr):
if len(arr) < 2:
return arr
mid = len(arr) // 2
low_arr = merge_sort(arr[:mid])
high_arr = merge_sort(arr[mid:])
merged_arr = []
l = h = 0
... |
0daf019552713456251ab569f4206d8536e97bcd | pauloALuis/LP | /SeriesDeProblemas2/pb4.py | 1,408 | 4.5625 | 5 | #!/usr/bin/env python3
"""
pb1.py
18/08/2021
"""
import random
import math
#4.a)
def generate_list(n: int = 10):
"""
function that generates a list
@param n : length of the list
@return list with pair numbers between 0 and 50
"""
l=[]
[l.append(random.randint(0,25) * 2) for _ in range(0,... |
d4a2dcff93d43bcfa30f41dc8f76d9ff4fecaa3f | justyna-eevee/codecool_week_pair2_homework | /hello_world/helloinput.py | 327 | 3.546875 | 4 | def get_user_name():
name = input('What is your name? ')
return name.upper()
def get_hello_message():
name = get_user_name()
if name:
return f'Hello, {name}!'
else:
return 'Hello World!'
def say_hello():
print(get_hello_message())
if __name__ == "__main__":
say_hello... |
990b1068c0d749c9ed29bcec9d29907f23318045 | richardcinca/CursuriPY | /Functions/ex1.py | 388 | 3.578125 | 4 |
lista=[]
count=0
while count<5:
number=input('>>')
lista.append(int(number))
count+=1
# print(lista)
#VARIANTA PRIN ACCESARE ELEMENTE LISTA
suma=0
for i in range(0,len(lista)):
suma=suma+lista[i]
print(f' Total = {suma}')
#VARIANTA PRIN ITERARE SI ADUNARE
# def sum(lista):
# suma=0
# for i i... |
0656314b2fa7826f4cc2f3ddad88598eb253f217 | fmojica30/leetcode_practice | /sliding_puzzle_2.py | 1,379 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from copy import deepcopy
class Queue(object):
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
return
def dequeue(self):
return self.queue.pop(0)
class Solution():
def slid... |
c62e4e3bdd7032ea780bd5cf9604c6fe44c5b1ec | Exia01/Python | /Self-Learning/iterators_and_generators/generators.py | 914 | 4.3125 | 4 | # generators are iterators
# example:
# def count_up(max):
# count = 1
# while count <= max:
# yield count # yield has a next stores the most recent cycle
# count += 1
# total_count = count_up(20)
# print(list(total_count))
# print(help(count_up))
# counter = count_up(20)
# print([x for x in... |
a5b809d24686527234468793fdeeb6e09cbe0bd7 | PawarKishori/QSE | /two_relations.py | 1,039 | 3.65625 | 4 | import sqlite3
conn=sqlite3.connect('Treebank_English.db')
def rel2(conn):
cursor=conn.cursor()
cursor2=conn.cursor()
x=input("enter the first relation\n:")
y=input("enter the second relation\n:")
x="'"+x+"'"
y="'"+y+"'"
cursor.execute('SELECT p.rel, c.rel, count(1) FROM Tword p INNER JOIN T... |
13a74e73a06e7a857e173236caf743831548e581 | pgenev/Programming101-Tasks-Completion | /Week1/1.Warmups/factorial_digits.py | 274 | 3.8125 | 4 | from factorial import factorial
def fact_digits(number):
sum = 0
number = abs(number)
while(number != 0):
sum += factorial(number % 10)
number = number // 10
return sum
print(fact_digits(111))
print(fact_digits(145))
print(fact_digits(999)) |
939e9ea2fc1fa96b44832cf07816de6186a0299e | wy/ProjectEuler | /solutions/problem56.py | 508 | 3.515625 | 4 | # coding: utf8
# Author: Wing Yung Chan (~wy)
# Date: 2017
# Powerful Digit Sum
# maximise the digits sum of a^b for a,b < 100
def digitsum(n:int) -> int:
s = str(n)
d = 0
for c in s:
d += int(c)
return d
def problem56():
max = 0
for a in range(99,0,-1):
for b in range(99,0,-1... |
673f125787776592babd1e9b450b1416fc118ce7 | likesfish/learning | /homework6.py | 257 | 3.984375 | 4 |
for i in range(1, 101, 1):
if i % 2 == 0 and i % 3 == 0:
print (i, "fizzbuzz")
elif i % 2 == 0:
print (i, "fizz")
elif i % 3 == 0:
print (i, "buzz")
else:
print (i, "you're still a number")
|
b8200fa038012b6c307f7bd22ef65e58ecf730d8 | sakumiak/clearcode_tasks | /task2.py | 1,859 | 4.0625 | 4 | #Python intern task - task2
#Function damage
# Inputs spell: str
# Outputs: dmg: int
# This function check if spell is spell and counting damage points.
def damage (spell):
dmg = 0
subspells_dict = {'fe': 1, 'je': 2, 'jee': 3, 'ain': 3, 'dai': 5, 'ne': 2, 'ai': 2}
subspells_list = ['fe','jee','je','ain','dai',... |
6ec7185ea8a03d14d4b87468e1882b5e61e25006 | rishabkatta/CDSusingPython | /people.py | 5,486 | 4 | 4 | _author = 'sps'
"""
CSCI-603: String/File/List/Dictionary Lecture (week 5)
Author: Sean Strout @ RIT CS
This is a demonstration program for strings, files, lists and dictionaries.
It takes a comma separated file (CSV) that contains basic information about
individuals (one per line):
id,first_name,last_name... |
31e4558361382063fa321a39c9f25f210e2085de | arnabs542/Competitive-Programming | /CodeForces/problem/A/996A_HitTheLottery.py | 323 | 3.578125 | 4 | # https://codeforces.com/problemset/problem/996/A
money = int(input())
bills = 0
if money>=100:
bills += money//100
money -= bills*100
if money>=20:
bills += money//20
money -= (money//20)*20
if money>=10:
bills += 1
money -= 10
if money>=5:
bills += 1
money -= 5
print(bills + mon... |
ec3988f213783578a6d95d25921099300e6a6421 | pauloestrella1994/automate_stuffs_with_python | /regular_expressions/begin_finish_regex.py | 1,643 | 3.90625 | 4 | import re
#Match the object only with it's in the begging of the string (^)
beginRegex = re.compile(r'^Hello')
mo = beginRegex.search('Hello there!')
mo2 = beginRegex.search('He said "Hello"')
print(mo.group())
if not mo2:
print("Can't match object")
#find the object in the final of the string ($)
endRegex = re... |
16533f2f86a3481580c1d6fe93e774bfe3b6e231 | RDAW1/Programacion | /Practica 1/Exercici_03.py | 162 | 3.953125 | 4 | print 'ACTIVIDAD 3: NUMERO PAR O IMPAR'
print 'Escribe el numero'
n=input()
if n % 2==0:
print 'El numero es par'
else:
print 'El numero es impar'
|
d742337caf58417de0b4880feb142ca0107415cb | LordGhostX/unittest-intro | /test_calc2.py | 718 | 3.53125 | 4 | import unittest
import calc
class TestCalc(unittest.TestCase):
def setUp(self):
self.first_number = 10
self.second_number = 5
def tearDown(self):
print("tearDown Class")
def test_add(self):
self.assertEqual(calc.add(self.first_number, self.second_number), 15)
def tes... |
5620c9d334d8aa2a72966f870979f1a6eb44b307 | ServePeak/proj2-pd6-08-JASE | /stuyteachers.py | 11,677 | 3.5 | 4 | ## ACCESS TEACHER LIST:
## getTeachers(SORT)
## available options:
## - first
## - last (DEFAULT if left blank)
## - title
##
## returns dictionary of sorted results
import urllib
import json
import math
from bs4 import BeautifulSoup
from operator import itemgetter
from pymongo import MongoClient
# our functions
i... |
c44362d571f8beaa1e5c2ddcdd137249f5460de0 | PChalmers/LearnJava | /Python course/src/ProblemSet1_3.py | 1,005 | 3.78125 | 4 | '''
Created on Jan 14, 2015
@author: ca0d0340
'''
def main():
s = 'ygcgfislipsdbqggjzkff'
resultString = ''
tempString = ''
previousLetter = ''
rIndex = 0
while rIndex < len(s):
currentchar = s[rIndex]
# print previousLetter, currentchar, tempString, result... |
3b8953b116afa01d745ead8c3a47cb2019506b10 | max-zia/nand2tetris | /assembler/symbol_table.py | 1,444 | 4.03125 | 4 | """
Keeps a correspondence between symbolic labels in a Hack assembly program
and numeric addresses.
"""
def constructor():
"""
Creates a new empty symbol table. In this case, the structure used to
represent the relationship between symbols in a Hack assembly program
and RAM and ROM addresses is a hash table (i.e... |
ace23dddc3ad7631687d0908389aee5aefaef734 | XavRobo/Pyton_vrac | /test_json/test.py | 485 | 3.53125 | 4 | import json
# fix this function, so it adds the given name
# and salary pair to salaries_json, and return it
def add_employee(salaries_json, name, salary):
salaries[name] = salary
return json.dumps(salaries)
# test code
with open('salaries.json', 'r') as f:
salaries = json.load(f)
new_salaries = add_empl... |
01d0d828f97f77f1ceb97243f9347cd9678a07e8 | Arindaam/Class-work | /Data Structures/Misc/open_ma.py | 5,396 | 3.765625 | 4 | import turtle
happy=turtle.Screen()
happy.bgcolor("black")
turtle=turtle.Turtle()
turtle.shape("circle")
turtle.color("peru")
turtle.width(9)
turtle.speed(11)
colors=["white","ivory","dark orange","coral","cyan","hot pink","gold","ivory","yellow","red","pink","green","blue","light blue","light green",]
def move(x,y):
... |
a9ce6d71e3d7283c5895936b0d3d22e2bdcf53e5 | feadoor/advent-of-code-2018 | /13.py | 7,250 | 3.546875 | 4 | TURN_LEFT = 0
TURN_STRAIGHT = 1
TURN_RIGHT = 2
UP = 0
LEFT = 1
DOWN = 2
RIGHT = 3
def replace_cart(track_segment):
if track_segment == '<' or track_segment == '>':
return '-'
elif track_segment == '^' or track_segment == 'v':
return '|'
else:
return track_segment
def is_cart(c):
... |
5e1b14e6f2b5b769875111a2f34fe398ae0036c5 | aditepDev/python_101 | /l07_regular/Exercise/ValidateTel.py | 696 | 3.53125 | 4 | import re
# กำหนด แพทเทิล ของ tel
# ขึ้นต้อนด้วย 08 ตัวเลข - ตัวเลช 3 ตัว - ตัวเลช 4 ตัว
telRE = r'^08\d-\d{3}-\d{4}$'
try:
# เปิดไฟล์
file = open('/home/aditep/softwares/python/l05_io_FileHandling/io_Exercise/student','r')
allStds = file.readlines()
for s in allStds:
name = s.strip().split(","... |
3ae2000f2537b5156fe0ea29d52a70bfd89a6deb | yuhsh24/Design-Pattern | /Python/Proxy/Play.py | 996 | 3.75 | 4 | # -*- coding:utf-8 -*-
class Play:
def Play1(self):
pass
def Play2(self):
pass
def Play3(self):
pass
class Player(Play):
def Play1(self):
print "战役"
def Play2(self):
print "军团"
def Play3(self):
print "神器"
class ProxyPlayerVip1(Play):
... |
4481af310834026f36072d4283958c84145c4664 | totetmatt/project-euler | /03 - Largest prime factor/main.py | 288 | 3.5 | 4 | number = 600851475143
import math
def isPrime(n):
for j in range(int(n/2)+1,2,-1):
if n % j == 0:
return False
return True
i = int(math.sqrt(number))
while i:
if number % i == 0:
if isPrime(i):
print(i)
break
i -=1 |
8d8a81f6a1a75a526b9037ed39036abd856985b7 | KshitizS26/computer-vision-programming | /rotation.py | 1,382 | 3.890625 | 4 | import numpy as np
import argparse
import imutils
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
cv2.imshow("Original", image)
cv2.waitKey(0)
'''
rotating the image around its cente... |
948eaf86cb9dfc470f056d4fddc78c6711daee9f | kellyo1/gwcfiles | /Test Folder/listchallenge.py | 1,934 | 4.09375 | 4 | #imports the ability to get a random number
from random import *
aRandomNumber = randint(0,100)
print("This will generate a random number from 0 to 100")
print(aRandomNumber)
#create the list of wods you want to choose from
#this will be a random generator for food (menu)
dinnermenu = ["burgers and fries", "pasta", ... |
37853fc2a44555fdd160ebe39c4cdf5f79f9b7c8 | ShitalBorganve/raspberrypi | /projects/image_processing/background_change.py | 1,908 | 3.640625 | 4 | #!/usr/bin/env python
'''
This program takes an image and changes the background for a given one.
It shows in two windows the original with the background detected and colore
d as black and the image with the background changed.
The *** USER tag in the comments is to point good places where the user
can modify it fo... |
0e6c48c0ee2b28da2014fd9f5ccb21bf1b9f8b96 | recooper1066/pythonExercises | /FromBook/Chapter 02/2.4.py | 552 | 4.21875 | 4 | # Exercise 2.4
# Bob Cooper
# Exercise 4: Assume that we execute the following assignment statements:
width = 17
height = 12.0
# // Floor Division operator - divide and throw away remainder.
print(width//2, ' ', type(width//2))
# // Modulus operator - divide and return remainder.
# not in exercise, but related to flo... |
82eda89e3bc67a9dfbe3ca9e148ca316e6b1e5d1 | RJPlog/aoc-2020 | /day23/python/asung/solution.py | 2,232 | 3.875 | 4 | #!/usr/bin/env python3
import os
from typing import Dict, Iterator, List
class Solver:
def __init__(self, filepath: str) -> None:
with open(filepath, 'r') as text_file:
self.cups = [int(label) for label in text_file.read().strip()]
@staticmethod
def solve(cups: List[int], move_count: ... |
c6529c7e2b78cd6ce44b4dd8aa806d6ea445d722 | starmi/python-learning-projects | /Pandas/dataManipulation.py | 1,901 | 3.609375 | 4 | # How to manipulate DataFrames and make transformations
# Dataset: https://www.ars.usda.gov/northeast-area/beltsville-md/beltsville-human-nutrition-research-center/nutrient-data-laboratory/docs/sr28-download-files/
import pandas
food_info = pandas.read_csv("food_info.csv")
#attributes on pandas DataFrame objects: pand... |
d2b95ce6c8853c64dc2c70023cd839a41db454cd | freedream520/python_notes | /examples/start/default_arg.py | 173 | 3.703125 | 4 | '''
Created on 2013-9-12
@author: Administrator
'''
def f(a, L=None):
if L == None:
L = []
L.append(a)
return L
print f(1)
print f(2)
print f(3)
|
320657bfc81b924c93e0867405297ecfb5cf361c | astroML/astroML | /astroML/stats/_binned_statistic.py | 13,324 | 4.375 | 4 | import numpy as np
def binned_statistic(x, values, statistic='mean',
bins=10, range=None):
"""
Compute a binned statistic for a set of data.
This is a generalization of a histogram function. A histogram divides
the space into bins, and returns the count of the number of points i... |
636d2ccf2699b1e2e3f04a394a094d55c0571b2a | Freewin/mclass | /Chapter_2_and_3/mulit_inheritance_depth_first.py | 334 | 3.546875 | 4 | # Example of depth first search presented in class
class A(object):
def dothis(self):
print("Doing this in A")
class B(A):
pass
class C(object):
def dothis(self):
print("Doing this from C")
class D(B, C):
pass
d_instance = D()
d_instance.dothis()
# Method Resolution Order
p... |
1bdaf816b75fac3fc43f4d1d40eb0884fe1fd142 | DiegoFFreitas7/Teste_IA | /teste_Maximizacao.py | 3,575 | 3.546875 | 4 | from random import randint
from algoritmo_Genetico import Individuo, Algoritimo_Genetico
'''
PROBLEMA
Existe 3 tipos de item para se colocar em uma caixa de capacidade igual a 20Kg
A massa, valor e peso de cada item e descrito abaixo
Item Quantidade Massa(Kg) Valor(R$)
item_A 3... |
0c55851543194d3c79a6559a2bcdfbffaf5dc701 | DavidMetcalfe/USB-drive-mounted-check | /USB_drive_mounted_check.py | 919 | 3.59375 | 4 | # ------------------------------------
# Loops through available drives and returns
# the drive letter if one matches the given
# drive name. If none match, return 0.
# Ideal for checking if a specific USB
# drive is mounted.
#
# David Metcalfe, January 19, 2020
# ------------------------------------
impo... |
1f7417c373569e0b62bc56f4a155524b40ae9a5d | vmnchv/PYTHON_ALGORITMS | /Lesson3/DZ3_3.py | 293 | 3.84375 | 4 | #В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
from random import random
N = 15
arr = [0]*N
for i in range(N):
arr[i] = int(random()*100)
print(arr[i], end = ' ')
print() |
0b25194f3dd653e142230ac05a0a3fd21f79889a | LukeBreezy/Python3_Curso_Em_Video | /Aula 14/ex060.py | 682 | 4.1875 | 4 | from math import factorial
num = int(input('Digite um número e veja o fatorial: '))
fatorial = factorial(num)
print('''
Utilizando módulo factorial()
O fatorial de {} é {}'''.format(num, fatorial))
# ===========================================
print('=*' * 20)
fatorial = num
for i in range(num-1, 0... |
9873594ba403b3dea2f0dd65ddbb289e6c5f5ddb | sedychl2/sr-4-5-6-2 | /инд задание в питоне.py | 441 | 4.15625 | 4 | V = 3
A = 1
R = 1
H = 2
if V <= A**3 and V <= 3.14 * R**2 * H:
print("Жидкость может заполнить обе ёмкости")
elif V <= A**3:
print("Жидкость может заполнить первую ёмкость")
elif V <= 3.14 * R**2 * H:
print("Жидкость может заполнить вторую ёмкость")
else:
print("Слишком большой объём жидкости")
|
321a686854f00e2b0dc0c154f028b805362e658b | GGbb2046/ST018 | /Exercises/Class03/FutureValueCalc.py | 273 | 3.65625 | 4 | print("Welcome to the calculation of Future Value ")
PV= float(input("Please enter the present value "))
R= float(input("Please enter the rate of return in % "))
N= float(input("Please enter the time period "))
FV= PV*(1+(R/100))**N
print("The future value", "is ", FV)
|
a59842935dda5f68d114b28d26fed5a00ccb516e | hackvan/codecademy-examples | /python/bitwise_operator.py | 1,638 | 4.46875 | 4 | print 5 >> 4 # Right Shift
print 5 << 1 # Left Shift
print 8 & 5 # Bitwise AND
print 9 | 4 # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88 # Bitwise NOT
'''
In Python, you can write numbers in binary format by starting the number with 0b.
When doing so, the numbers can be operated on like any other number... |
6d4289059dd03ecf766f0020d0b72b863761b04a | hiitiger/cobackup | /py/object.py | 511 | 3.546875 | 4 | class WTF(object):
def __init__(self):
print("I ")
def __del__(self):
print("D ")
print(WTF() is WTF())
print(id(WTF()) == id(WTF()))
l = [1, 2, 3]
g = (x for x in l if l.count(x) > 0)
l = [1]
print(list(g))
array_1 = [1,2,3,4]
g1 = (x for x in array_1)
l1 = [x for... |
9b0bbc5aa8c4ce11df81e3107001bea30c4fc83a | dstch/my_leetcode | /Breadth-first Search/Perfect Squares.py | 1,896 | 3.78125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: dstch
@license: (C) Copyright 2013-2019, Regulus Tech.
@contact: dstch@163.com
@file: Perfect Squares.py
@time: 2019/9/19 15:25
@desc: Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.