blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
a07499c6f379640db1ca5e741338fb3b8f97a897
Goose92/LabyrintheMulti
/carte.py
3,618
3.6875
4
# -*-coding:Utf-8 -* # Ce module contient la classe Carte # Une carte est composée d'un nom et d'un tableau (matrice représentant la carte) # La classe contient également plusieurs méthodes pour agir sur l'objet Carte import os from gestion import saisieLigneOK,formatLigneOK,choixValide,nbCoupsJoue,sensJoue,supprimer...
9927d3ceb58d4faf112ffbd94ee73766c023867a
willgood1986/myweb
/pydir/slice.py
665
4.25
4
# -*- coding: utf-8 -*- print('nums=list(range(200)):') nums = list(range(20)) print(nums) print("nums[0:2]") print(nums[0:2]) print("nums[1:2]") print(nums[1:2]) print("nums[-3:0] length") print(len(nums[-3:0])) print("nums[-3:-1] length") print(len(nums[-3:-1])) print("When the start index is less than 0, the end ind...
0b16a72382da23022ae7e0c2186536a85d507b22
abueesp/mathstuffinc
/MersennePrimes.py
618
4.03125
4
## Mersenne Primes Code ## ## Series: Arithmetic Primes ## ## Author: Abueesp ## ## Date: Tue, May 23 2015 ## ## License: CC NC-BY-SA ## scriptname = 'Mersenne Prime Code' prompt = '> ' print "Hello, I'm the %s, a pretty dumb code for easy testing of Mersenne primes (2^n-1). Take into account that if n is prime then ...
629584917ee390caaaae6e81b4cd75dfa2fc9e87
joepbasile/CS115
/memoization.py
4,559
3.5
4
''' Created on Sep 10, 2018 @author: joepb ''' import time def fib(n): if n <=1: return n return fib(n-1)+ fib(n-2) #start_time = time.time() #print(fib(40)) #print('computation time without memoization: %.2f' % (time.time() - start_time)) def fib_memo(n): def fib_helper(n, memo...
ee856c98add6edf6e534671539cf58afe80c3775
eronekogin/leetcode
/2022/balance_a_binary_search_tree.py
812
3.625
4
""" https://leetcode.com/problems/balance-a-binary-search-tree/ """ from test_helper import TreeNode class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: def get_node_values(root: TreeNode) -> None: if not root: return get_node_values(root.left) ...
c4ede376ccdf54cefa86f28edb43d48645f7865f
jvenkat/Python_DS
/Queue.py
629
3.6875
4
class Queue: def __init__(self): self.queue=[] def isEmpty(self): return self.queue==[] def enque(self,data): self.queue.append(data) def deque(self): data=self.queue[0] del self.queue[0] return data def peek(self): if len...
d1c4ecc991e9ae6fe8570dcf4977c279228355f3
EDG-UPF-ADS/Python-1
/2 - 11.03.20/salario_bruto_liquido.py
311
3.546875
4
qtd_h=int(input('Quantidade de Horas:')) vlr_h=int(input('Valor das Horas:')) slr_bruto=qtd_h*vlr_h imposto=(slr_bruto*0.27) slr_liquido=slr_bruto-imposto print('\nO Salário Bruto é de R$ %.0f'%slr_bruto) print('O Salário Líquido é de R$ %.0f'%slr_liquido) print('O Valor do Imposto é de R$ %.0f'%imposto)
742cf55ff704861c2a62bdee299cb48d5dfc1058
zhangni57951/hello_word
/renming.py
631
3.515625
4
# encoding:utf-8 import re def find_item(hero): with open("name.txt") as f: data = f.read().replace("|","") name_num = re.findall(hero,data) # print("主角 %s 出现 %s 次"%(hero,len(name_num))) return len(name_num) name_dict = {} with open("name.txt",encoding='cp936') as f: for line in f: ...
6c35d0d511155827598fe0df1bb9c700dfe495aa
rustinshamloo/NFL-Big-Data-Bowl
/player_id_function.py
1,773
3.84375
4
# edit in here, run in terminal, save/push to git on terminal: #1. git add . #2. git commit -m "message" #3. git push # create function that returns player characteristics (height,weight,etc.) with playerid as input # the data is in players.csv # use score function as ex, find all chrs. and turn them into a list # mi...
0829bdcdb89615ba45150680f2715635596ab84e
srmchem/python-samples
/Python-code-snippets-201-300/246-unit-converter.py
3,255
3.5
4
"""246-Unit Converter GUI Download all snippets so far: https://wp.me/Pa5TU8-1yg Blog: stevepython.wordpress.com requirements: None. origin: https://codereview.stackexchange.com/questions/239821/simple-gui-unit-converter-with-tkinter Code has been Shamblized a bit to make it slightly more PEP8. """ f...
a7c3853f2d470344298324bbdf9b1554e454354b
nkirkpatrick/google-python-os
/week7/scripts/dict_examples.py
142
3.515625
4
d = {"key1": 10, "key2": 23} if "key1" in d: print("this will execute") if "nonexistent key" in d: print("this will not")
e05a7739bd50f3c106c23de79aa1d108320c4c19
Lewic1201/pythonDemo
/source/application/loansPrac/person.py
1,094
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/10/5 17:02 # @Author : Administrator # @File : person.py # @Software: PyCharm # @context : from card import Card class Person: def __init__(self, name, userId, phone, card): self.name = name self.userId = userId self.phon...
b09d57dba36c8c046434b1e2e5797681999a6eb4
mohsinbasheer-gif/helloworld
/numbercheck.py
263
3.921875
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 20:49:08 2019 @author: HP """ print("enter number") num=int(input()) if (num>0): print("number is positive") if (num<0): print("number is negative") if (num==0): print("number is zero")
82678b1fb0656ce09d9d293f2a421452a81079ca
Indrajit67/pythonlearn
/TestOOP.py
820
3.859375
4
#Python Tokens - Keywords, identifiers, literals, operators #Keywords are special reserved words # e=512000 # b=((e*1.5)/8) # print (b) #arthimetic operators +,-,/,* #relational operators <,>,==,!= #logical Operation &, | # # a=10 # b= 20 # c= True # d = False # print (a<b) # # print(c|d) #Data Type ---- Inte...
ffb14cb7e6e80bcccfd7f07da78b032114267e54
ArturAssisComp/ITA
/ces22(POO)/Lista1/Question_2.py
674
4.25
4
''' Author: Artur Assis Alves Date : 07/04/2020 Title : Question 2 ''' import turtle #Functions: def draw_poly(t, n, sz): ''' Draws a regular polygon with 'n' sides. Each side has length 'sz'. Input : t -> turtle.Turtle() n -> integer sz -> float Output: ...
8f2eadce636423f7ba1b038c5d0a15683e7ba888
CCC53/Python
/Curso Python 2.0/STRING.py
963
4.3125
4
name, age= ('Fransisco', 18) #Concadenar un string y un int print("Mi nombre es " +name +" y tengo " +str(age)) #Otra manera de juntar variables para hacer un cadena es por posicion print("Mi nombre es {name} y tengo {age}".format(name=name, age=age)) #Otra manera es por el metodo F-string (de Python 3.6 en ad...
f842c74c945acd59dba0f30973a5dea3a106b14b
mahtabfarrokh/SearchEngine
/Trie.py
6,940
3.5625
4
from tkinter import END class Node : def __init__(self , dWord , flag ): self.data = dWord self.Rc = None self.Lc = None self.next = None self.flag = flag self.address = [] class MyTrie : def __init__(self ,fileOpen ): self.root = Node("" ,0 ) se...
fc95ad8425cd9f2110736420fec5dcba43a21813
mohitpatil30501/python
/Fabonacci Series.py
302
3.921875
4
#Made by Mohit Patil. #08/08/2020 #Fabonacci Series f = 0 s = 1 n=int(input("Enter the Limit of terms:")) print("First "+str(n)+" terms of Fibonacci series are:\n") for i in range(0,n): if (i <= 1): nex = i else: nex = f + s f = s s = nex print(str(nex))
24a90a54be5004badfc226349cd9a245c5221f74
nwaiting/wolf-ai
/wolf_ml/practice_pandas/pandas_drop.py
749
3.890625
4
#coding=utf-8 """ drop删除行、删除列 print frame.drop(['a']) print frame.drop(['Ohio'], axis = 1) """ import numpy as np import pandas as pd def main(): df = pd.DataFrame({'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings','kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders']...
110259fe449a9bfff934a4e41b68054d01c312fb
wulinlw/leetcode_cn
/中级算法/backtracking_5.py
2,190
3.890625
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/49/backtracking/95/ # 单词搜索 # 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 # 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 # 示例: # board = # [ # ['A','B','C','E'], # ['S','F','C','S'], # ['...
464b534a471814f70cfee5b9edecf5638c57956e
Momin-C/Python-Course
/Object Oriented Programming Basics/Misc/InnerClass.py
295
3.796875
4
class Car: def __init__(self,make,year): self.make = make self.year = year class Engine: def __init__(self,number): self.number = number def start(self): print ("Engine Started") c = Car("Tesla",2017) e = c.Engine(2003) e.start()
1a3689681b252e87b0c323aa73b32166bb3e8469
oktaran/LPTHW
/exercises.py
1,367
4.21875
4
""" Some func problems ~~~~~~~~~~~~~~~~~~ Provide your solutions and run this module. """ import math def add(a, b): """Returns sum of two numbers.""" return a + b def cube(n): """Returns cube (n^3) of the given number.""" # return n * n * n # return n**3 return math.pow(n, 3) def is_od...
1c767feaf2b0f6a4f5c4f215c3e8c8b07b8e39ee
sservett/python
/PDEV/EXAMPLES/ex001.py
1,391
3.8125
4
""" Servet INCE -- delete this line a = int(input()) b = int(input()) if not (a >= 1 and a <= (10 ** 10)): print("a is Invalid number") if not (b >= 1 and b <= (10 ** 10)): print("b is Invalid number") total = a + b diff = a - b multiply = a * b print(total) print(diff) print(multiply) ===============...
de84100843c2d2615b5043193661dc46fd710641
Joe-Demp/leetcode
/python/is_power_of_2.py
763
3.65625
4
class Solution: def isPowerOfTwo(self, n: int) -> bool: count_of_ones = 0 while n > 0 and count_of_ones < 2: count_of_ones += n % 2 n = n // 2 return count_of_ones == 1 # taken from Leetcode class FasterSolution: def isPowerOfTwo(self, n: int) -> bool: re...
e9e6b03982be4b6e00693a3c068cb3bec252dafd
LIM-EUNBI/Python
/day20210710.py
306
3.71875
4
# from abc import ABC, abstractmethod # class Animal(ABC): # @abstractmethod # def bark(self): # pass # class dog(Animal): # pass # class cat(Animal): # pass class Parent: def __init__(self): self.value = 0 class Child(Parent): def __init__(self): pass
e94d6a64d7085cb4d3e2affacc4e4d6ef1a86a06
Vinayak030/python
/1.2.3.alist.py
179
3.765625
4
l=['akhil','athira','abhi','aneesha','arun'] count=0 for name in l: for i in name: if i=='a': count=count+1 print("The Name list is ",l) print("The Count of a is ",count)
7533668f24b8a37c3fff7789367d092968a72843
objoyful/our-code
/JetsonAI/faceRecognizer/faceRecognize-9-classes.py
823
3.875
4
class Rectangle: def __init__(self, color, w, l): self.width = w self.length = l self.color = color def area(self): self.area = self.width * self.length return self.area def per(self): self.perimeter = 2 * self.length + 2 * self.width ...
9258b0df1725707a7e95058277b1480acef235ce
suhailars/Python-practice
/chap2/phoneno.py
371
3.546875
4
import re def regular(): k=0 i="" while(k<10): if k != 9: i+='\d' else: i+='\d' k+=1 print 'regular exp is:',i return i def phone(): print 'entr a phone no' s=raw_input() match=re.search(regular(),s) if match: print 'good phone no tc!...
ed754956c3953496d9b6b7409ac76ca9493f30bd
mouday/SomeCodeForPython
/test_from_myself/Python17个常用内置模块总结/11.datetime模块.py
623
3.546875
4
import datetime print(dir(datetime)) print(dir(datetime.datetime)) print(datetime.time()) print(datetime.date(year=2015,month=12,day=11)) print(datetime.datetime.now()) print(datetime.datetime.now()-datetime.timedelta(days=5)) ''' datetime.date:表示日期的类。常用的属性有year, month, day datetime.time:表示时间的类。常用的属性有hour, minute, se...
714c25586b994af6938070793012080479f0ed4d
willstem/Project-Euler
/P004.py
527
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 25 12:22:15 2018 @author: will """ def is_palindrome(list): return list == list[::-1] largest_num = 0 for num1 in xrange(100,999): for num2 in xrange(100,999): check = str(num1*num2) if is_palindrome(check): if int(chec...
dcd2d16d208c608cabc9119c6980ef64471fae58
wizardlancet/ICS-Fall-2014
/ICS-Lab1/gaddis-chap3-q2-rectangles.py
440
4.0625
4
len1 = int(input("Enter length of rectangle 1 - ")) wid1 = int(input("Enter width of rectangle 1 - ")) len2 = int(input("Enter length of rectangle 2 - ")) wid2 = int(input("Enter length of rectangle 2 - ")) if ( len1 * wid1 ) > ( len2 * wid2 ): print("Rectangle 1 has the greater area!") elif ( len1 * wid1 )...
b90158695f567f676d867d2bfbd4163ff73e825a
rodrigocruz13/holbertonschool-machine_learning
/pipeline/0x01-apis/0-passengers.py
1,266
3.734375
4
#!/usr/bin/env python3 """script for getting info from web pages """ import requests def to_int(a_str): """[Converts strings into numbers] Args: a_string ([str]): [a string number] """ if not isinstance(a_str, str) or (a_str == 'n/a') or (a_str == 'unknown'): return 0 ...
a925bd5d7961195e17ff2624e1e26e7d888f2595
ritzdevp/cheatsheetsML
/data_preprocessing_template.py
1,991
3.84375
4
# Data Preprocessing Template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values """All rows. All columns except last one,as its the outcome""" y = dataset.iloc[:, 3].values """...
2e0b8086af59f942d5db5bc0e511d759dc7a7692
zhangluming1120/myself-1
/e1/np_summary.py
957
3.828125
4
import numpy as np def main(): data = np.load('monthdata.npz') totals = data['totals'] counts = data['counts'] result1 = totals.sum(axis=1) # print(totals) print("{} row has the lowest value".format(np.argmin(result1))) precipitation = totals.sum(axis=0) observations = counts.sum(axi...
43662989ede65e64cd7635743da129dc4178c585
hkm11495/CS261.HW1
/a1_p4_swap_pairs.py
717
4.21875
4
# Course: CS261 - Data Structures # Student Name: Holly Murray # Assignment: 1 Problem 4 # Description: This receives a 1D list of integers and returns a new list the same length where pairs of # elements are swapped. The original list is not changed. def swap_pairs(arr: []) -> []: # """ ODO: Write this implem...
d8c792cc1ad105d6ff478aca8f31c7d5e448f5db
elenasacristan/file-io-vscode
/book.py
222
3.515625
4
import re import collections # https://www.w3schools.com/python/python_regex.asp text = open('book.txt', encoding='utf-8').read().lower() words = re.findall("\w+", text) print(collections.Counter(words).most_common(20))
a6a7a215b41bee85fd99ccc135a8cb920dfe96a2
dionwang88/lc1
/algo/334_Increasing_Triplet_Subsequence/Q334.py
494
3.578125
4
class Solution: def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) < 3: return False import sys small = big = sys.maxint for n in nums: if n <= small: small = n ...
78fde46678be86f4968ab37d28b664901f5c61d0
shelvi31/Python
/Code with HarryPython/Dictionary and Functions.py
503
3.84375
4
d1=[] #d1 is a list d2={} #d2 is a list d3=() #d3 is a tuple print(type(d1)) print(type(d2)) print(type(d3)) d2={"shelvi":"pizza","sakshi":"pasta","cp":"daliya",5:7,"shubham":{"Breakfast":"pizza","L":"Roti","Dinner":"AALU"}} print(d2) print(d2["shelvi"]) print(d2[5]) print(d2["shubham"]["Dinner"]) d2["ankit"]=["khana"]...
ef1059b91dc06fb6cd5a400f0b487783ad967050
daniel-reich/ubiquitous-fiesta
/JmyD5D4KnhzmMPEKz_0.py
397
3.71875
4
def constraint(txt): if all(i in txt.lower() for i in 'abcdefghijklmnopqrstuvwxyz'): return 'Pangram' elif all(txt.lower().count(ch)==1 for ch in txt.lower() if ch != ' '): return 'Heterogram' elif len(set(i[0] for i in txt.lower().split())) == 1: return 'Tautogram' elif set.intersection(*map(set, ...
396c9e808785d7861b4fc9a29f350010d62a3833
rafaelperazzo/programacao-web
/moodledata/vpl_data/40/usersdata/120/19833/submittedfiles/main.py
180
3.515625
4
# -*- coding: utf-8 -*- from __future__ import division import funcoes #COMECE AQUI m=input('Digite m:') e=input('Digite e:') print(calcula_pi(m)) print(calcula_razao_aurea(m,e))
9de2ef5f3264e824bf24978d038140c087ab772d
natsumemaya/hexlet_tasks
/8_oop/dictionary_with_aliases/solution.py
6,761
3.625
4
# Как вы уже знаете, в Python многое работает на основе протоколов. Обращение по индексу или ключу — через те самые квадратные скобки — тоже работает с любыми объектами, реализующими "subscription protocol". # Этот протокол требует, чтобы у объекта имелись нужного вида методы __getitem__ и __setitem__, первый из котор...
1fadf2e0267eaa079536c0f93d8b8ec00e62ecd9
asabnis7/python-basics
/ex48/lexicon.py
1,365
3.703125
4
def convert_num(s): try: return int(s) except ValueError: return None def scan(raw): lexicon = [('direction','north'), ('direction','south'), ('direction','east'), ('direction','west'), ('direction','down'), ('direction','up'), ('direction','left'), ('direction'...
6848622a5163b03a5c035f0a05e2d8161bc0f293
messaismael/Test_python
/essai.py
446
3.75
4
print("Ce script recherche le plus grand de trois nombres") print("Veuillez entrer trois nombres séparés par des virgules : ") ch =input() nn = list(eval(ch)) max, index = nn[0], 'premier' if nn[1] > max: # ne pas omettre le double point ! max = nn[1] index = 'second' if nn[2] > max: max = nn[2] ...
86dd30ed2c595f98092154e14c08444f274d733a
rishi772001/Competetive-programming
/problem solving/matrix.py
253
3.765625
4
def py(): a=int(input("enter no.of.rows")) b=int(input("enter no.of.colums")) c=[[input("enter the elements")for j in range(a)]for i in range(b)] for i in range(a): for j in range(b): print (c[i][j])
398638a448164853dc4accb655f19ecf88e629e9
RyanMatlock/randchoice
/randchoice
3,461
3.734375
4
#!/usr/bin/env python3 """randchoice Pick an option from list passed in through stdin and/or arguments passed to the script. """ import sys import logging import random import termcolor import argparse logging.basicConfig(level=logging.WARNING) EXIT_SUCCESS, EXIT_FAILURE = 0, 1 def int_gt_zero(string): """Ens...
65299e5350714ee37e21288a230cacac005db813
ninja-22/HOPTWP
/CH2/listcomp.py
276
4.03125
4
#!/usr/local/bin/python def square(num): return num ** 2 my_list = [1, 2, 3, 4] sq_list = [] for num in my_list: sq_list.append(square(num)) print(sq_list) ## same code as above, can be achieved in less as below: sq_list = [ x**2 for x in my_list] print(sq_list)
f50ee33ccd3c77a327e3089a29568e2328a66235
IshfaqKhawaja/leetcode
/Linked List/removeKthElementFromLast.py
929
3.96875
4
class Node(): def __init__(self, data, next=None): self.data = data self.next = next class LL(): def __init__(self): self.root = Node(-1) def insert(self, data): current = self.root while current.next != None: current = current.next end = Node(d...
1917b7f85d00be4698a29ca3773fd4c2e02e2356
kbcmdba/pcc
/ch5/ex5-8.py
812
4.3125
4
# Hello Admin: Make a list o five or more usernames, including the name #'admin'. Imagine you are writing code that will print a greeting to each # user after they log in to a website. Loop through the list, and print a # greeting to each user: usernames = ['admin', 'kbenton', 'gpatel', 'sdhingr', 'amaser'] def print_...
51ff7be52e9284841b5b843dc43438e14fa135a2
AksharaPande/demo
/mca4/varun aswal 1901024/q2.py
66
3.625
4
thislist = [1,2,3,4,5] thislist.reverse() print(thislist)
f1bd7d2fec3bad6c574519628e524f16840a438a
yli1517/regression_analysis
/module_3_project/visualizations.py
8,324
3.71875
4
""" This module is for your final visualization code. One visualization per hypothesis question is required. A framework for each type of visualization is provided. """ import matplotlib.pyplot as plt import seaborn as sns # Set specific parameters for the visualizations LARGE = 22 MED = 16 SMALL = 12 PARAMS = {'axes...
fe5182d76bf9824e14d9f5f85014aecfd9fd6791
celsopa/theHuxley
/HUX - 1310.py
270
3.515625
4
a = int(input()) b = int(input()) c = int(input()) n = int(input()) pA = int(a/(a+b+c+n)*100) pB = int(b/(a+b+c+n)*100) pC = int(c/(a+b+c+n)*100) pN = int(n/(a+b+c+n)*100) print("""Candidato A: {}% Candidato B: {}% Candidato C: {}% Nulos: {}%""".format(pA, pB, pC, pN))
a48a23dd17023120c73079bdf3ce7bc51da48391
S-shubham/NLTK
/fetching_text_from_web.py
827
3.6875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import nltk,re,pprint # In[2]: from nltk import word_tokenize # In[3]: from urllib import request # In[6]: url="http://www.gutenberg.org/files/2554/2554-0.txt" # In[7]: response=request.urlopen(url) # In[9]: raw=response.read().decode('utf8') # In[...
041f36be4867cd3c0407b3a042d49d20e330790c
githubdacer/python_learning
/practice/is_next_to_number.py
732
4.09375
4
""" Just a routine practice: The idea is to return True if 3 is next to the other. """ def is_next1(nums): for i in range(len(nums)): try: if nums[i] == 3 and nums[i+1] == 3: return True except IndexError: return False def is_next2(nums): for x in ...
3494950e79cd2475a395b5c628f08b1b884fda76
lychees/ACM-Training
/Workspace/Python/main.py
315
3.5625
4
def count_strings(m, patterns, n): dp = [0] * (n + 1) dp[0] = 1 for i in range(1, n + 1): for pattern in patterns: if i - len(pattern) >= 0: dp[i] += dp[i - len(pattern)] return dp[n] m = 3 patterns = ["a", "b", "ab"] n = 4 print(count_strings(m, patterns, n))
a0d7f7664660995aaeb9aaedb751d1f2245b67d8
sudh29/Algorithms
/heapSort.py
557
3.96875
4
# heap sort def heapify(a, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and a[i] < a[left]: largest = left if right < n and a[largest] < a[right]: largest = right if largest != i: a[i], a[largest] = a[largest], a[i] heapify(a, n, largest) ...
8b8f1067ca09cdcafa28baa4f271826b57911904
ajaykommaraju/Courseera_Python_Project
/sum_of_squars_of_a_number.py
261
4.09375
4
#this program prints the sum of squares of a number from 0 to x , we are using range function . def square(n): return n*n def sum_squares(x): sum = 0 for n in range(x): sum += square(n) return sum print(sum_squares(10)) # Should be 285
e130e4a572f08675c8ed6c87835e8ec8786be7c7
pashas66/IS211_Assignment10
/Test_music_script.py
3,114
4.09375
4
import sqlite3 import pprint def insert_data(): """ The function responsible for housing the table creating script. Parameters: None Returns: SQL string script. """ sql_insert = """ INSERT INTO artists (artist_id, artist_name) VALUES (1, "Frank Sinatra"), (2, "The Beatles...
a5ee88069d212500afc36fe9178291c0129eb252
kogotto/experiments
/py/016_if/main.py
230
4
4
#!/usr/bin/python s = 'some str' if s == 'some str' or s == 'another str': print('match') else: print('miss') if s in [ 'some str', 'another str', ]: print('match2') else: print('miss2')
2ee8cdd7a81b75fd45caabb46320727bb65001cf
pranshu798/Numpy
/Python Numpy/Basic Operations/Unary operators.py
556
4.0625
4
# Python program to demonstrate # unary operators in numpy import numpy as np arr = np.array([[1, 5, 6], [4, 7, 2], [3, 1, 9]]) # maximum element of array print("Largest element is:", arr.max()) print("Row-wise maximum elements:", arr.max(axis=1)) # minimum element of array prin...
f228836c87d8594d056ae65301a809bc7fe1f3b3
jedzej/tietopythontraining-basic
/students/BRACH_Jakub/lesson_01_basics/L01P02_Triangles.py
252
3.96875
4
#!/usr/bin/env python3 #print("Enter the base length") base = float(input()) #print("Enter the height") height = float(input()) if height > 0 and base > 0: area = 0.5 * base * height print("{0:.2f}".format(area)) else: print("Invalid data!")
d2d04abb506d0848ef8a9fde43688be587380398
minjeongPark41/CodeUp100
/workspace/93.py
360
3.546875
4
n = int(input()) a = input().split() #a[0]=?, a[1]=?,....a[n-1]=? for i in range(n): a[i] = int(a[i]) # for i in range(n): # print(a[i], end=' ') # 이거를 거꾸로 어떻게 출력할 수 있을까 # for i in range(n): # a[n-i-1] = a[i] # a[0] = 1 a[n-1] = 2 # a[1] = 3 a[n-2] = 4 for i in range(n): print(a[n-i-1], ...
fbff0328c8f431837ee7b661d38993cb61c8a81c
Jari-Achterberg/SVV-Project_
/Integration_scheme_verification.py
4,186
3.53125
4
# Making the integration_scheme from Coordinates import d, Nx, Nz, x_list, la from matplotlib import pyplot as plt import pickle def integral(x1, x2, y1, y2): # Calculating parameters for linear equation y = ax + b a = (y2-y1)/(x2-x1) b = y1-((y2-y1)/(x2-x1))*x1 # Integration scheme for f(x)=ax+b ...
8ccc600c3d43430dd5ce8663f8518fe534cf0a01
Shio3001/koneta
/a.py
268
3.5
4
s = str(334**334) #s = str(334*334) t = 334 for i in range(333): t = t * 334 print(t) print(s) if s == str(t): print("一致") else: print("不一致") if "334" in s: print("aho") print(s.find("334")) for i , k in enumerate(s): print(i,k)
d127544f7cc2f2baa89cea3988ee07cde3c09ff4
alexandraback/datacollection
/solutions_5652388522229760_0/Python/pilagod/1.py
905
3.578125
4
class Solution(object): def fallAsleep(self, n): if n == 0: return "INSOMNIA" step = 0 # test if 1023, then stop bitsTable = 0 while bitsTable != 1023: step += 1 numBits = 0 numString = str(n * step) for i in num...
206ecd42b077c4a3f5a806060706e5ede89f7dbb
idobleicher/pythonexamples
/examples/basic-concepts/variables.py
716
4.53125
5
# To assign a variable, use one equals sign. # Unlike most lines of code we've looked at so far, it doesn't produce any output at the Python console. x = 7 print(x) # 7 print(x + 3) # 10 print(x) # 7 spam = "eggs" print(spam * 3) # eggseggseggs # Variables can be reassigned as many times as you want, # in order ...
bb6f109ac511612e7ecb4b55482416c523790c12
AshurMotlagh/CECS-100
/Lab 20-1.py
289
3.890625
4
def main(): n1 = int(input("Enter a number: ")) print() print("Calling\'show_double\' function inside main function.") show_double(n1) print() print("Back to \'main\' function.") def show_double(a): print("Double of",a,"inside \'show_double\' is:",a*2) main()
55fa571c48ba9c9e97d5e9018dd30e08e3a71908
kleinstadtkueken/adventOfCode2018
/src/2018/day_15/exercice1.py
6,389
3.5625
4
#!/usr/bin/python3 def printCave(): units.sort(key=lambda u: u.x) units.sort(key=lambda u: u.y) for y, line in enumerate(cave): for char in line: print(char, end='') print(' ', end='') for u in units: if u.y == y: print(u, end=' ') ...
011df6d90f4a76844c11154d392c809593096dfd
Wilhit/African-Countries
/afrian_countries/main.py
1,374
4.09375
4
import turtle import pandas screen = turtle.Screen() screen.title("African Countries Game") image = "blank-outline-map-africa.gif" screen.addshape(image) turtle.shape(image) # def get_mouse_click_coor(x, y): # print(x, y) # # # turtle.onscreenclick(get_mouse_click_coor) # # # turtle.mainloop() co...
0f2260ad357d88544dd38900719c2ca050ec5019
maevefarrell/hackBU_intro_to_python_2019
/Advanced/inheritance.py
4,380
4.625
5
# Advanced Python Tutorial (Inheritance) # Author: Melanie Chen # Based on material from https://docs.python.org/3/tutorial/classes.html line = "________________________________________________________" # When possible, we want to avoid rewriting the same code over and over again. Consider the following example: cla...
1cdb5f9c49d64fb6ad5e530ce74f5ba85cf65130
ayushiagarwal99/leetcode-lintcode
/leetcode/greedy/45.jump_game_ii/45.JumpGameII_JohnJim0816.py
1,459
3.796875
4
#!/usr/bin/env python # coding=utf-8 ''' @Author: John @Email: johnjim0816@gmail.com @Date: 2020-07-27 14:42:30 @LastEditor: John @LastEditTime: 2020-07-27 14:43:08 @Discription: @Environment: python 3.7.7 ''' # Source : https://leetcode.com/problems/jump-game-ii/ # Author : JohnJim0816 # Date : 2020-07-27 ########...
c5bd07fb507f74c40e5fafb38cb9d8c877bc22a6
ak-b/Problem-Solving
/tree_dfs/tree_dfs02.py
2,493
4
4
''' Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’. Time complexity # The time complexity of the above algorithm is O(N^2)O(N ​2 ​​ ), where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse eac...
d207880e827f181e91931731f7794b56d6bb7d81
sajjad065/assignment2
/Datatype/qsn35.py
406
4.125
4
total=int(input("How many elements in the dictionary ")) dic={} count=0 for i in range(total): key1=input("Enter key ") value1=input("Enter value ") dic.update({key1:value1}) print("items in dictionary ", end='') print(dic) print("Only keys ") for key, value in dic.items(): print(key) print("Only v...
b761bd43450dc937fd641e5ca547d2b18a4f0d82
insomniac-tk/AI
/search.py
6,579
4.34375
4
class Problem(object): """The abstract class for a formal problem. You should subclass this and implement the methods actions and result, and possibly __init__, goal_test, and path_cost. Then you will create instances of your subclass and solve them with the various search functions.""" def __init...
4571f4ab02e2d9bbdd32867b05e6f88290a059a8
jacquerie/leetcode
/leetcode/0202_happy_number.py
390
3.53125
4
# -*- coding: utf-8 -*- class Solution: def isHappy(self, n): seen = set() while n != 1: n = sum(int(char) ** 2 for char in str(n)) if n in seen: return False seen.add(n) return True if __name__ == "__main__": solution = Solution(...
6bbbf901087dca1fcb421c75d494b90f01039ed1
FlorenciaAK/Craps_GustavoB_FlorenciaA
/Come_Out.py
4,259
3.765625
4
print ("{}Fase Come Out (1ª fase){}".format('\033[1;31m','\033[m')) aposta_plb = 0 aposta_f = 0 aposta_ac = 0 aposta_t = 0 while not jogar_dados: tipo_aposta = input("Qual aposta você deseja realizar? pass line bet (plb) / field(f) / any craps (ac) / twelve(t) / jog...
a325a48dbe17c266cde3240ccd5d169cabf90660
Doctor-Gandalf/2048_RAE
/model/boards/tile.py
1,436
3.828125
4
__author__ = 'Kellan Childers' class Tile: """Represent different elements in a plot as simple values.""" def __init__(self, value=0): """Generate a tile. :param value: the main value of the tile (default 0) :return: a new tile with set value and background """ self._...
3883667beff4fc25589e8524e1a7e8754928fc12
rathore99/datastructure-in-python
/printTriangle.py
216
3.828125
4
height = int(input()) width = 2**(height) -1 for i in range(height): widthtmp = 2**i -1 str1 = "{:{fill}{align}{width}}" str2 = '* '*widthtmp print(str1.format(str2,fill=' ',align='^',width= width))
df6c2025091be1f7e279c5f896e5f2a18483c063
Subhash3/CodeChef
/INOI_long_chal/table_sum.py
569
3.578125
4
#!/usr/bin/python3 def get_table_sums(row, N) : table_sums = list() second_row = list(range(1, N+1)) max_score = 0 for j in range(N) : for i in range(N) : a = row[i] b = second_row[i] if a + b > max_score : max_score = a + b table_sums...
b5dc5f529205d3a91f91233e0a96c2c073ed4906
rodolfojbrandao/gitrepository
/ex82.py
305
3.75
4
resposta = 's' lista = list() pares = list() impares = list() while resposta == 's': n = int(input('digite: ')) lista.append(n) if n%2==0: pares.append(n) else: impares.append(n) resposta = str(input('quer continuar? [s/n] ')) print(lista) print(pares) print(impares)
311031fdb556d5ad32c8de85a79e453eda072421
AshimaSEthi/50-Days-50-Python-Programs
/program17.py
199
3.515625
4
keys = ['First Name','Last Name','Email'] values = ['Coding','Mente','codingmente@gmail.com','test'] dict1 = {} for i in keys: for j in values: dict1[str(i)] = j values.remove(j) break print(dict1)
4490eac7610abab274c5c8263e22c099af2ec458
mengnan1994/Surrender-to-Reality
/py/0394_decode_string.py
4,064
4.0625
4
""" Given an encoded string, return it's decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, squar...
ba46fcb683d6627648b63cb95bf0949cf97086e3
itactuk/isc-206
/testing_python_script/ejemplo_serie_div3.py
195
4
4
x = int(input('Cantidad de numeros: ')) for i in range(1, x + 1): v = int(input("n"+ str(i)+": ")) if v%3 == 0: print("Es divisible") else: print("No es divisible")
a0cef3a93c1bc9e8a136b2ece04756fb5b2fa84d
ccsreenidhin/Practice_Anand_Python_Problems
/Learning_python_AnandPython/iter and genr/problem4.py
326
3.75
4
#Problem 4: Write a function to compute the number of python files (.py extension) in a specified directory recursively. import os def pyext(f): count =0 for path,dirn,filen in os.walk(f): for i in filen: if '.py' in i: count +=1 print count pyext("c:/anand pyt...
4e5e6c2547f3fe5299e4d5e6acfbeb4dca7af436
gavthetallone/python-exercises
/easy/isbn.py
1,248
4.03125
4
print("Please type out the first 12 digits of the ISBN. For example, 978-0-306-40615") isbn_input = str(input(": ")) #taking user input input_split = isbn_input.split('-') #splitting input and placing str values into a list input_split_str = input_split[0] + input_split[1] + input_split[2] + input_split[3] ...
e296f1f95e06fdb88e65f859e27c27d7ebaf782e
sungminoh/algorithms
/leetcode/solved/740_Delete_and_Earn/solution.py
6,659
4.3125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: Pic...
e2bd169d99be8a0580eb594fc96912be352bbda1
santosclaudinei/Python_Geek_University
/sec05_ex18.py
627
4.0625
4
opcao = int(input(""" Escolha uma das opções abaixo: \t[1] - SOMAR \t[2] - SUBTRAIR \t[3] - MULTIPLICAR \t[4] - DIVIDIR Qual é a sua escolha: """)) if 0 < opcao < 5: num1 = int(input("Informe um numero: ")) num2 = int(input("Informe outro numero: ")) if opcao == 1: print(f'O resultado da...
fc5194624926df11c009e7f70719838cf57d9d16
vkallsen/ThreadCount-v1
/ThreadCount1.py
3,249
3.671875
4
#This is a list of DMC colors that are available. (Obviously not complete but a sample. dmcColors = {3811: "Turquoise - VY LT", 3812: "Seagreen - VY DK", 3813: "Blue Green - LT"} number: int #print them out for number,name in dmcColors.items(): print(str(number),name) #https://stackoverflow.com/questions/...
6e1de1037daf1e913ee720c4d4ccb9567449da62
LazyMisha/prometheus-python
/Практичне завдання 5.2.py
884
3.828125
4
''' Розробити функцію counter(a, b), яка приймає 2 аргументи -- цілі невід'ємні числа a та b, та повертає число -- кількість різних цифр числа b, які містяться у числі а. Наприклад Виклик функції: counter(12345, 567) Повертає: 1 Виклик функції: counter(1233211, 12128) Повертає: 2 Виклик функції: counter(123, 45) Пов...
63ab3a9691c5ef060bf661dfa9ed9eee4d4a9d67
hsydw/python
/초보자를 위한 파이썬 200제/098-2.py
141
4.03125
4
str1 = input('정렬할 문자열을 입력하세요 : ') sor1 = sorted(str1, reverse=True) print(sor1) sostr1 = ''.join(sor1) print(sostr1)
f5fa0865cf85aa37e60e808927574457d9b1bef5
Danielacvd/Py3
/Entrada_de_datos/entrada_de_datos_teclado.py
358
4.40625
4
""" Otra forma para que podamos introducir una cierta cantidad de datos es usando una lista, pero tenemos que saber desde antes cuantos seran los datos que ingresaremos, usaremos una lista vacia """ lista_de_datos = [] for x in range(5): lista_de_datos.append(input("Introduce un dato: ")) print(lista_de_datos) for...
476e524eecb59c62f810f0e9bf5c00e2f60b3c20
netotz/p-dispersion-problem
/heuristic/functions.py
1,257
3.5625
4
''' Supplementary functions for the heuristics. ''' from typing import Tuple from models import Point, Matrix, Solution def objective_function(solution: Solution, dist_matrix: Matrix) -> int: ''' The maximin objective function of the PDP: to maximize the minimum distance between any two of the points in ...
04f510a18adf2ccc2f01b414790a0e27d380cb8c
xibaochat/crescendo_projects
/10days_stats/0day/1.py
800
3.921875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def manage_input(): try: num = int(input()) except: print('not an integer') x = [] w = [] try: x = list(map(int, input().split())) w = list(map(int, input().split())) except: pr...
5856b3d90bed87d1884e50ac6e9647a670764fa4
MrDengT/DensityPeakCluster
/cluster_dp.py
7,143
3.5
4
from collections import defaultdict import numpy as np import matplotlib.pyplot as plt class Graph(defaultdict): def __init__(self, input_file, sep=" ", header=False, undirect=True): """ 文件格式: node1, node2, dist(node1, node2) ... 默认是无向图 """ super(Gr...
9e691d206e7c6968de2ea4929537e10a2a878225
yoursshahnawaz/python_projects
/fibonacii_series/script.py
301
4.28125
4
# Fibonacci Series - Python Project n = int(input("Enter How Many Elements you want in the Fibonacci series = ")) a = 0 b = 1 print ("Fibonacci Series with",n,"elements -: ") print (a,end="") print (", "+str(b),end="") while n>2: c=a+b a=b b=c print (", "+str(c), end="") n-=1
0fcf34ae04fdbd536d6579ea0647b6e506e2acf3
HebertFB/Exercicios-de-Python
/secao_5_exercicios/ex21.py
1,435
4.03125
4
# EX21 print(f'{" " * 25} \033[1;33mEscolha a opção:\033[m') print('\033[1;33m=-\033[m' * 33) print('1- Soma de 2 números.') print('2- Diferença entre 2 números (maior pelo menor).') print('3- Produto entre 2 números.') print('4- Divisão entre 2 números (o denominador não pode ser zero).') print('\033[1;33m=-\033[m' * ...
e0cc3bd6370514ce005282937aa3510342366ff7
haosdent/AProblemADay
/leetcode_224.py
981
3.671875
4
class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): cur = self r = [] while cur is not None: r.append(cur.val) cur = cur.next return str(r) class Solution: # @param head, a ListNode # @return a L...
ae4b451bc1f8e93d7dc5ebb4716e4cfb3d6d2777
DC9600/google_scraper
/google_filename1.py
2,725
3.640625
4
# Google Search Results Scraper # make sure to install the following libraries: # pip install beautifulsoup4 # pip install google import numpy as np count = 0 try: from googlesearch import search except ImportError: print("No module named 'google' found") # to search #query = input('what do you want to search?: ') ...
fef3abb48f85cc4dde2cdbe47239984c2660d584
82-petru/codecademy_classes
/Classes_12.py
747
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 20:52:04 2019 @author: petru """ class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def self_condition(self):#method to modify condtion(variable member) value self.c...
057f00227d5e36f09aab902a3d7cf30ec8b8df1c
aihelena/advent_code
/1_2.py
437
3.5
4
puzzleInput= total=0 #running total sum strungInput=str(puzzleInput)#turns input into digits listedInput=[int(x) for x in strungInput] #split list of digits in half firstHalf=listedInput[0:len(listedInput)/2] secondHalf=listedInput[len(listedInput)/2:len(listedInput)] #check each digit with corresponding one in secon...
2df27d943ce5f423d42a3acd9663434065316c8a
PacktPublishing/Modern-Python-Standard-Library-Cookbook
/Chapter05/datetimes_09.py
326
3.765625
4
import datetime def workdays(d, end, excluded=(6, 7)): days = [] while d.date() < end.date(): if d.isoweekday() not in excluded: days.append(d) d += datetime.timedelta(days=1) return days print(workdays(datetime.datetime(2018, 3, 22), datetime.datetime(2018, 3, ...