blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6a05b06340aaa9f43e39ea930ec174c5cba6cbf2 | RyutaHoshino/SchoolProject | /q8.py | 184 | 3.53125 | 4 | #coding:utf-8
import random
num=30
count=0
for i in range(num):
a=random.uniform(0,1)
b=random.uniform(0,1)
if a*a+b*b<1:
count+=1
print ("pi="+str(4.0*count/num))
|
d5c5ef30eac59ec1c86b0bafad460dd8407e709b | ErenBtrk/Python-Fundamentals | /Python File Management/2-ReadFile.py | 1,069 | 3.90625 | 4 | # try:
# file = open("newfile.txt") #default mode is "r"
# print(file)
# except FileNotFoundError:
# print("File not found error.")
# finally:
# print("File is closed.")
# file.close()
#######################################################
file = open("newfile.txt","r",encoding = "utf-8") #utf-8 ... |
9a67d8901e07a8126a45a6eca617736e6a81b616 | SidPatra/ProgrammingPractice | /Coding/Ex5.py | 714 | 3.890625 | 4 | # Base 10 to Base 2
# algorithm
# j
# SUM bi * 2**i
# i=0
# 1. Determine bj by finding the greatest power of 2 less than or equal to decimal
# 2. find the next bi set into 1 by finding (bj+bi) <= decimal
# 3. Repeat 2 until you sum is equal to decimal
print('base 10 number:')
b10 = int(input()) # base10 number
f ... |
e00e27f8d239b84d0c6192b52177daacfaa267ec | mube1/Cryptool | /decrypt_with_offset.py | 1,361 | 3.734375 | 4 | # the data used can be programmed to be from the user
Cipher_text="utnrocifrigaYaeoanomgnsregrmnulpi"
keye=5 # the length of the key
offset=6 # the offset
Len=len(Cipher_text)+ offset # total length assumed with offset in mind
offset=offset%(2*keye-1) # offset at most can be twice the key minus 1
Plain=[None]*(Len)
... |
438befc2bbe97ae45fb45a2a3a353338640006b2 | sweavo/code-advent-2020 | /day10_1.py | 1,683 | 4 | 4 | """ the problem
It looks like the question of whether such a path exists is a red herring. It's
enough to sort the list of "joltages" and then count the intervals as we walk
up the values. I can use the interval as an index to a dict and just increment
the value there.
python contains collections.Counter that encaps... |
524ea5331a81c8a3dec7b5a5b4f8497b4fc5edae | patkhai/LeetCode-Python | /LeetCode/DecodeString.py | 1,280 | 4.15625 | 4 | '''
Given an encoded string, return its 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... |
d37cd4d10fee602ffcb0433c98d1d19b3e3c45d2 | Akshatt/show-me-the-data-structures | /problem2.py | 1,361 | 3.546875 | 4 | import os
def find_files(suffix, path):
if suffix == '' or not os.path.exists(path):
return "Error:for {} files in {}\nFile/Directory does not exist".format(suffix,path)
path_entries = os.listdir(path)
#base case
if len(path_entries) == 0:
return []
#file_paths = [pa... |
708a9a83230f741936115df2688ecb1eb9ed925c | sengarmaithili/python_project | /load_csv.py | 4,013 | 3.5 | 4 | import csv
def load_students_csv():
elist = []
file = open('students.csv','r')
reader = csv.reader(file)
header = ('FormNumber', 'Name', 'A_rank','B_rank', 'C_rank','Degree','Percentage','Preference', 'Course_name', 'CenterID', 'Payment', 'Reported_center', 'PRN')
def convert_student_field(field, ... |
a4987ff5c4ca812748fcdea0805f20f1e71d9262 | colephalen/SP_2019_210A_classroom | /students/BrianB/lesson04/dic_lab.py | 1,648 | 4.5625 | 5 | #!/usr/bin/env python3
d = {
'name': 'Chris',
'city': 'Seattle',
'cake': 'Chocolate'
}
def dict_1():
"""
reads a dictionary
Returns: dictionary, deletes one key, adds a new key: value, displays the
new key: value, displays dictionary keys and values and test if 'cake' is
a key an... |
500c4932fb601d1397d7d89c20dbf9bcc24398a9 | MihaiCatescu/python_exercises | /exercise9.py | 510 | 4.1875 | 4 | '''
Take two lists and write a program that returns a list that contains only the elements that are common
between the lists (without duplicates). Make sure your program works on two lists of different sizes.
'''
import random
list_a = random.sample(range(100), 10)
list_b = random.sample(range(100), 15)
list... |
a6e28f9420a501add2bfcdb49cf10b1e44f3216d | mmbsow/Coursera_Intro2DataScience_UW | /assignment3/unique_trims.py | 508 | 3.609375 | 4 | import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
def mapper(record):
# key: friend A
# value: friend B
sequence_id = record[0]
nucleotide = record[1][:-10]
if nucleotide:
mr.emit_intermediate(nucleotide, 1)
def red... |
0b8260b4808c46537a208d9f1f1747c404bdd03d | subZiro/adventofcode_2020 | /code/day_9.py | 2,796 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# --- Day 9: Encoding Error --- #
from itertools import combinations
"""
For example, suppose your preamble consists of the numbers 1 through 25 in a random order.
To be valid, the next number must be the sum of two of those numbers:
26 would be a valid next number, as it could be 1 plus... |
c0216360ebf4789deb3376c69da0e05a98acb813 | Shristi19/DataStructuresInPython | /tree traversal.py | 941 | 3.71875 | 4 | class node:
def __init__(self,key):
self.right=None
self.left=None
self.val=key
def preorder(root):
if root:
print(root.val)
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
... |
9a77ed842cee4f07713ca1ba35b68b46b76a1d13 | Darcy382/code-breakers | /2.Fundamentals/linked_list_cycle.py | 1,192 | 3.734375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# First Attempt O(n) time and O(1) space
def hasCycle(self, head: ListNode) -> bool:
if head:
slow = head.next
if slow:
fast = head.next.next
else:
return False
else:
... |
70988a0caf9a1a1ef063df4939741a3ea26986f0 | ellinx/LC-python | /IntersectionOfTwoArraysII.py | 1,042 | 4.1875 | 4 | """
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
1. Each element in the result should appear as many times as it shows in both arrays.
2. The result can be ... |
3dbad7e2ab1b82f21d88b3a1a515ed5c5095dfcd | ravindrajoisa/Python | /Basics/Inherit and Polymorphism.py | 1,201 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[20]:
class Student():
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
self.term = 1
def name(self):
return self.firstname + " " + self.lastname
class WorkingStudent(Student): ... |
480c0f84d8766e342b0cac105589dc7ef857a4e7 | syedayazsa/HackOff-MLH | /brain.py | 2,582 | 3.5 | 4 |
#Importing keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import numpy as np
import pickle
#Initializing the CNN
classifier = Sequential()
# Step 1 - ... |
fb6ac69ceb4ebd677638c7570619269a016de3b8 | urluba/summer2018 | /20180808/calculatrice.py | 1,068 | 3.765625 | 4 | '''
1 - Lire un fichier
dont le format est:
int;int;operation (+|-|*|/)
exemple:
1;1;+
2 - utiliser les informations fournies dans le fichier pour effectuer les operations arithmetiques définies
3 - Ecrire les résultats justes dans un fichier
sous le format:
L'addition de <premier nombre> avec <second nombre> est:... |
eca4e4b2dd9953fc06121e9c2330c7d02a5bfa64 | jadewu/Practices | /Python/Copy_List_with_Random_Pointer.py | 787 | 3.546875 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
# 用字典存储每个原节点和对应的新节点,d中的key是原节点,value是新节点,d[node] = new_node,这样可以很方便地找到next和random
# 核心:d[node].random = d[node.random] ... |
4fbfb712553dfa75b6ae1d3f2d09314bf17a701c | yuuuhui/Basic-python-answers | /梁勇版_5.54py.py | 396 | 3.65625 | 4 | import turtle
from math import *
turtle.showturtle()
turtle.penup()
turtle.goto(-175,0)
turtle.pendown()
turtle.goto(175,0)
turtle.dot()
turtle.penup()
turtle.goto(0,-180)
turtle.pendown()
turtle.goto(0,180)
turtle.dot()
turtle.penup()
turtle.goto(-15,0.25 * 15 ** 2)
turtle.pendown()
for i... |
42b18e684da6da0da7b056b2fe12e6d8474aa642 | mfaria724/CI2691-lab-algoritmos-1 | /Laboratorio 03/Lab03Ejercicio3.py | 985 | 3.765625 | 4 | #
# Lab03Ejercicio3.py
#
# DESCRIPCION: Programa que dado un entero positivo n, determina si n
# es perfecto.
#
# Autor:
# Manuel Faria
# Variables:
# n: int // ENTRADA: Número que se desea verificar si es primo.
# i: int // Iterador que servirá para salir del do.
# k: int // Valor donde se almacenará la sum... |
3fb841d16f7d56af86d245f390ee049ea754fda2 | sunxianfeng/LeetCode-and-python | /leetcode with python/sort colors.py | 572 | 3.6875 | 4 | # -*- coding:utf-8 -*-
def sortColors(A):
len_A = len(A)
if len(A) == 1:
return
left = 0
right = len_A - 1
i = 0
while i <= right:
if A[i] == 0:
if left == i:
i += 1
else:
A[left], A[i] = A[i], A[left]
left += 1
... |
64b3429e5b8f55550c3715614c5c1df99990d475 | tompika/num_beadando | /problems/MatrixVektor/main.py | 867 | 3.921875 | 4 | #!/usr/bin/env python3
from functools import reduce
def matrix_vector_multiplication(A, v):
nrows = len(A)
w = [None] * nrows
for row in range(nrows):
w[row] = reduce(lambda x, y: x + y, map(lambda x, y: x*y, A[row], v))
return w
def main():
first_line = list(map(float, input().strip().... |
e801f62f4b15b20a3ac2921f9bc0c1c2b04db954 | miloscomplex/100_Days_of_Python | /day-18-start/spirograph.py | 488 | 3.6875 | 4 | from turtle import Screen
import turtle as t
import random
tim = t.Turtle()
t.colormode(255)
tim.shape("turtle")
tim.pensize(3)
tim.speed("fastest")
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r,g,b)
directions = [0, 90, 180, 270]
he... |
0ea75584e69d9f7b96110738982b9a4eeab490a1 | Randomgamer22/uploadingFile | /uploadFiles.py | 809 | 3.5 | 4 | import os
import dropbox
class TransferData:
def __init__(self, token):
self.token = token
def upload_file(self, file_from, file_to):
dbx = dropbox.Dropbox(self.token)
for root, folders, files in os.walk(file_from):
print("done")
for f in files:
local_path = os.path.join(root, f)
... |
1f0d272771edb9ea8f6e5ae363d5d68d246ede3f | hajin-kim/2020-HighSchool-Python-Tutoring | /day2/day2-09 elif.py | 146 | 3.9375 | 4 | num1 = int( input() )
num2 = int( input() )
if num1 > num2:
print(num1)
elif num1 < num2:
print(num2)
else:
print(num1)
|
e99c65c86d7261f4847bb41395750f1aa682d1c4 | muhadeel/hadoop_patterns | /filtering.py | 665 | 3.703125 | 4 | import re
from mrjob.job import MRJob
class MRJobFilter1(MRJob):
def mapper(self, _, line):
# assume CSV input, format Author;Title;Year
# retrieve records from 2021
attributes = line.split(';')
if attributes[2] == '2021':
yield line, None
def reducer(self, key, v... |
8e3ac4363427cc16f768e402a67ccaaabdee2a96 | archeskeith/socket_programming | /client.py | 1,638 | 3.578125 | 4 | import socket
#declares global variables
#variables match with the server variable values to initiate compatibility
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "192.168.1.5"
ADDR = (SERVER,PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#connect ... |
4b46da9e14f16a6b97e735cb7aac9da9ebceb9a4 | gabriellaec/desoft-analise-exercicios | /backup/user_241/ch16_2020_06_22_17_36_57_149053.py | 93 | 3.640625 | 4 | x = input(float("Qual o valor da conta: ")
print("Valor da conta com 10%: R$ X.YZ".format(x)) |
3a7478b78f498878743969ab29bc5366131bede0 | daniel-reich/turbo-robot | /cHzvB5KCWCK3oCLGL_22.py | 1,985 | 4.40625 | 4 | """

The goal of this challenge is to implement the logic used in Conway's Game of
Life. Wikipedia will give a better understanding of what it is and how it
works (check the resources tab above).
### Rules
* **For a space that's ... |
bfd8165d6f952c96fa9472a0be1bfacffa762a00 | MaksimBibaev/task6 | /6.py | 636 | 3.71875 | 4 | try:
kol=int(input("Сколько значений вы хотите ввести?"))
except ValueError:
print("Ошибка")
else:
if kol>0:
array=[]
c=0
count=0
while c!=kol:
a=int(input("Введите значение"))
array.append(a)
c+=1
delta=int(input("Введите дэльту"))... |
f712278fc4345231a27bf8d8f5a58d12bb508fc5 | wncbb/prepare_meeting | /airbnb/url_decode/2.py | 290 | 3.671875 | 4 | def letterCasePermutation(S):
res = ['']
for ch in S:
if ch.isalpha():
res = [i+j for i in res for j in [ch.upper(), ch.lower()]]
else:
res = [i+ch for i in res]
return res
s='aBc'
rst=letterCasePermutation(s)
for v in rst:
print v
|
50de5e3cdb9f19eb82032e06e93573937c68a7d8 | MJeremy2017/dancing-pie | /indeed/linklist.py | 931 | 3.71875 | 4 | class Node:
def __init__(self, val, nxt=None):
self.val = val
self.nxt = nxt
class LinkedList:
def __init__(self, head):
self.head = head
def find(self, index):
i = 0
node = self.head
while node:
if i == index:
return node.val
... |
0f05ebdeb700a3226ed2fe0dbb14b06606437a81 | rajeshalda/Python-Tutorials | /Day 7 len str sliceing.py | 1,322 | 3.9375 | 4 | #mystr="Rajesh is Good Boy"
#print(mystr)
#in python index start with 0,1,2..
#in this i want only some charater that i want
mystr="RAJESH IS GOOD BOY"
print(mystr[0:3]) #RESULT RAJ
#HERE YOU 0 INCLUDE AND 3 EXCLUDE ITS TAKE 012 TOTAL 3 STRING
#R A J E S H
#0 1 2 3 4 5 6
mystr="RAJESH IS GOOD BOY"
print(len(mystr))... |
fc70f19a1067c4ce3665c022940510068df607c3 | Eragon-18/Project98 | /swappingData.py | 355 | 3.625 | 4 | def swappingFileData() :
f1in = input("Enter name of the first file")
f2in = input("Enter name of the second file")
f1op = open(f1in, "r")
f2op = open(f2in, "r")
f1r = f1op.read()
f2r = f2op.read()
f1ow = open(f1in, "w")
f2ow = open(f2in, "w")
f1ow.write(f2r)
f2... |
1bed2ec2ebdc4eebfa40805960470e2ea44a5d52 | ChastityAM/Python | /Python-data/identity_operators.py | 396 | 3.96875 | 4 | x = 10
y = 10
print(x == y)
print(x is y)
str1 = "Hello"
str2 = "Hello"
print(str1 == str2)
print(str1 is str2)
list1 = [1, 2, 3] #these have the same values, but are
list2 = [1, 2, 3] # 2 different objects
print(list1 is list2) #checks if they are the same object(identity)
print(list1 == list2) #checks if values are s... |
f4f98df85530b6c42adf4eac325b569330479f58 | RafaelDSS/uri-online-judge | /iniciante/python/uri-1045.py | 548 | 3.875 | 4 | # -*- coding: utf-8 -*-
valores = list(map(float, input().split()))
valores.sort(reverse=True)
a, b, c = valores
no = True
if a >= b+c:
print('NAO FORMA TRIANGULO')
no = False
if a**2 == b**2 + c**2 and no:
print('TRIANGULO RETANGULO')
if a**2 > b**2 + c**2 and no:
print('TRIANGULO OBTUSANGULO')
... |
75a05b8430b02f3bd7e654b81031a5245a398482 | JimmyKent/PythonLearning | /com/jimmy/basic/PlotLearning.py | 1,533 | 3.96875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def draw_point(x_list, y_list):
# 绘制散列点
plt.plot(x_list, y_list, '*')
plt.show()
def draw_line(a, b):
"""
关键在于
1.坐标轴的取值范围
2.x的取值范围
y = ax + b
:param a:
:param b:
"""
plt.figure() # 实例化作图变量
plt.title('line') # 图... |
41b006028f46c25be4989ee1c3997a388bf3a8ee | snehadasa/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 598 | 4.375 | 4 | #!/usr/bin/python3
"""Module to print square pattern"""
def print_square(size):
"""prints square pattern for given size.
size: size of the square to be printed.
Return: square pattern.
Raise: TypeError, ValueError.
"""
if not isinstance(size, int):
raise TypeError("size must be an ... |
0187158a50fdaa6078cd13e27dd38f90d8655acb | Fayebest/leetcode-hit | /在排序数组中查找元素.py | 1,467 | 3.5625 | 4 | class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans = self.half_search(nums,target,0)
sta = 0
end = 0
if ans == -1:
return [-1, -1]
if ans > 0 an... |
e3ade15099b295e649aa1a23f132556213dac865 | ceasaro/ceasaro_py | /adventofcode.com/2021/day_01/puzzle_2.py | 676 | 3.703125 | 4 | #!/usr/bin/python3
import argparse
import sys
def run(input_file):
increases = 0
values = []
with open(input_file) as fp:
for position, line in enumerate(fp.readlines()):
value = int(line)
if len(values) == 3:
previous_sum = sum(values)
valu... |
44ca7a5b2cb778360ea3a00c3fd964e804928945 | kwasnydam/python_exercises | /StrukturyDanychIAlgorytmy/scripts/variables.py | 656 | 3.890625 | 4 | var1 = [2, 4, 6] #var1 nie jest obiektem, jest referencja
print(var1) # [2 4 6]
var2 = var1 #var2
var2.append(8)
print(var1) #[2 4 6 8]
print(var2) #[2 4 6 8]
#Typowanie dynamiczne
var1 = 1
print(type(var1)) #int
var1 += 0.1
print(type(var1)) #float
#zasieg zmiennych
zm1 = 10
zm2 ... |
b624bf7c995cce05c921b52f102c83d670292317 | mandar-degvekar/DataEngineeringGCP | /StringReverse.py | 287 | 4.25 | 4 | def reverse(s):
str = ""
for i in s:
# print(i)
str = i+" "+ str
#print(str)
return str
print("Hello World")
fval = input("Enter your fname: ")
lval = input("Enter your fname: ")
print("----------------------------------------")
print("reverse " + reverse(fval+lval))
|
a16b1fb45854540de19b161c0868d53e7574d686 | RafaelTeixeiraMiguel/PythonUri | /br/com/rafael/teixeira/uri/beginner/uri_1010_simple_calculate.py | 260 | 3.796875 | 4 | x = 0
total = 0
for x in range(0,2):
values = input()
array = []
array = values.split()
cd = int(array[0])
qtd = int(array[1])
price = float(array[2])
total += qtd * price
print("VALOR A PAGAR: R$ {total:.2f}".format(total = total)) |
5070854d2d4c1b633d68922137ea0e638a818ef2 | mrtonks/Machine_Learning_AZ | /Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/data_preprocessing_template.py | 726 | 3.59375 | 4 | # Data Preprocessing
# Importing the libraries
import numpy as np # Maths
import matplotlib.pyplot as plt # Plot charts
import pandas as pd # Import/manage datasets
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values
# Splitting the dataset int the ... |
14d726b10795edfd2c88c482e212a7dd7861cebd | jackngogh/Python-For-Beginners | /codes/03_data_types/002/tuples.py | 138 | 3.53125 | 4 | list = (1, 2, 4)
print(list)
print(list[0])
list2 = (4, 5, 6)
print(list2)
print(list2[0])
print(list2[1])
print(list2[2])
list2[2] = 7 |
9d5373aec397f0ee7968d6ccd08a3471cf871c7a | kojo-gene/python-tutorials | /lecture17.py | 207 | 3.671875 | 4 | print(7 > 6 and 6 >= 6) #true and true => true
print(3 != 3 or 4 == 4) #false or true => true
print(not 5 > 2) #false
print(not 5 < 3 and true or 6 <= 6 and not false) #true and true or true and true => true |
74d04a7bf3e559b0660a391868cc476d72c3ec93 | n17/python_audio_demo | /spectrogram.py | 427 | 3.5625 | 4 | """
Compute and display a spectrogram.
Give WAV file as input
"""
import matplotlib.pyplot as plt
import numpy as np
import sys
from audio_demo import spectrogram, display_spectrogram, read
if __name__ == "__main__":
if len(sys.argv) != 2:
print "Usage: python spectrogram.py wavfile.wav"
sys.exit(1)
... |
8669d4ecaf3cb3b70bdd2b06e47c8652919482fc | Radg/projecteuler | /012/euler012.py | 1,202 | 3.953125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven trian... |
33ec8c4fc333deaa74d93a92ebb0d87967c2ca98 | salvador-dali/algorithms_general | /interview_bits/level_6/06_dp/10_2d_string_dp/06_interleaving-strings.py | 2,478 | 3.640625 | 4 | # https://www.interviewbit.com/problems/interleaving-strings/
def isInterleave(s1, s2, s3):
if len(s1) + len(s2) != len(s3):
return False
match = [[False for _ in xrange(len(s2) + 1)] for _ in xrange(len(s1) + 1)]
match[0][0] = True
for i in xrange(1, len(s1) + 1):
match[i][0] = match[... |
97a7d55d121239380cf5aceb9848dc38c0988516 | ArkaprabhaChakraborty/Datastructres-and-Algorithms | /Python/Rat_in_a_maze.py | 2,317 | 3.703125 | 4 | '''
Rat in a maze backtracking problem.
Given a maze of zeroes and ones where 0's mark valid path and 1's mark obstacles, find the shortest path from a given source to a given destination.
'''
import sys
sys.setrecursionlimit(10**6)
def rat_travel(maze,n,source_x,source_y,dest_x,dest_y):
solution = [[0 for i... |
293a7f89517569f85aa2b6922fed77cde27574a6 | saiphaniedara/HackerRank_Python_Practice | /Sets_SymmetricDifference.py | 453 | 3.984375 | 4 | '''
Problem statement:
https://www.hackerrank.com/challenges/symmetric-difference
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from sys import stdin
m = int(stdin.readline())
M = set(map(int,stdin.readline().split()))
n = int(stdin.readline())
N = set(map(int,stdin.readline().spl... |
4a6db656ad82b3a0f2f58fab8b3af26a4b29aa1b | TrendBreaker/project-euler-python | /problem_31.py | 714 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Problem 31
In England the currency is made up of pound, £, and pence, p,
and there are eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p... |
6089aeae5cd44cecbf8e7ac07002ef7e4f2a77e7 | JackoDev/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 637 | 3.59375 | 4 | #!/usr/bin/python3
"""
a function that queries the Reddit API and returns the number of
subscribers (not active users, total subscribers) for a given
subreddit. If an invalid subreddit is given, the function should return 0.
"""
from requests import get
def number_of_subscribers(subreddit):
"""
doc for numbe... |
50eab386c8476099bb9726770fd93df5bd6aa4c5 | analuisadev/100-Days-Of-Code | /day-18.py | 535 | 3.65625 | 4 | from time import sleep
print ('\033[1m{:=^40}\033[m'.format(' PALINTHROME DETECTOR '))
phrase = str(input('\033[1mType a phrase:\033[m ')).strip().upper()
sleep(1)
p = phrase.split()
together = ''.join(p)
reverse = together[::-1]
print ('\033[1mThe reverse of\033[m \033[1;32m{}\033[m \033[1mis\033[m \033[1;32m{}\033[m'... |
f4c07cda9a2a0da66f826b5088bfeb4cd1a31251 | oGabrielF/DocumentationPython | /Python/Advanced/ListComprehension/listComprehension.py | 1,001 | 4.34375 | 4 | # PYTHON AVANÇADO LIST COMPREHENSION
# FORMA SIMPLES DE FAZER ISSO
x = [1,2,3,4,5]
y = []
# Obter os valores dos números da lista x ao quadrado
for i in x:
y.append(i**2) # Append adicionar um item a lista
print(x) # Números da lista
print(y) # Números da lista x ao quadrado passado pra lista y
# FORMA UTILIZAN... |
dcddb9d52ccc8e06ea900432162a619669ac5134 | Manikantha-M/python | /programs/patterns.py | 845 | 3.765625 | 4 | # n=int(input('Enter:'))
# for i in range(1,n+1):
# for j in range(i):
# print('*',end=' ')
# print()
# n=int(input('Enter:'))
# for i in range(n,0,-1):
# for j in range(i):
# print('*',end=' ')
# print()
# n=int(input('Enter:'))
# k=1
# for i in range(1,n+1):
# for j in range(i)... |
185bddb2e47eef7574be68f34b2145f1af659a23 | HWNET12/ENAUTO | /functions.py | 299 | 3.828125 | 4 | import datetime
def greet():
#Get current time
dt = datetime.datetime.now()
if dt.hour <= 11:
greeting = "morning!"
elif dt.hour <= 17:
greeting = "afternoon!"
else:
greeting = "night"
print(f"Hello, good {greeting}.")
greet() |
b2bb9afd51c08d3bca711048b7d69f8e804afcd5 | Eqliphex/python-crash-course | /chapter03 - Lists/exercise3.8_seeing_the_world.py | 399 | 4.25 | 4 | locations = ['Nepal', 'Japan', 'Antarktis', 'Switzerland', 'Russia']
# Raw output
print(locations)
# Temp sorted
print(sorted(locations))
# Still in original form
print(locations)
# Reversing the list
locations.reverse()
print(locations)
locations.reverse()
print(locations)
# Sorting the list permanently
loc... |
c4135a15bc611302f9b0f954d9fdf6c8aafd6873 | yue-w/LeetCode | /Algorithms/429. N-ary Tree Level Order Traversal.py | 2,184 | 3.734375 | 4 |
from typing import List
## Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
from collections import deque
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
#return self.method1(root) ## bfs
... |
3b81ebdf3d49546c9c0d6fb36c5bdca7bc659062 | Aswani-kolloly/luminarPython | /collections/list_pgm2.py | 321 | 3.703125 | 4 | lst=list()
r=int(input("enter range of list"))
print("Enter elements")
for i in range(0,r):
lst.append(int(input()))
print("\nList\n",lst)
num=int(input("Enter number"))
print("\n 'pairs")
for i in range(0,r):
for j in range(i+1,r):
if (lst[i]+lst[j]==num):
print("\n(",lst[i],",",lst[j],")")... |
3cdef6d1da4c9fe5d6c0ff43ebc9e4b836854068 | Sam-Tennyson/Database-Application | /mainDB.py | 1,522 | 3.703125 | 4 | from pythondb import DBHelper
def Application():
db = DBHelper()
while True:
print("--------------WELCOME--------------")
print()
print("Press 1 to Insert new user")
print("Press 2 to display all user")
print("Press 3 to delete user")
print("Press 4 to update us... |
286b355d7e02857ea0730b1a7e57b7fe62b8aa85 | VivaLaDijkstra/AC-Automation | /queue.py | 321 | 3.71875 | 4 | #! /usr/bin/env python
from collections import deque
class queue(deque):
def push(self, item):
self.append(item)
def pop(self):
return self.popleft()
def test():
q = queue()
for i in range(10):
q.push(i)
while q:
print q.pop()
for i in range(10):
q[i] = i * i
if __name__ == '__main__':
test(... |
08790d897e0a5543f7c8fdcd900efeffc6c2b6db | muon012/python-Masterclass | /38-updatingShelve.py | 1,672 | 4.5 | 4 | # TWO WAYS TO UPDATE SHELVES
print("------------------------- 1 -------------------------")
# First method:
# We create a temporary variable that will hold the values of a key. In this case we create a temporary list to
# hold the values of the key we want to append.
# We then append that temporary list.
# Finally we s... |
a22020227f6ec17d0303e536f8f35bfe3e6c87b9 | jedzej/tietopythontraining-basic | /students/pluciennik_edyta/lesson_02_flow_control/knight_moves.py | 237 | 3.5625 | 4 | a = int(input())
b = int(input())
c = int(input())
d = int(input())
knight_can_move = (
(abs(a - c) == 2 and abs(b - d) == 1)
or (abs(a - c) == 1 and 2 == abs(b - d))
)
if knight_can_move:
print('YES')
else:
print("NO")
|
47b8bc485073e7c3cc1c7b1a763ebe5db9e24eb6 | MuSaCN/PythonLearning | /Learning_Basic/老男孩Python学习代码/day3-函数与变量/func_test1.py | 397 | 3.734375 | 4 | # Author:Zhang Yuan
#定义一个函数
def function1():
"""testing1,注释最好写上"""
print("you are in the Testing")
return True
#定义一个过程(没有返回值)
#python中过程也有返回值None
def function2():
"""Testing2"""
print("you are in the Testing2")
x=function1()
y=function2()
print("from func1 return is %s"%x)
print("from func2 retu... |
d733f7934374419f25b2599d4ccecafc6196ca00 | yogesh1234567890/insight_python_assignment | /completed/Data18.py | 239 | 4.375 | 4 | #18. Write a Python program to get the largest number from a list.
input_string = input("Enter a list element separated by space: ")
list = input_string.split()
list.sort()
print("The largest number in the list is: " + str(list[-1])) |
d918507818bae64f03848382b47df0ce9f0b5999 | tcrowell4/adventofcode | /2020/day10_part2_working.py | 4,153 | 3.859375 | 4 | #!/usr/bin/python
# aoc_day1_part1.py
"""
--- Day 10: Adapter Array ---
Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off!
Its battery is dead.
You'll need to... |
1767fa67e54e485a8a1e9cf0a4437fa7754d8023 | axu682/SkyMap | /Constellations v4/Cardinal.py | 2,080 | 3.6875 | 4 | import math
class Cardinal(object):
def __init__(self, label, angle):
# initialize coordinates
self.initialX = math.cos(math.radians(angle))
self.initialY = 0
self.initialZ = math.sin(math.radians(angle))
self.x = self.initialX
self.y = self.initialY
... |
f4278dabf3056e95385a70d8928bc4f837b23572 | Silentsoul04/notes-8 | /algorithm/链表/83. 删除排序链表中的重复元素.py | 1,750 | 4 | 4 | """
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from notebook.algorithm.链表.utils import ListNode
from notebook.algorithm.链表.utils import init_ln
from notebook.al... |
c8605720817f452bfdb9915a9288d2a9e9e29841 | priyapower/python_gui_calculator | /practice/g_layout.py | 1,177 | 3.703125 | 4 | """Grid layout example."""
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QGridLayout # Imports the Grid Layout Manager class
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QWidget
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("QGridLayout"... |
f53f566bd7936089260b15f73ef957f03a7b8d53 | dafnemus/python-curso-udemy | /Unidad_6/for_1.py | 1,292 | 3.71875 | 4 | # pylint: disable=missing-docstring
# Uso del FOR:
# Imprimir las letras de una cadena.
PALABRA = 'mañana'
for letra in PALABRA:
print(letra)
print()
# imprimir los elementos de una lista.
lista_nombres = ['lola', 'pablo', 'matias']
for persona in lista_nombres:
print(persona)
print()
# imprimir todad las... |
fec6976e2e000a5ee788816800a4ab2a42e9e2e3 | DuncanArani/Security | /run.py | 8,796 | 3.578125 | 4 |
#!/usr/bin/env python3.6
import string
import random
import datetime
from locker import Locker
from user import User
def passwor_generator(size=8, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def new_password(account, username, thepass):
new_pass ... |
16e5616346fa5b01c020afead8a97565c883a326 | yzjbryant/YZJ_MIX_Code | /Python_Code_Beginner/05_高级数据类型/hm_21_遍历字典的列表.py | 687 | 4.09375 | 4 | students = [
{"name":"阿土"},
{"name":"小美"}
]
#在学员列表中搜索指定的姓名
find_name = "李四"
for stu_dict in students:
print(stu_dict)
if stu_dict["name"] == find_name:
print("找到了 %s" % find_name)
#如果已经找到,应该直接退出循环,而不再遍历后续的元素
break
# else:
# print("抱歉没有找到 %s... |
76a6d212e536eedf75d1df0ab7fc499e7d7b491d | feiyu4581/Leetcode | /leetcode 51-100/leetcode_58.py | 508 | 3.609375 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
res, first = 0, True
for index in range(len(s) - 1, -1, -1):
if s[index] != ' ':
first = False
if s[index] == ' ' and not first:
br... |
645b7c8314d0e3cf26ed1762fd3d03b93675eb4c | ogenodisho/Tkinterweave | /utils.py | 876 | 3.65625 | 4 | '''
This module is just for random/helpful utility methods
that many other modules may find useful.
'''
# Returns a tuple of coords that represent
# (in order) the width, height, xPos, yPos of a window.
def get_window_geometry(window):
l = []
curr_value = ""
for letter in window.geometry():
if... |
a9b2516a3a8ca078519f0668c047cf049872df61 | Aasthaengg/IBMdataset | /Python_codes/p03729/s699671169.py | 152 | 3.546875 | 4 | def main():
num = list(map(str,input().split()))
if num[0][-1]==num[1][0] and num[1][-1]==num[2][0]:
print('YES')
else:
print('NO')
main() |
217246b94c23f4047492aad374940d8f15cae075 | garyyli/Unit5 | /listDemo.py | 272 | 4.21875 | 4 | #Gary Li
#11/14/17
#listDemo.py - print out the first and last word in a list
words = input('Enter a list of words: ').split(' ')
#print out the list one item per line
for w in words:
print(w)
print('The first word is', words[0])
print('The last word is', words[-1]) |
3ab41de7d71e19023eba97a7dc0f0a7d9a2865b3 | dolsbrandon/python | /rand_num_game.py | 1,375 | 4.15625 | 4 | #Random Number Guess Game by Brandon Dols
# import random functions
from random import seed
from random import choice
from random import shuffle
#main function
def main ():
# seed random number generator
seed(1)
# prepare a sequence
sequence = [i + 1 for i in range(20)]
play = True;
... |
cc8581490008208f3351b31b8126f032d9ec03d4 | SaintClever/Python-and-Flask-Bootcamp-Create-Websites-using-Flask- | /_Python Crash Course/46. Functions in Python Part Two.py | 1,496 | 3.859375 | 4 | # max and min
print(max(2,3))
print(max([1,4,7,12,100]))
print(min([47,45,2,9,19]))
print('') #space
# enumerate
mylist = ['a','b','c']
index = 0
# WITHOUT Enumerate
for letter in mylist:
print(letter)
print('Is at index: {}'.format(index))
index = index + 1
# index += index # because this is set to ... |
d38efbe28fd3a5dc97a33567a76c5ce53ff932ae | Utkarsh731/HackerRank-Sorting | /closestNumber | 835 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the closestNumbers function below.
def closestNumbers(arr):
arr.sort()
min=arr[1]-arr[0]
output=[]
for i in range(0,len(arr)-1):
if abs(arr[i]-arr[i+1])==min:
min=abs(arr[i]-arr[i+1])
out... |
3374b004b004b419aef2c38833810339d4b047c7 | tails1434/Atcoder | /ABC/103/B.py | 233 | 3.765625 | 4 | def rotate(word , n):
return word[n:len(word)] + word[:n]
def main():
S = input()
T = input()
for i in range(len(S)):
if rotate(S,i) == T:
print('Yes')
exit()
print('No')
main() |
50364c8bf8283ef96d89b31cefc89b5c47cc763d | Mahip-Jain/Calculator | /Calculator.py | 6,928 | 4.09375 | 4 | import sys
only_numbers = "Sorry, you are only allowed to enter numbers"
maxquestions = 10
correct_ans = "You gave the correct answer"
incorrect_ans = "You gave the incorrect answer"
correct_ans_is = "\nThe Correct answer is"
enter_age = "Enter your age:"
enter_name = "Enter you name:"
welcome = "\nWelcome to MA... |
5767dcc4a73fd4449ce01992b1453754fa3a1805 | Athie9104/python-exersises | /matplot_exer.py | 872 | 3.984375 | 4 | # Example 1
import matplotlib.pyplot as plt
import numpy as np
x= np.array(["A", "B", "C", "D"])
y= np.array([3, 8, 1, 10])
plt.bar(x, y)
plt.show()
# Exercise 1
import matplotlib.pyplot as plt
cities=['East London', 'Cape Town', 'Kimberley', 'Durban']
rainfall= [140, 200, 120, 157]
x_pos = [i for i, _ ... |
1990b0540637244e17e13b704adf865abd5b0062 | GianlucaPal/Python_bible | /cinema.py | 741 | 4 | 4 | films = {
'Finding Dory':[3,5],
'Bourne':[18,5],
'Tarzan':[15,5],
'Ghost Busters':[12,5]
}
while True:
choice = input('What film would you like to watch?:').strip().title()
if choice in films:
age = int(input('How old are you?:').strip())
#check users ag... |
6eb8e01d2a9614b54a7ba03853221d1f218465e8 | matheus073/projetos-python | /CorridaDeBits/1013.py | 201 | 3.578125 | 4 | x = input()
x = x.split()
a,b,c,maior=int(x[0]),int(x[1]),int(x[2]),0
if a>=b and a>=c:
maior = a
elif b>=a and b>=c:
maior = b
else:
maior = c
print("%i eh o maior"%maior)
|
48a40b873d83ea325768e3ec700a3e3b83f204c7 | aritrasen12345/J.A.R.V.I.S | /jarvis.py | 6,280 | 3.53125 | 4 | # Jarvis Project
# pip install pyqt5
# pip install speechrecognition
# pip install pyttsx3
# pip install pyaudio
# pip install wikipedia
import speech_recognition as sr
import datetime
import wikipedia
import pyttsx3
import webbrowser
import random
import os
import requests
# Text to Speech
# Make a speaker who speak... |
a9f1eaba2ae7f9cabac1b50aeb3ddb1018879b97 | biqosik/CodeWars---solution | /Scramblies.py | 154 | 3.640625 | 4 | from collections import Counter
def scramble(s1, s2):
letters = Counter(s1)
word = Counter(s2)
return all(word[i] <= letters[i] for i in word) |
1358bac7b88a2b8b6e59daeeb257d55b691a872f | gbramley/PythonFileMover1Drill | /PythonFileMoverDrill2.py | 602 | 3.59375 | 4 | # Python version 2.7.13
# Author: Gavin Bramley
# Python Drill File Mover
# - Move the files from Folder A to Folder B.
# - Print out each file path that got moved onto the shell.
# - Upon viewing Folder A after the execution, the moved files should not be there.
import shutil
import os
def shutil():
... |
6484330eb4f4b5dd70ec9dcbc04de86ce3c47293 | heejung-choi/python | /03_slicing.py | 434 | 3.8125 | 4 | # slicing
sample_list = list(range(0,31))
print(sample_list)
print(sample_list[1:3])
# [|1,2,3,4]
# | 슬라이싱의 시작부분 (공간을 자른다.)
print(sample_list[10:-1])
# 끝에만 제외해서 하고 싶다면
print(sample_list[0:len(sample_list) :3])
#print(sample_list[0:31:3]) 동일
print (sample_list[::3])
print(sample_list[::-1])
# 뒤에서 부터 역순으로
print(sample... |
fb6232a85f6e2db186a7bbbd4929166d2efce939 | eltrai/algsContests | /GoogleCodeJam/2018/Qual/B-TroubleSort/B.py | 560 | 3.578125 | 4 | #!/usr/bin/env python3
def readint():
return int(input())
def readints():
return map(int, input().split())
def readline():
return str(input())
T = readint()
for case in range(T):
l = readint()
sequence = list(readints())
s1 = sorted(sequence[::2])
s2 = sorted(sequence[1::2])
result = "... |
644a26089daca4a3ff361f2f237678452b4ea2d3 | natalia1722/kpk2016 | /gun.py | 3,713 | 3.71875 | 4 | from tkinter import *
from random import choice, randint
screen_width = 400
screen_height = 300
timer_delay = 100
class Ball:
initial_number = 20
minimal_radius = 15
maximal_radius = 40
available_colors = ['green', 'blue', 'red']
def __init__(self):
"""
Cоздаёт шарик в случайном м... |
845576bf6602e7eadc1043aa70943988b678926e | Idreesqbal/PythonTutorial | /11AdvancedFileObjects.py | 1,036 | 4.3125 | 4 | with open('test.txt', 'r') as f: # it is always a good practice to open files like this
f = open('test.txt', 'r') # this also a way to work with files but the problem is
f.mode
f.close() # if u forget to put this at the end of file operation, the file may go to error
# to make sure our file handeling is in the safe ha... |
651765b84de3a64d185db80a9eb15a0d86e7e8a2 | WangYoudian/Algorithms | /LeetCode/Day8/HashTable.py | 1,792 | 4.0625 | 4 | # 构造哈希表的单个节点
class Node:
def __init__(self, key, value):
# self.hnext在Python中直接是列表的index体现
# self.hnext = None
self.data = (key, value)
# 构造哈希Map类,以及创建、插入、删除、查找方法
class ChainedHashMap:
def __init__(self, size):
self.size = size
self.table = [[] for i in range(size)]
def hash_func(self, key):... |
a3893337645cbb64ae22af994b7d4c1d893560c8 | valerpenko/Misha | /lists/checklist.py | 731 | 3.734375 | 4 | # арифм или геом?
l=[2,3,4,5,6]
if len(l)<3:
print("список недостаточной длины")
exit()
if l[1]-l[0]== l[2] - l[1]:
# проверка арифм прогрессии
d=l[1]-l[0]
i=2
while i+1<len(l):
if l[i+1] - l[i]!=d:
print("плохой список")
exit()
i+=1
print("арифм прогресси... |
1f177ee7de336a51efe40fb6f174bb307fd2a125 | dfbacon/holbertonschool-higher_level_programming | /0x06-python-test_driven_development/2-matrix_divided.py | 1,049 | 3.875 | 4 | #!/usr/bin/python3
'''
This is the "matrix_divided" module.
The matrix_divided module supplies one function, matrix_divided(matrix, div).
'''
def matrix_divided(matrix, div):
'''Return matrix with each value divided by @div
matrix: matrix being evaluated
div: divisor
'''
type_err = "matrix must... |
b138c7d646585c1ffa2c272c948861c27ed5dd9a | ruanpablom/PAP | /python/a8.py | 1,148 | 3.578125 | 4 | #!/usr/bin/env python
str = input('Digite o texto: ')
str2 = str.upper()
vogais = "AEIOU"
consoantes = "BCDFGHJKLMNPQRSTVWXYZ"
pontos = ".;?:.!"
n_vogais = 0.0
n_consoantes = 0.0
n_espacos = 0.0
n_pontos = 0.0
n_outros = 0.0
n_pa = 0.0
n_npa= 0.0
for i in range(0,len(str2)):
if str2[i] in vogais:
n_vogais... |
cb439d9b8f7d02218a130e3c9179ab81b6876edb | RichardFlynn/KattisProblems | /icpcawards.py | 137 | 3.859375 | 4 | input()
unis=[]
while len(unis)<12:
uni,team=input().split()
if uni not in unis:
unis.append(uni)
print(uni,team) |
8aa84d0aa56f0af66365d206b349f1fc5703924a | samuellsaraiva/1-Semestre | /l04e06mediaParesImpares.py | 2,279 | 4.25 | 4 | '''' 5. Construa o programa que calcule a média aritmética dos números pares.
O usuário fornecerá os valores de entrada que pode ser um número qualquer par ou
ímpar. A condição de saída será o número -1.
6. Complemente o programa anterior, acrescente o cálculo da média aritmética
dos números ímpares.
Teste 1:... |
7b66bac41ab8a98964873c7fa42ec73354461576 | goodmanj/ArduinoPythonSerialGUI | /serialslider.py | 856 | 3.625 | 4 | # Blink an Arduino's built-in LED for an amount of time determined by a GUI
# slider.
# Works in cooperation with serialslider.ino on the Arduino side.
# Serial comms library
import serial
# GUI library
import tkinter as tk
# Create a serial object. Change 'COM7' to match your computer's serial
# port, or use serial... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.