blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
da208b91fc0a69c00027e586d6e02a74a6cadb85 | harshitbhat/Data-Structures-and-Algorithms | /GeeksForGeeks/DS-Course/001-BitwiseOperators/004.leftShift.py | 309 | 3.984375 | 4 | '''
Left Shift Operator ( << ): It shifts the bit left by the amount specified and adds 0 in same amount to the right side of the number, thus it multiplies the number.
i.e x << y, this implies that resultant is x * (2^y)
'''
x = 3
print(x << 1) # 6
print(x << 2) # 12
print(x << 3) # 24
print(x << 4) # 48 |
5f3ca88b3366568b983118f161fb80c9f9f4880f | Zahidsqldba07/python_course_exercises | /TEMA 2_CONDICIONALES/Condicionales/ej2.5.py | 520 | 4.09375 | 4 | #!/usr/bin/python3
#Programa que te dice de una entrada de tres numeros cual es mayor
try:
num1=int(input("Introduce un número: "))
num2=int(input("Introduce un número: "))
num3=int(input("Introduce un número: "))
if num1 > num2 and num1 > num3:
print("El numero " + str(num1) + " es mayor")
elif num2 > num... |
337a56ee750ded41572f55120085f69a0b162681 | jefethibes/Aulas | /Python/Python/ExeLista24.py | 673 | 4.1875 | 4 | '''24 - Receba duas listas e exiba a união destas listas e a intercalação destas listas,
isto é, 1º da 1ª lista, 1º da 2ª lista, 2º da 1ª lista, 2º da 2ª lista.'''
lista1 = []
lista2 = []
lista_intercalada = []
print('Digite 5 elementos para a lista 1:')
for i in range(5):
lista1.append(input('Elemento {}: '.fo... |
c35b4f4a265ac6fb6351f8900a4d988b34f761cf | boaass/KKB | /PrerequesiteTest/Spiral Memory/main.py | 1,387 | 4.25 | 4 | # -*-coding:utf-8 -*-
# You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the
# grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward.
# For example, the first few squares are allocated like this:... |
253506493ba7aaa3c96220575f6bba56cc953eb8 | ccruz182/Python | /classes/computed_attr.py | 943 | 3.578125 | 4 | class Color():
def __init__(self):
self.red = 50
self.green = 75
self.blue = 100
def __getattr__(self, attr):
if attr == "rgbcolor":
return (self.red, self.green, self.blue)
elif attr == "hexcolor":
return "#{0:02x}{1:02x}{2:02x}".format(self.... |
9b2ea0618af53ecfa3681d71223c91cbe9c1c97a | gangtaehwan/wikidocs-chobo-python | /ch03/simpleInterest.py | 437 | 3.625 | 4 | def simple_interest(p, r, t):
return int(p * r * t)
def simple_interest_amount(p, r, t):
return int(p * (1 + r * t))
if __name__ == '__main__':
# Quiz 1
# ex 1
print(simple_interest(10000000, 0.03875, 5))
# ex 2
print(simple_interest(1100000, 0.05, 5/12))
# Quiz 2
# ex 1
p... |
0a09ae29470df5e0c78fa527c1a21d894bf6b8b7 | AFRothwell/Initial-Commit | /AdventOfCode/Day 2 Part 1.py | 2,121 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 1 16:02:59 2021
@author: Andrew Rothwell
"""
'''
--- Day 2: Password Philosophy ---
Your flight departs in a few days from the coastal airport; the easiest way
down to the coast from here is via toboggan.
The shopkeeper at the North Pole Toboggan Rental Shop is having... |
61dd764e56119cf38a9bcd22d442bd960a6b4530 | travismyers19/Vulnerable_Buildings | /get_soft_story_images.py | 2,357 | 3.671875 | 4 | # This script takes addresses from a csv file and gets the
# associated street view image and places it in the specified folder.
# the image is saved as "row.jpg", where row is the row number
# from the csv file.
from Modules.addresses import Addresses
from Modules.imagefunctions import write_image_to_file
import os
... |
e4219830969b332f808a1d22011db7dc9fefe644 | bossjoker1/algorithm | /pythonAlgorithm/Practice/2181合并零之间的节点.py | 855 | 3.671875 | 4 | # 我的解法,还行
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp, pre = head.next, head.next
while temp:
if temp.val == 0:
pre.next = temp.next
pre = temp.next
else:
if temp.next:
... |
0cd764409147e88bdc7202270f34c031b7ecf61b | madisonhoover4/cs1301 | /lab2.py | 7,436 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Georgia Institute of Technology - CS1301
Lab2 - API and Requests module - due Thursday, Mar. 30, 2017
"""
import requests
import time
from collections import Counter
__author__ = "MADISON HOOVER"
__collaboration__ = """ I worked on this assignment alone using only this semester's course mate... |
76e13b5ceaea6b9712b606579080561031567b10 | adamgiesinger/face_recognition | /recognize_single_image.py | 2,892 | 3.859375 | 4 | import face_recognition
from PIL import Image, ImageDraw, ImageFont
import os
import sys
# This is an example of running face recognition on a single image
# and drawing a box around each person that was identified.
# i.e. python .\recognise.py knownPeople/
pathToKnownPeopleImages = sys.argv[1] # known persons
output... |
64c47a7c534c4b9c19a05c95c0f35157f4eb039c | mindful-ai/18012021PYLVC | /day_02/transcripts/tr_loops.py | 4,054 | 3.890625 | 4 | Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> s = "python"
>>> for c in s:
print("Oracle")
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
>>> for c in s:
print(s + " ----> " + "Oracl... |
3b502aefb3fbc20bdf29e0ae1240f2da5cb048dc | Lightman-EL/Python-by-Example---Nikola-Lacey | /N6_While_Loop/045.py | 128 | 4.0625 | 4 | total = 0
while total <= 50:
number = int(input("Input a number: \n"))
total += number
print("The total is ", total) |
f0c78f03dac86220cf439f55e87adbc3851b959e | rafaelperazzo/programacao-web | /moodledata/vpl_data/94/usersdata/250/55602/submittedfiles/mediaLista.py | 188 | 3.671875 | 4 | # -*- coding: utf-8 -*-
n=int(input('tamanho da lista:'))
a=[]
soma=0
for i in range (0,n,1):
a.append(int(input('valores da lista:')))
soma=soma+a[i]
media=soma/(len(lista))
|
67a0b069e1bfb8aebf90b0a79672a0bb4ab95bec | Udayan92/MyCodes | /hw2.py | 4,033 | 4 | 4 | # Name:
# Section:
# hw2.py
##### Template for Homework 2, exercises 2.0 - 2.5 ######
# ********** Exercise 2.0 **********
def f1(x):
print x + 1
def f2(x):
return x + 1
# ********** Exercise 2.1 **********
def outcome(player1, player2):
if player1 == 'rock' and player2 == 'rock'... |
d6a67a96ac198bddc2c634be05585b785c478f17 | math77/Algorithms | /alg12.py | 197 | 4.21875 | 4 | temp_fahrenheit = float(input("Digite uma temperatura em Fahrenheit\n"))
temp_celsius = ((temp_fahrenheit-32)*5)/9
print("A temperatura {}F é igual a {}ºC".format(temp_fahrenheit, temp_celsius))
|
72c1c97e234fd9f3ccde990bb06f225a6841409a | b1ueskydragon/PythonGround | /leetcode/p0205/isomorphic_strings_test.py | 695 | 3.515625 | 4 | import unittest
from .isomorphic_strings import Solution as A
class IsomorphicStringsTest(unittest.TestCase):
def test_true(self):
a = A()
self.assertTrue(a.isIsomorphic("egg", "add"))
self.assertTrue(a.isIsomorphic("paper", "title"))
self.assertTrue(a.isIsomorphic("egggggga", "add... |
1a1ee020e0be358ff99cee82739868a0333393c2 | DanielBrito/ufc | /Monitoria - Fundamentos de Programação/Lista 4 - Ítalo/18_potencia.py | 451 | 3.921875 | 4 | # Questão 18 - Lista 4 (Ítalo)
def potencia(x, n):
if x==0 or x==1 or n==1:
return x
if n==0:
return 1
if n<0:
return 1/potencia(x,-n)
val = potencia(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
base = ... |
6b28d8019957b930b545ce7d6c99012d529704f9 | MelodyChu/Juni-Python-Practice | /replit_practice2.py | 3,608 | 4.1875 | 4 | """a = int(input()) # 1234
b = a % 10 # =4
c = ((a - b)/10) % 10 # 1230/10 = 123; 123/10 % = 3
print (c*10 + b) """
"""# Find tens digit
a = int(input())
b = a % 10 #single digit
c = ((a - b)/10) % 10 #1230
print (c) """
"""
# Given 3 digit number find sum of digits
a = int(input()) # 123
b = a % 10 # single digit # ... |
3c639b552af6c69051dd973d6e47dcb8970d1ea7 | tab1tha/Beginning | /subclassList.py | 642 | 4.0625 | 4 | #in this program,a subclass is created which inherits the attributes of the built in class;list.
class Counterlist(list):
def __init__(self,*args):
super().__init__(*args)#the super function is used to initialise the superclass(es)
self.counter=0
def __getitem__(self, index):
self.counte... |
3ce1ae8fb2c61f03ff5cc9f91a711f3314ae6c26 | YutaGoto/daily_atcoder | /2021-01/abc153_d.py | 162 | 3.578125 | 4 | n = int(input())
c = 0
base = 1
while True:
c += base
if n == 1:
print(c)
exit()
else:
n = n // 2 + n % 2
base *= 2
|
868617839ea8bb08b64021b760d3411c1910ac5f | lilbond/bitis | /day3/abstract.py | 329 | 3.9375 | 4 |
import abc
class ABCClass(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def __str__(self):
raise NotImplementedError('users must define __str__ to use this base class')
class MyAbstractClass(ABCClass):
pass
# def __str__(self):
# return 'here i am!'
a = MyAbstractClass()
pr... |
c9f4f26c7af0e2935a332fa942b4b56af4d6bdc7 | jiacovacci/py_exam | /dict.py | 145 | 4.1875 | 4 | #!/usr/bin/python3
# DATA TYPE Examples
print('dictionary example')
x = {"name" : "John", "email" : "john.iacovacci1@gmail.com"}
print (x['name'])
print(type(x))
|
86455b3dfe936a558be2016f80b70268321327de | brysonpayne/teachkids | /ch03/Challenge2_ColorMeSpiralled.py | 1,045 | 4.59375 | 5 | # ColorMeSpiralled.py
import turtle # set up turtle graphics
t=turtle.Pen()
turtle.bgcolor('black')
# Set up a list of any 10 valid Python color names
colors=['red', 'yellow', 'blue', 'green', 'orange',
'purple', 'white', 'gray', 'brown', 'sea green']
# ask the user's name using turtle's textinp... |
05c564510bfdd0152f7d02fb01bef29dfb87b644 | MalahovMV/Neuron_network | /BP/main.py | 545 | 3.671875 | 4 | from Neuron import neuron
def main(rate_learn):
rate_learn = rate_learn
e = 0.00001
y_true = 0.3
input_x = [1, 2]
network = neuron(rate_learn, y_true, input_x)
while True:
network.calculate_values()
network.calculate_error()
print("Epoch= %2d" % network.epoch, " y=%7F" ... |
513c99ec2c59aec595e6e62e1361f2d5483f06a5 | sebastianlettner/tf-graph-tool | /tf_graph_tool/components/recurrent/binary_lstm/binary_stochastic_neuron/bsn_stochastic_model.py | 2,459 | 3.703125 | 4 | """ The stochastic model of the neuron. """
import tensorflow as tf
from tensorflow.python.framework import ops
import bsn_literals
class BsnStochasticModel(object):
"""
The BsnStochasticModel class provides tensors for sampling the preprocessed input ranging
from (0, 1) to either 0 or 1.
THere is a... |
3daf5fb969c1a3bcc401545fd18189004130ba02 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4464/codes/1734_2503.py | 206 | 3.609375 | 4 | from math import *
n = int(input("Fale a quantidades de termos da serie, macho: "))
soma = 4/1
cont = 1
while (cont < n):
soma = soma + (-1)**cont * (4/(cont*2+1))
cont = cont + 1
print(round(soma,8)) |
a9915a6586403bb57f670c76ae55fdacc69e0786 | functioncall/rescue-habit | /core/node/node.py | 1,112 | 4.15625 | 4 | class Node(object):
"""
A node instance contains a list of: next and previous nodes.
The basic unit of a Graph data structure.
"""
def __init__(self, name, data, nxt, pre):
"""
:param name: <str>
:param data: <object>
:param nxt: <list>
:param pre: <list>
... |
f62f534fe5c6a985d1b422419319683196353f5d | karanj1994/trafficDataAnalysis | /notebooks/trafficDataScrape.py | 4,069 | 3.703125 | 4 |
# https://www.dataquest.io/blog/web-scraping-tutorial-python/ - reference for Beautiful Soup Training
import requests # Gets the HTML from a webpage
from bs4 import BeautifulSoup # Used to parse HTML
import csv
highwayRankingWebpage = requests.get("https://reason.org/policy-study/24th-annual-highway-report/24th-ann... |
496b999de9fca738abffe346be78c739c54770a8 | nowlansavage/python-challenge | /PyPoll/main.py | 1,904 | 3.78125 | 4 | import os, csv
#initiate variables
num_votes = 0
candidates = []
unique_candidates = []
most_votes = 0
#name file path
csvpath=os.path.join('Resources','election_data.csv')
#read csv file
with open(csvpath) as datafile:
csvreader = csv.reader(datafile)
#skip header row
header = next(csvreader)
#Loop through dat... |
8e481e58fb41326850b35942b97d81dec95e5418 | tzyl/project-euler | /23.py | 649 | 3.828125 | 4 | def is_abundant(n):
"""Returns true if natural number n is abundant."""
if n < 12:
return False
factors = [1]
for x in xrange(2, int(n ** 0.5) + 1):
if n % x == 0:
if x ** 2 == n:
factors.append(x)
else:
factors.append(x)
... |
33b5f6d0706ac2abbf8b053f24af840ff380f064 | HuangYongBo/Messy | /learn_python/class/demo_project.py | 1,298 | 3.703125 | 4 | #!/usr/bin/env python3
#coding:utf-8
import sys,random
class Home(object):
def __init__(self,name,area,location):
self.name = name
self.area = area
self.location = location
self.furniture_count=0
self.furniture=[]
print("构造房子:%s"%(self.name))
print("房子位于:%s占地面积:%d"%(self.location,self.area))
def __del... |
3aa72886c3cf9e7e3cd62d610de1d137ce1a50b3 | lonelyarcher/leetcode.python3 | /BackTrack_Pruning_1307. Verbal Arithmetic Puzzle.py | 4,441 | 4.1875 | 4 | """ Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:
Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as ... |
247e4b45197456ba6468aabec1b625402319ca6e | mingming733/LCGroup | /Sen/Length_of_Last_Word.py | 856 | 3.75 | 4 | class Solution:
# @param {string} s
# @return {integer}
# def lengthOfLastWord(self, s):
# s = s.split(" ")
# print s
# for i in range(len(s) - 1, -1, -1):
# if s[i] != " " and s[i] != "":
# return len(s[i])
# return 0
def lengthOfLastWord(self, s):... |
fb21fdadf71c5772d2c94985f6a96248ffa9ef39 | Aasthaengg/IBMdataset | /Python_codes/p02713/s749235371.py | 211 | 3.5625 | 4 | import math
a = int(input())
lis =[]
ans = 0
for x in range(1,a+1):
for y in range(1, a+1):
lis.append(math.gcd(x,y))
for z in range(1, a+1):
for l in lis:
ans += math.gcd(z,l)
print(ans) |
0a716517744146d4dd316129612a863abf4cc072 | axlbrandonbezerra/Python | /hipotenusa.py | 544 | 3.8125 | 4 | #Autor: Axl Brandon Rodrigues
'''Calcula o comprimento da hipotenusa'''
from math import hypot
while True:
try:
co = float(input('Digite o comprimento do Cateto Oposto: '))
except ValueError:
print('Digite apenas valores numéricos!')
else:
break
while True:
try:
... |
f884ae24524855140f7bb8353596a631ff5a6f3d | gp-antennas/PythonBicone | /BiconeClasses.py | 3,706 | 3.734375 | 4 | #Classes for Bicone Algorithm
import numpy as np
import random
class Individual:
def __init__(self, chromosome = None, fitness = 0.0):
self.fitness = fitness #Fitness Score of the Individual
if chromosome is None: #Genetic material for the Individual
... |
359f2cc12436ff498469168080245c9be452e2bc | junekim00/ITP115 | /Assignments/ITP115_A8_Kim_June/ITP115_A8_Kim_June.py | 4,683 | 4.1875 | 4 | # June Kim
# ITP115, Fall 2019
# Assignment 7
# junek@usc.edu
# This program allows for a game of tic-tac-toe.
import random
import TicTacToeHelper
# checking to see if spot is open or not
def isValidMove(boardList, spot):
if boardList[spot] == "x" or boardList[spot] == "o":
return False
... |
d05deb33e9b3566dfa1e6188979516c3d9c68699 | Ys-Zhou/leetcode-medi-p3 | /201-300/215. Kth Largest Element in an Array.py | 1,033 | 3.8125 | 4 | # Runtime: 1492 ms, faster than 14.63% of Python3 online submissions
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def half_quick_sort(start, end):
if start == end:
return nums[... |
7c55dc7a024ffa65bc89b9855b0120796b616d22 | Rishikesh-G-Kashyap/Launchpad-Assignments | /Problem1.py | 159 | 3.9375 | 4 | name = input("Enter name: ")
age = int(input("Enter Age: "))
year = str((2019 - age)+100)
print("Hey " + name + "! You will turn 100 years old in " + year) |
21337566ed1cd5f8e815aa324fbfc77e7c302771 | samtaitai/py4e | /exercise1003.py | 857 | 4.09375 | 4 | import string
#file = input("Enter a file name: ")
file = input('Enter a flie name: ' )
hand = open(file) #not a method, but function
counts = dict()
#make a list of single words
for line in hand:
#str.maketrans; If three arguments are passed, each character in the third argument is mapped to None.
#every di... |
e0dbbbe93eca0d132c18e881aaa7770c74f0564e | Vlek/2048 | /2048.py | 2,323 | 3.828125 | 4 | #!/usr/bin/env python3
from random import choice, randint
class Twoohfoureight:
def __init__(self):
self.map = [[0]*4 for i in range(4)]
self._add_random_piece(2)
def print_map(self):
for i in self.map:
#print('\t'.join(map(str, i)))
print(i)
def _add_rand... |
19533558ae8212778f3f3c0a5596dbce44aacfa1 | carden-code/python | /stepik/code_review.py | 1,197 | 4.03125 | 4 | # A sequence of 10 integers is received for processing.
# It is known that the entered numbers do not exceed 10 ** 6 in absolute value.
# You need to write a program that prints the sum of all negative numbers in the sequence and
# the maximum negative number in the sequence.
# If there are no negative numbers, you nee... |
deb9eb639725ca8cf4abf150161ec37108db96b6 | HaugenBits/CompProg | /ProgrammingChallenges/Chapter_1/CheckTheCheck/ChecktheCheck.py | 4,658 | 3.546875 | 4 | import sys
class ChessBoard:
def __init__(self, cBoard, num):
self.cBoard = cBoard
self.num = num
self.kinginCheck = "no"
self.kingOnBoard = False
def checkForCheck(self):
for y, line in enumerate(self.cBoard):
for x, ele in enumerate(line.strip()):
... |
01f5182546b1f85cf48b0eff6996f61be58a8853 | AgguBalaji/MyCaptain123 | /areaofcircle.py | 338 | 4.46875 | 4 | """Calculate and print the area of the circle based on the user's input of the circle's radius"""
#user input--->taking the input only as int type
radius=float(input("Input the radius of the circle :"))
#calculating the area of the circle
area=3.14159*(radius**2)
#output
print(" The area of the circle with radius",r... |
dc01aaf3128f71e81e817cb2bce72219de20b4fd | CiceroLino/Learning_python | /Curso_em_Video/Mundo_1_Fundamentos/Usando_modulos_do_python/ex019.py | 536 | 4.09375 | 4 | #Desafio 019 do curso em video
#Programa que sortea um item da lista
#https://www.youtube.com/watch?v=_Nk02-mfB5I&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=20
from random import choice
print()
n1 = str(input('Primeiro item da lista: '))
n2 = str(input('Segundo item da lista: '))
n3 = str(input('Terceiro item da ... |
0cf56fe9cd607812d6e10adb0df38f2d6cb8fc96 | kresnajenie/curriculum-python | /4Loop/tebakangka.py | 387 | 3.96875 | 4 | angka_tebakan = 25 #Ini adalah angka yg benar
tebakan = 0 #Untuk menyatakan ada variabel tebakan
while tebakan != 25:
tebakan = int(input("Masukkan tebakan anda: ")) #Pengguna memasukkan tebakan yang nanti akan dievaluasi oleh program
if tebakan < angka_tebakan:
print("terlalu kecil")
if tebakan > ... |
50acb25ad11ad2a648774a7f3af8a0c7d869cca4 | ayk-dev/python-fundamentals | /exams/moving_target.py | 1,087 | 3.5625 | 4 | targets = list(map(int, input().split()))
while True:
line = input()
if line == 'End':
break
tokens = line.split()
command = tokens[0]
index = int(tokens[1])
if command == 'Shoot':
power = int(tokens[2])
if 0 <= index < len(targets):
targets[i... |
3847137f45bd2e9e9a7cdf117d51eefda0c89d8c | kiran-kotresh/Python-code | /replace_vowels_!.py | 133 | 4.15625 | 4 | vowels = 'aeiouAEIOU'
string = 'Hi! Hi!'
for x in string:
if x in vowels:
string = string.replace(x, '!')
print(string)
|
77eb64c6243ad773ab6bf39b4c27200c3e9574c6 | DilipBDabahde/PythonExample | /Assignment_2/Pattern4.py | 350 | 3.984375 | 4 | """
8).Write a program which accept one number and display below pattern.
Input: 5
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
"""
def Pattern4(iNo):
for i in range(0,iNo):
for j in range(0,i+1):
print(j+1,"",end="");
print("");
def main():
ival = int(input("Enter a val: "));
Pattern4(ival);
if __n... |
db6802cee6da68cc71141f1e3102c152a6f20d28 | sevdaghalarova/ileri_seviye_moduller | /odev1.py | 722 | 3.515625 | 4 | """Bilgisayarınızdaki tüm mp4,txt ve pdf dosyalarını os modülüyle arayın ve bunların nerede
bulunduklarını ve isimlerini ayrı ayrı
"pdf_dosyalari.txt","mp4_dosyaları.txt","txt_dosyaları.txt" adlı dosyalara kaydedin."""
import os
for klasor_yolu,klasor_islemi,dosya_islemi in os.walk("/Users/sevdaagalarova/Desktop"): # b... |
26ee4434e7df5fb3a8bf77ef5ce76ade7df5f213 | S3annnyyy/CS50-problem-set-solutions | /Pset 7/houses/import.py | 927 | 4.09375 | 4 | import csv
from sys import argv
from cs50 import SQL
#check for correct command line arguement
if len(argv) != 2:
print("Usage: python <filename>.csv")
exit()
#correct command line arguement
#database for file characters.csv for SQL
db = SQL("sqlite:///students.db")
#opening characters.csv
with open(argv[1],... |
6fbc2b5bf64aff170506cbaa0be992635012709d | NeaHerforth/Completed-Kattis-Files | /coldputer.py | 322 | 3.890625 | 4 | #! /usr/bin/env python3
import sys
#s=sys.stdin.read().splitlines()
s='''5
-14 -5 -39 -5 -7'''
s=s.splitlines()
#Number of temperatures collected
n=int(s[0])
#Temperatures
temp=s[1].split()
#Find out how many temps are below 0 degrees
count=0
for i in temp:
if int(i)<0:
count +=1
print(count)
#Accepte... |
1e0a761f589fe8f3cfc18b66a54af0437fe2c7fc | chlee1252/dailyLeetCode | /book/problems/impossibleCoin.py | 258 | 3.53125 | 4 | def solution(N, coins):
if 1 not in coins:
return 1
target = 1
coins.sort()
for coin in coins:
if target < coin:
break
target += coin
return target
print(solution(5, [1,2,4,7]))
print(solution(5, [3,2,1,1,9])) |
ff4bad85356533966f79bfa9578452229d8404da | paladino3/AulasPython | /Exercicios/ex017.py | 443 | 4.21875 | 4 | """
Desafio 017
Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo,
calcule e mostre o comprimento da hipotenusa.
"""
from math import pow, sqrt
co=float(input('Digite o tamanho do Cateto Oposto: '))
ca=float(input('Digite o tamanho do Cateto Adjacente: '))
hip=((co**2)+(ca... |
b621916820d294c82b52a853b5c181ca66a49b44 | nisheshthakuri/Python-Workshop | /JAN 19/Assignment/Tuple/Q4.py | 132 | 4.09375 | 4 | Q.Program to convert a list to a tuple
Solution:
lists = [1, 3, 5, 7, 9, 11]
print(lists)
tup = tuple(lists)
print(tup)
|
343c5be8b96038f6cb987d519d67e108069318ed | compilepeace/DS_AND_ALGORITHMS | /DS_with_python/dynamic_programming/05_min_number_of_squares_reccursion.py | 738 | 3.578125 | 4 | import sys
import math
def isPerfectSquare(n):
root = math.sqrt(n)
result = root - int(root)
if result == 0:
return True
else:
return False
def minNumberOfSquares(n, dp):
if n == 0:
return 0
# In case number is a perfect square
if isPerfectSquare(n):
return 1
result = IN... |
c0acb074f67b5f0c412d1fd3d0bb27b24651a0eb | rahulvennapusa/PythonLearning | /Basics/EvenOddCehck.py | 213 | 4.21875 | 4 | inp_str = (input("Enter an integer"))
if type(inp_str) == int and inp_str % 2 == 0:
print("Even number")
elif type(inp_str) == int and inp_str % 2 != 0:
print("Odd number")
else:
print("Not a number")
|
4a9786e609017219c6b097848b5d8af650987c53 | niphadkarneha/SummerCamp | /Python Scripts/Intro_to_Python.py | 1,880 | 4.28125 | 4 | # Intro to Python
# The PRINT statement
print("text")
print("Hello, world!")
print("")
print("Suppose two swallows \"carry\" it together.")
print('African or "European" swallows?')
# Mathematical operations
2+2
50 - 5*6
(50 - 5*6) / 4
8 / 5 # division always returns a floating point numbe... |
1a0b4f03018171f6df44ff767fa7313e27d86532 | arkolcz/rpi_weather | /rpi_weather.py | 2,533 | 3.515625 | 4 | import sys
from urllib.error import HTTPError
import urllib.request
import json
import requests
# Globals
IP_INFO_URL = 'http://ipinfo.io/json'
# Keys for dict containing ip based data
COUNTRY = 'country'
CITY = 'city'
HOST_IP = 'ip'
# OpenWeather API url
OW_API_URL = 'https://api.openweathermap.org/data/2.5/weather... |
d658fd72c7b3a4b47b2ebfad103adee4d2be3fd1 | Wizmann/ACM-ICPC | /Leetcode/Algorithm/python/2000/01171-Remove Zero Sum Consecutive Nodes from Linked List.py | 1,045 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeZeroSumSublists(self, head):
l = []
s = set([0])
pre = 0
while head:
pre += head.val
... |
7ac93a04e4420e9baee87f842ba846c2628dda61 | tum0xa/algo_and_structures_python | /Lesson_1/4.py | 2,661 | 4.46875 | 4 | """
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Прог... |
e802e8154b571e52d5a55c68cb99efa9e09f76b2 | Benjaminlii/pythonFirst | /9.面向对象高级.py | 2,639 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Benjamin
# date:2020.11.18 21:06
# 使用__slots__
# 在类内部定义__slots__属性为一个字符串元组可以限制类的属性
class Student(object):
__slots__ = ('name', 'age')
student = Student()
# student.score = 100
# 使用@property
# 在python中使用set_xxx()或者get_xxx()方法对属性进行操作灵活性不如直接对属性进行操作,但直接操作属性有... |
4e3ac3bec34fc5c0bb9c3b00dca4bd5916809497 | pvargos17/python_practice | /week_02/labs/03_variables_statements_expressions/Exercise_09.py | 466 | 4.5625 | 5 | '''
Receive the following arguments from the user:
- miles to drive
- MPG of the car
- Price per gallon of fuel
Display the cost of the trip in the console.
'''
print("""
-------------------------------------------------
TRIP COST CALCULATOR
------------------------------------------------... |
6b650a9aef5554aaf4306f9a7253c7e9ae67f4b7 | genggng/leetcode | /316-1.py | 1,098 | 3.515625 | 4 | """
6214. 判断两个事件是否存在冲突 显示英文描述
给你两个字符串数组 event1 和 event2 ,表示发生在同一天的两个闭区间时间段事件,其中:
event1 = [startTime1, endTime1] 且
event2 = [startTime2, endTime2]
事件的时间为有效的 24 小时制且按 HH:MM 格式给出。
当两个事件存在某个非空的交集时(即,某些时刻是两个事件都包含的),则认为出现 冲突 。
如果两个事件之间存在冲突,返回 true ;否则,返回 false 。
"""
from typing import List
class Solution:
def haveCo... |
be00f9ab62bd23184ede35811ebfd9ead23a2561 | TheLostLight/Simple-Scheduler | /src/filegenerator.py | 1,341 | 3.84375 | 4 | import random
from datetime import datetime
# Randomly generates an example file which can be used as
# input in fileread.py
#
# file_name - Name of resulting output file
# nclass - Number of individual class times to generate
# max_time - The maximum latest time a class can end at
def createExampleFile(file_name... |
1e58be0c73df6eb43fc620ea2e0a92a1eb9b1c0d | tw-alexander/CodeHS-Intro_To_Computer_Science-Answers-Python | /CodeHs/4.Functions And Exceptions/2.Namespaces in Functions/6.2.6 Adding to a Value.py | 95 | 3.859375 | 4 | num1 = 10
num2 = int(input())
def add_sum():
sum = num1+num2
print(sum)
add_sum()
|
9cf3781afbb5c09fd1db83b2b7435d8fe8654aef | YimoZhu/Numerical-Analysis | /prog3/codeQ1Q2Q3Q4.py | 6,612 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Author: Yimo Zhu
This is for Math 128A programming assignment #3
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
###############################################################################
def q1(a,b,x):
#Take the input vectors a&b to use R... |
7cbc25853699adff4c2aa5cf3aed10a948403e7d | gtsofa/homestudy | /find_fib.py | 324 | 4.0625 | 4 | # find_fib.py
# 1,1,2,3,5,8,13
# The fibonacci sequence is defined by:
# Fn = Fn-1 + Fn-2
# where F0 = 0 and F1 = 1
def fib(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
result = fib(num - 1) + fib(num -2)
return result
print(fib(3))
print(fib(4))
print(fib(... |
904a7d4ba0a5a818d416c5c55bd7cbea1e6044f3 | areshta/python-edu | /basic-training-examples/tuple/tuple-1.py | 900 | 4.4375 | 4 | #Python-3 tuple examples
print("\n*** Simple tuple ***\n")
seasons = ("winter", "spring", "summer", "autumn")
print("There are enough tuples in real life.\nSeasons, for example: ", seasons)
print("\n*** Create tuple from list ***\n")
a, b = 3, 4
c = tuple([a,b])
print(c)
print("\n*** Function can return tuple ***\n"... |
0e062c29009d03b26d3d22fd897aead0c786b656 | girishdhegde/aps-2020 | /argsorter.py | 297 | 3.75 | 4 | def argsort(lst):
idx = [i for i in range(len(lst))]
zp = list(zip(lst, idx))
zp.sort()
return list(zip(*zp))[1]
if __name__ == '__main__':
import random
n = int(input())
a = [random.randint(0, 10) for i in range(n)]
print(a)
print(argsort(a))
print(1232) |
c2abeb30d41c27a0e1167d3b371a78e16e0d9a18 | kylederkacz/Exercises | /phonenumbers.py | 814 | 4.15625 | 4 | PHONE_NUMBER_LENGTH = 10
def phone(number):
number = str(int(number))
if len(number) < PHONE_NUMBER_LENGTH:
raise Exception('Invalid phone number')
def calcstrings(number, digit, string):
if digit == PHONE_NUMBER_LENGTH:
print string
else:
for i in 1,2,3:
calcstrings(number, digit+1, string+get_char... |
fce8265ddac56dc04a11c63db76b0bb68fcad763 | shantelAT/Learningpython | /LearningPython/DataStructurestack.py | 494 | 4.1875 | 4 | #************** Learning Stacks
class Stack():
def __init__ (self, item):
self.itemlist = []
def push(self, item):
self.itemlist.append(item)
def get_stack(self):
return self.itemlist
def pop(self):
return self.itemlist.pop()
def is_list_empty(self):
ret... |
395c4bcae4ffd77dc5df3d71fbb008a552336d1e | AbeForty/Dojo-Assignments | /Python/Python Fundamentals/findCharacters.py | 270 | 3.828125 | 4 | word_list = ['hello', 'world', 'my', 'name', 'is', 'Anna']
new_list = []
def findCharacter(char, lst):
for i in range(0, len(lst)):
if word_list[i].find(char) > 0:
new_list.append(word_list[i])
print new_list
findCharacter("o", word_list)
|
fabff8fcda7d846be80709a673ae65c57891a281 | hariesramdhani/pyScripts | /markovize.py | 2,895 | 4.21875 | 4 | #!/usr/bin/python3
"""
Markovize is a program that will let you randomize sentences
from a txt file based on the probability of appearance of
letter that came after the order using Markov's chain rule.
------------------------------------------------------------
PROGRESS : ████████████████████████████████████████████... |
8aa5b599f84ee8813645fbd83453dcdc7ea1e5a4 | bobogit/python | /103枚举.py | 456 | 3.765625 | 4 | from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Sun
print(day1.value)
@unique
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
# ... |
4a86f36509a99bdc1a2812a973d958fe1d0f40f6 | EvanMu96/Cipherinpython | /Reverse_Cipher/Reverse.py | 2,735 | 3.828125 | 4 | # Reverse cipher
import sys,pyperclip
__author__ = "Evan Mu"
def main():
my_message = """Alan Mathison Turing was a British mathematician, logician
, cryptanalyst, and computer scientist. He was highly influential in the d
evelopment of computer science, providing a formalisation of the concepts of
... |
835d00d1805e089392c8e59959da16241ddbe40c | satrini/python-study | /exercises/exercise-52.py | 250 | 3.875 | 4 | while True:
genrer = str(input("Your genrer: ")).strip().lower()
if genrer == "m" or genrer == "f":
print("Registered with success!")
print(f"Genrer: {genrer}")
break
print("invalid input!")
print("End program..")
|
0326e9dc97c5f8059e1c33efc3c0cc462c0e3b4e | J-AugustoManzano/livro_Python | /ExerciciosAprendizagem/Cap08/c08ex16.py | 166 | 3.796875 | 4 | valores = [1, 2, 3, 4, 5]
soma = 0
for i in valores:
soma += i
print("Somatório = ", soma)
enter = input("\nPressione <Enter> para encerrar... ")
|
1aa58908df9f7d89d18fafc9d12942e6894313d6 | CelvinBraun/snake | /snake.py | 2,559 | 3.84375 | 4 | from turtle import Turtle, Screen
import time
#game settings
window_title = "snake"
background_color = "black"
screen_width = 600
screen_height = 600
move_speed = 0.3
#snake settings
color_of_snake = "green"
shape_of_snake = "square"
size_of_snake = 1
move_distance = 20
#directions
up = 90
left = 180
down = 270
righ... |
af9e8245c8c534b6eee3411d7ad469a8107c5e30 | ayushggarg/classy_crypto_vB | /Transposition.py | 1,002 | 3.625 | 4 | import math
def TranspositionDy(message, key):
#myMessage = 'Cenoonommstmme oo snnio. s s c'
#myKey = 8
key = int(key)
plaintext = decryptMessage(key, message)
return(plaintext + '|')
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message) / key)
numOfRows = key
numOfShadedBoxes = (numOfColumn... |
98ce7f9e704b8b2c2c1fd06fab846cadc355b2d0 | datasnakes/archives | /Pandas/CleanCSV.py | 1,345 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""This script is designed to remove duplicates from a .csv file and
not which duplicates were removed in a .txt file.
"""
# List of modules used.
import pandas as pd
# Use pandas to read in the dataframe and create lists.
# Read in main file
maf = pd.read_csv('GPCR_Master_Accession_File.csv', ... |
93691678125915703b19ce2333207405d2f5be7a | Jadams29/Coding_Problems | /Looping/Loop_Print_Odds.py | 359 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 11:48:07 2018
@author: joshu
"""
# Use for loop to iterate through list from 1 - 21
# Use modulus to check if odd or even
# Print out the odd numbers
for i in range(1, 22):
if ((i % 2) != 0):
print("i = ", i)
newlist = [i for i in rang... |
4e3dda89d177ce3750ba96bb3817342a1f7e2c32 | papalos/geekbrains_hw | /lesson_five/lsn5_task1.py | 894 | 3.625 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
# Если есть окончание ввода, значит присутствует цикл записи
# построчный ввод видимо означает, что введенные данные в файле тоже должны отображаться постр... |
de73c99391114cb0d27a7e787219bd2d9649ad7b | Natt7/python-learning | /geekbangpython/if.py | 398 | 3.703125 | 4 | x = 'xyz'
if x == 'abc' :
print(x)
elif x =='xyz' :
print('x = xyz')
else:
print('x no equal')
chinese_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊'
print(chinese_zodiac[-1])
print(chinese_zodiac[0:4])
year = int(input('请输入您的出生年份:'))
print(year % 12)
print(chinese_zodiac[year % 12])
if (chinese_zodiac[year % 12]) == '狗' :
... |
3de9b9a70e27b8e7eefafa34367be0878b6de3f7 | qetennyson/maththeme_ct18 | /ch3_data_stats/fart.py | 1,047 | 3.84375 | 4 | from collections import Counter
import csv
def read_csv(filename):
farters = []
non_farters = []
maybe_farters = []
with open(filename) as my_file:
reader = csv.reader(my_file)
next(reader)
for row in reader:
if row[2].lower() == 'yes':
farters.appen... |
a792f43bd5547a57f9f68b4f96828ec125652333 | aswinzz/Simulation-Lab-Assignments | /Lab5/randomGen.py | 1,841 | 3.5625 | 4 | import time
# X(i+1) = (a*X(i) + c) % m
# Mixed Congruence Method
class Mixed:
def __init__(self):
self.a = 48271
self.m = 2147483647
self.c = 1
def generate(self,n):
# seed will be a unique number in each iteration by using current time in micro seconds
seed = (time.t... |
677bd239bef14e5a02487e2f4feacd21cd7a3b11 | Shengjie-Sun/LeetCode | /Algorithms/226-Easy-Invert Binary Tree-[Tree].py | 990 | 4.03125 | 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 invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
else:
# root.left, roo... |
f3780142bcf1aa6590cbedaf476f6493e547d7d8 | makarov-wl24/python-getting | /lesson5-task3.py | 1,538 | 3.671875 | 4 | # Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов.
# Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников.
# Выполнить подсчет средней величины дохода сотрудников.
with open('lesson5-task3.txt', 'r+', encoding='utf-8') as file:
... |
a65e9891373333a8a6ce1fa9f6c89738a209a06b | Nicole-Bidigaray/Bootcamp-pirple.com | /Python_is_Easy/Importing/Guessing_Game_PartB.py | 626 | 3.65625 | 4 | from random import random
from time import perf_counter
randVal = random()
# print(randVal)
# time.clock() -> timevalue
# time.clock() -> timevalue2
upper = 1.0
lower = 0.0
# guess = 0.5 -> Too Low _> lower 0.5
# guess = 0.9 -> Too High -> uper 0.9
# guess = 0.5
startTime = perf_counter()
while(True):
guess = ... |
32f06af480f67cdbf9441acb54d494920c6c3f27 | ExploreNcrack/Comput496 | /assignment1/simple_board.py | 3,078 | 4.0625 | 4 | """
simple_board.py
Implements a basic Go board with functions to:
- initialize to a given board size
- check if a move is legal
- play a move
The board uses a 1-dimensional representation with padding
"""
from sys import stdout
import numpy as np
from board_util import GoBoardUtil, BLACK, WHITE, EMPTY, BORDER, \
... |
725e47721e379e8a38314baca93a98d58c88df2d | malk321/master-python | /nihongo o benkyoshimashô/kanjis.py | 6,403 | 3.625 | 4 | # -*- coding : utf-8 -*-
from PIL import Image
from random import randrange
from math import ceil
import sys
import psutil
# We ask the player what mode he wants to play
mode = 0
romajis_file = open("romajis.txt",'r')
menu_flag = 1
while (menu_flag == 1) :
while (mode != 1 and mode != 2 and mode != 3 and mode ... |
5c24d9a8eb608de6f56bee8411cd61ca20337ea8 | rdoyama/coding | /minefield/play.py | 2,937 | 3.9375 | 4 | # import pygame
# import sys
# # initializing the constructor
# pygame.init()
# # screen resolution
# res = (720,720)
# # opens up a window
# screen = pygame.display.set_mode(res)
# # white color
# color = (255,255,255)
# # light shade of the button
# color_light = (170,170,170)
# # dark shade of t... |
638109ba0649efa4a09a249fb751a93c4006c99f | alexandraback/datacollection | /solutions_2449486_0/Python/OverlordAlex/lawnmowing.py | 855 | 3.5625 | 4 | import numpy as np
cases = int(raw_input())
for case in range(cases):
r, c = map(int, raw_input().strip().split())
board = []
done = False
if (r==1) or (c==1):
print "Case #"+str(case+1)+": YES"
done = True
for i in range(r):
row = map(int, raw_input().strip().split())
board.append(row)
if (done): c... |
b3ec832ae421fcdb13b36eea7f47f325cdca5323 | klassen-software-solutions/pyutil | /kss/util/strings.py | 488 | 4.0625 | 4 | """Misc. string related utilities."""
def remove_prefix(text: str, prefix: str) -> str:
"""Removes the prefix from the string if it exists, and returns the result."""
if text.startswith(prefix):
return text[len(prefix):]
return text
def remove_suffix(text: str, suffix: str) -> str:
"""Remove... |
47299882939de8ed348daa90c857fc8424aa7624 | Aditya7861/Self | /guess_game.py | 605 | 3.984375 | 4 | import random
original_num = random.randint(2,89)
print(original_num)
def guess_checker(count):
user_guess = int(input("Enter your guess no:-"))
if(user_guess < original_num):
print("Your guess Number is low")
count = count +1
guess_checker(count)
elif(user_guess > original_num):
... |
e228d61643136143614b333cdfbca9705020e082 | PeriGK/DeepLearningND | /NeuralNetworksIntro/KerasIntro/keras_imdb.py | 3,659 | 3.6875 | 4 |
# coding: utf-8
# # Analyzing IMDB Data in Keras
# Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
# get_ipython().run_line_ma... |
f969889b844219a7a351c7f595ada2d5cd1841cb | mapozhidaeva/other | /Test_yourself_before_exam/Guess_TERM.py | 1,250 | 3.765625 | 4 | import random
def file_reading(filename):
with open(filename, 'r') as f:
return f.read().split('\n')
terminology = file_reading('Terminology.tsv')
definitions = file_reading('Definitions.tsv')
the_dictionary = dict(zip(terminology, definitions))
print ('Let\'s start the test! (press Enter to end the ga... |
434b60b1dee69da6a2cabe16a577576652745ae1 | zhangler1/leetcodepractice | /哈希表/hash/Group Anagrams49.py | 684 | 3.828125 | 4 | from typing import List,Dict,Tuple
from collections import defaultdict
#python的 list不可hash 必须
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
charCounter=[0]*26
groupdict:Dict[Tuple,List]=defaultdict(list)
for word in strs:
for char i... |
69d31a0468da80740486fa058f67b4814a97b06b | mbadayil/Ilm | /Insertion_Point.py | 209 | 3.71875 | 4 | def InsPoint(nums, target):
if target in nums:
return nums.index(target)
j=len(nums)-1
for i in range(0,j):
if nums[i]>=target:
return i
print(InsPoint([1,2,5,6],0))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.