blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
9fbc99a4530e82bbeb3d7e3b378e840ad23a5662 | dcragusa/LeetCode | /100-199/140-149/144.py | 1,042 | 4.15625 | 4 | """
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1, None, 2, 3], Output: [1, 2, 3]
1
\
2
/
3
Example 2:
Input: root = [], Output: []
Example 3:
Input: root = [1], Output: [1]
Example 4:
Input: root = [1, 2], Output: [1, 2]
1... |
7e6d0cac3b718470e86944b508f19fda5343da79 | dcragusa/LeetCode | /1-99/40-49/43.py | 958 | 4.5625 | 5 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2,
also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3", Output: "6"
Example 2:
Input: num1 = "123", num2 = "456", Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1... |
58df73678cbd095fea3ed3c477f05cbe81eebf9d | dcragusa/LeetCode | /1-99/60-69/67.py | 528 | 4.1875 | 4 | """
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1", Output: "100"
Example 2:
Input: a = "1010", b = "1011", Output: "10101"
"""
"""
This is fairly trivial to do by converting the argume... |
c1b6ad529f2be7716814c1a16d4afd51c4aeeddb | dcragusa/LeetCode | /1-99/20-29/22.py | 1,998 | 4.3125 | 4 | """
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
['((()))', '(()())', '(())()', '()(())', '()()()']
"""
"""
We start with one pair of parentheses, which can only be (). For each additional pair, we add an open brac... |
27419cc9188daaf8cf78d2be008f21ce35b4d98c | dcragusa/LeetCode | /1-99/30-39/38.py | 1,668 | 4.28125 | 4 | """
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the ... |
57eabe477c0e06243108f259068acefbcb2c99ad | dcragusa/LeetCode | /1-99/50-59/52.py | 1,658 | 4.03125 | 4 | """
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4, Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown belo... |
a7642a80d728d5c5ed8b717e02f31973c13c997d | dcragusa/LeetCode | /1-99/90-99/92.py | 1,845 | 4.21875 | 4 | """
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4, Output: 1->4->3->2->5->NULL
"""
"""
We obtain the first node we are reversing (current), along with the node before that (reversal_head). Then we iterate
along the n... |
d95ed24919b2b9527136fb65e7772b1b85102bf9 | dcragusa/LeetCode | /100-199/110-119/117.py | 1,544 | 4.0625 | 4 | """
You are given a binary tree made up of the following nodes:
class Node:
val: int
left: Optional[Node]
right : Optional[Node]
next: Optional[Node]
Populate each next variable to point to its next right node. If there is no next right node, the next variable should
be set to None. Initially, all nex... |
1f30fbf51386a7dff9fdf22a6032fb0f554578e2 | dcragusa/LeetCode | /1-99/50-59/50.py | 1,934 | 4.1875 | 4 | """
Implement pow(x, n), which calculates x raised to the power n (x^n).
Example 1:
Input: 2.00000, 10, Output: 1024.00000
Example 2:
Input: 2.10000, 3, Output: 9.26100
Example 3:
Input: 2.00000, -2, Output: 0.25000, Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0, n is a 32-bit signed integer, wi... |
efd220cbddd2ceb70276d7bb01689937a14e5498 | dcragusa/LeetCode | /1-99/60-69/60.py | 2,200 | 3.90625 | 4 | """
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123", "132", "213", "231", "312", "321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive. Give... |
9e13c18fc3efdb57e2b52a035f8449b1288e312e | dcragusa/LeetCode | /1-99/70-79/71.py | 2,137 | 4.25 | 4 | """
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the
directory up a level. Note that the returned canonical path must always begin with a sl... |
2548e5d21024e4c45bd0d1f395d86c5af1e00cbf | dcragusa/LeetCode | /1-99/80-89/84.py | 1,416 | 4.09375 | 4 | """
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area
of the largest rectangle in the histogram.
#
# #
# #
# # -
- # # - -
- - # # - -
Example (as above):
Input: [2, 1, 5, 6, 2, 3], Output: 10
"""
"""
We iterate through the ba... |
dab242d55f23456b1fa394f0861dfadc202b94b3 | dcragusa/LeetCode | /1-99/80-89/85.py | 2,987 | 3.78125 | 4 | """
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']]
Output: 6
"""
"""
We base our solution on probl... |
5f5faa9ed086ea1741a7ac316ecc196fb6ebe763 | dcragusa/LeetCode | /100-199/120-129/129.py | 1,552 | 4.21875 | 4 | """
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree
represents a number. For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total
sum of all root-to-leaf numbers. A leaf node is a node with no children.
Example 1:
Input: r... |
e3383b02c91cba5f71a07ddd90035b437d72c340 | dcragusa/LeetCode | /200-299/220-229/221.py | 2,128 | 3.90625 | 4 | """
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example 1:
Input: matrix = [
['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']
], Output: 4
Example 2:
Input: matrix = [
... |
9e4a0ff134fd9ecdb4fec4b6e83ea5416e573450 | dcragusa/LeetCode | /1-99/10-19/15.py | 2,011 | 4 | 4 | """
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], the solution set is: [[-1, 0, 1], [-1, -1... |
a8ef29ef8afff666f0d9150edc74daf8da0a5a4a | dcragusa/LeetCode | /100-199/130-139/133.py | 1,570 | 3.9375 | 4 | """
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (list[Node]) of its neighbours.
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with
val == 1, th... |
2016b3800a0096045b21c9268298c6ebdd011527 | dcragusa/LeetCode | /1-99/40-49/49.py | 886 | 4.375 | 4 | """
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]
Note:
All inputs will be in lowercase. The order of your output does not matter.
"""
"""
Firstly we sort each string in the given array - this ... |
fd301edd92e99a60fdc5d54cb9ab409f8b49fe98 | dcragusa/LeetCode | /1-99/90-99/91.py | 1,638 | 4.09375 | 4 | """
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1, 'B' -> 2, ... 'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
Input: "12", Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L... |
16e4c858a7b237a54ff607882f629e2c9cbd0477 | Wyrd00/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 253 | 3.953125 | 4 | #!/usr/bin/python3
"""
Module with one function: append_write
"""
def append_write(filename="", text=""):
"""Append to a file and return number of char written"""
with open(filename, 'a', encoding="utf-8") as f:
return f.write(text)
|
9db50616bf05b52fd1f1f50c02f3d5ce00b99a11 | Wyrd00/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 330 | 3.5 | 4 | #!/usr/bin/python3
"""
Module: class MyList inherits from list
"""
class MyList(list):
"""
"""
def __init__(self):
"""Spec method __init__ that inherits from baseclass __init__"""
super().__init__()
def print_sorted(self):
"""Sort the list"""
print("{}".format(sorte... |
a1e0ff7b595fb4f7eb10a54204f58e21fddaa1b5 | Wyrd00/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 288 | 3.734375 | 4 | #!/usr/bin/python3
"""
Module with one function: number_of_lines
"""
def number_of_lines(filename=""):
"""return number of lines in filename"""
with open(filename, encoding="utf-8") as f:
counter = 0
for lines in f:
counter += 1
return counter
|
3d43da638d24970e31a9d0e3b072593501900cc6 | sakhter981/personalized-task-manager | /task_manager.py | 3,786 | 3.734375 | 4 | import datetime
#pssd means password, ussnm is username
def user_information(ussnm, pssd):
name = input("enter you name please: ")
address = input("enter your address please: ")
age = input("please its time to tell about your age: ")
ussnm_ = ussnm+" task.txt"
f = open(ussnm_, 'a')
f.write(pss... |
82d672bb6595816551dc873334c6d627aae70e31 | xuanjunlee/algorithm018 | /week01/189. 旋转数组.py | 1,007 | 3.8125 | 4 | from typing import List
# 方法1
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if length < 2:
return None
step = k % length
if step == 0:
... |
048c60fcf6ad655b38fc2be97821276de3561b3e | xuanjunlee/algorithm018 | /week03/236. 二叉树的最近公共祖先.py | 753 | 3.828125 | 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 lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def back_tracking(node):
... |
78f1fa1d9a9f4c04010c1c579d42c0e1c63b4d6d | xuanjunlee/algorithm018 | /week02/429. N叉树的层序遍历.py | 789 | 3.796875 | 4 | from queue import deque
from typing import List
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return lis... |
86146cad96331ec705831e29196263a93085d998 | Gowrishankarvv/Hacktoberfest21-letshack | /Python Programs/All Sort Functions.py | 1,146 | 3.96875 | 4 | # sort.py
"""All types of Sort"""
# Functions
def bbl(lst):
"""Bubble Sort"""
n = len(lst)
# Traverse through all array elements
for i in range(n - 1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in r... |
efdb099231e847d9da3cf288a40ed527b7dd6060 | Gowrishankarvv/Hacktoberfest21-letshack | /C Programs/reverseNo.py | 263 | 4.28125 | 4 | def ReverseNo():
num=int(input("Enter the number to reverse:"))
reversed_num=0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
ReverseNo()
|
8dc9c228a903d469af5ff383892c86e6230c6480 | deshearth/ling406 | /assignment2/bin/letterLangId.py | 4,305 | 3.515625 | 4 | # -*- coding: latin-1 -*-
'''
Author: Yifeng Chu (ychu26)
These are functions for letter bigram language identification
some details:
space and punctuations are preserved when training the model.
'''
import os
import numpy as np
import codecs
import collections
import pandas as pd
import itertools
def get_data()... |
10f01428067588c9f82a75c33d6ef7481fecfd43 | ajithkjajith/Hackerrank-Exercise | /warmup-challenge/2.counting_valleys.py | 455 | 3.59375 | 4 | #https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
# Complete the countingValleys function below.
def countingValleys(n, s):
s=s+"."
count=0 #for level
v=0
for i in range(n):
if s[i]=="... |
ea47eabaefd977eb46ef7b0be56887bf702c38fc | pydemia/python-lecture | /scripts/python_basic/4.classes.py | 3,411 | 4.09375 | 4 | # -*- coding: utf-8 -*-
#%% 클래스 정의하기
obj = "python"
type(obj)
obj.capitalize()
"python".capitalize()
class Membership:
pass
someone = Membership()
someone
class Membership:
def __init__(self, name):
self.name = name
def introduce(self):
print(self.name + " is a member")
# ... |
8cb38bbd3b0fb838944105ca029a831ab9669cba | maheesurya/Bomberman-CLI | /Wall.py | 748 | 3.96875 | 4 | #!/usr/bin/python
''' This file sets the walls on the board '''
class Walls:
''' This class contains 2 private methods and 2 dummy public methods '''
def __init__(self, board):
self.__wall(board)
@classmethod
def __wall(cls, board):
for col in range(2, board.height - 2):
if ... |
c634fdbf4a82856875ad1c49572a62b1fc4f062d | p05655123/CYUT_IM_Verification_Python | /Q26/Repeat.py | 231 | 3.78125 | 4 | # 撰寫一個程式,輸入一個字串(text),並將此字串的每個字元重複兩次後印出。
# (請上傳 Repeat.py)
s = input("輸入一字串:")
a = ""
for i in range(len(s)):
a = a +s[i]+s[i]
print(a) |
eb4f78274b0a5b85b4db82ef1d38a125f60fb29e | p05655123/CYUT_IM_Verification_Python | /Q47/Degree.py | 277 | 3.8125 | 4 | # 攝氏溫度( C )轉換為華氏溫度( F )的公式為: F=9/5*C+32 。請撰
# 寫一程式 ,利用命令列輸入一個整數攝氏溫度 , 則印出其華氏溫度。 ( 請
# 上傳 Degree.py 檔 )
C=int(input("輸入攝氏溫度:"))
F=9/5*C+32
print(F) |
ff35d0c3790430a7cfb074337de91a536cf6a3fe | p05655123/CYUT_IM_Verification_Python | /Q51/Dseries.py | 198 | 3.96875 | 4 | # 試撰寫一程式可求出多項式(1+2)+(2+4)+(3+6)+…+( n+2*n )的和。
# (請上傳Dseries.py)
n = int(input("輸入n:"))
a =0
for i in range(1,n+1):
a = a + (i+2*i)
print(a) |
abc7f6aa4190ae1a004f49fe712dc9d90234aeaf | p05655123/CYUT_IM_Verification_Python | /Q40/SumOdd.py | 222 | 3.65625 | 4 | # 請撰寫java程式執行從1 到n的迴圈,計算奇數的總和。
# (請上傳SumOdd.py)
n = int(input("輸入n:"))
a = 0
for i in range(1,n+1):
if (i % 2 != 0):
a = a + i
print(a) |
71995c48044375a3ab94666f675d35b7ed87bafb | p05655123/CYUT_IM_Verification_Python | /Q43/TimeTranslate.py | 320 | 3.875 | 4 | # 請設計一個 Python 程式,輸入一個只以秒為單位的整數(second),將其換
# 算為以時、分及秒為單位的時間(請上傳 TimeTranslate.py 檔)
S = int(input("輸入秒:"))
M = S // 60
S = S % 60
H = M // 60
M = M % 60
print( str(H) + "時" + str(M) + "分" + str(S) + "秒") |
72c54497a0ac7c499a7bc57a760a6d0722de872e | p05655123/CYUT_IM_Verification_Python | /Q5/CheckDate.py | 1,014 | 3.921875 | 4 | # 撰寫一個Java程式,輸入年(year)、月(month)、日(day)三個整數,檢查是否
# 為合法日期,如是則印出此日期(yyyy/mm/dd),否則印出"日期錯誤"。
# (請上傳CheckDate.py檔 )
def month(x):
return{
1: 31,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}.get(x,'error')
y = int(input... |
e5f850247aedff985b748609af017506271e778f | sunsunbobo/sun | /python_practice/python_oo/python_cat.py | 487 | 3.875 | 4 | ##定义类,首字母需要大写
class Cat:
#毛色,橘色,四条腿,
#会吃,会叫,会睡
##属性
color = "orange"
leg = 4
##方法,在类的方法中,是使用def关键字定义
##def定义的 在类外叫做函数function,在类内叫做method
def eat(self):
print("Cat can eat!")
def cry(self):
print("Cat can cry!")
def sleep(self):
print("Cat can sleep!")
c... |
85f87b52f9e9ea15d84ebf6e13692281151b3c27 | EphTron/blind-racers | /Utility.py | 793 | 3.609375 | 4 | import pygame
class Vec2:
def __init__(self,x,y):
self.x = x
self.y = y
class Vec3:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
def rot_center(image, angle):
"""rotate an image while keeping its center and size"""
orig_rect = image.get_rect()
... |
e0400eca05cf36dd5a3ea33a53f2e45627a18d4e | sunt727/Data-Analysis-by-Python | /PracticeFinal/studyCode.py | 6,100 | 3.671875 | 4 | import numpy, sklearn.linear_model
def minkowskiDist(v1, v2, p):
"""Assumes v1 and v2 are equal-length arrays of numbers
Returns Minkowski distance of order p between v1 and v2"""
dist = 0.0
for i in range(len(v1)):
dist += abs(v1[i] - v2[i])**p
return dist**(1/p)
def accuracy(truePos, falsePos, trueNeg, fa... |
c2acde4bc2c30ed39409e9336b393b96f484b56e | ashpriyam/MyCodingExercise | /MyCodingExercise.py | 122 | 3.59375 | 4 | def numbr():
print("Input any numbers:")
n = input()
num = list(n)
for i in n:
print(i)
numbr()
|
11be85d9f5178224005966f7e9b0c2625b1e4b87 | dargen3/matematika-a-programovani | /1-lesson/graphic/ulam_spiral_natural_numbers.py | 1,139 | 3.890625 | 4 | from PIL import Image
def should_print(picture, number, x, y, natural_number): # decide if pixel x, y should be printed
if number % natural_number == 0:
picture.putpixel((x, y), (255, 255, 255))
return number + 1
def ulam_spiral_natural_number(natural_number): # show and save spiral of natural num... |
881e3c309d3efcbe76537c5bea6454795674d692 | dargen3/matematika-a-programovani | /1-lesson/games_with_number/collatz_sequence.py | 573 | 4.21875 | 4 | def collatz_sequence(n): # return number of steps of collatz sequence for n
count = 0
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = n * 3 + 1
count += 1
return count
def largest_sequence(max): # print number from interval (2, max) which have highest num... |
ba44fb290368744b074b4bbe4c7c8ed5307cbe90 | dargen3/matematika-a-programovani | /1-lesson/graphic/svg_turtle.py | 2,230 | 3.640625 | 4 | import math
from math import acos, degrees
class SvgTurtle:
"""
SvgTrutle is modul, which has similar behavior like normal turtle graphic in python2/3.
Module is still in develop.
"""
def __init__(self, x, y):
self.x = x
self.y = y
self.heading = 0.0
self.lines = []... |
6c2d06066c0e0fcf57ed491e3638a3d56bb92d07 | Swarnabh3131/sipPython | /sip/sipF05_DFsortcreate.py | 413 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
#https://thispointer.com/pandas-sort-rows-or-columns-in-dataframe-based-on-values-using-dataframe-sort_values/
#df creation
matrix = [(222, 16, 23),(333, 31, 11)(444, 34, 11), ]
matrix
# Create a DataFrame object of 3X3 Matrix
dfObj = pd.DataFrame(matrix, index=list('abc')... |
25104b11d36cae7f719ecbae92d19a2941359dba | lazear/ip2api | /ip2api/utils.py | 310 | 3.59375 | 4 | """Utility methods."""
def equal_dicts(a, b, ignore_keys):
"""Compare two dicts, withholding a set of keys.
From: http://stackoverflow.com/a/10480904/383744
"""
ka = set(a).difference(ignore_keys)
kb = set(b).difference(ignore_keys)
return ka == kb and all(a[k] == b[k] for k in ka)
|
d6f761599af38366876a6399da076afaa68aa239 | rbo93/mi_primer_programa | /Ejercicios de NATE/clases_naturaleza.py | 366 | 3.59375 | 4 |
class Dog:
def __init__(self, name, specie, age):
self.name = name
self.specie = specie
self.age = age
def speak(self):
print("Guau guau")
my_dog1 = Dog("doggy", "Bulldog", 13)
my_dog2 = Dog("Goldencito", "Golden", 10)
my_dog3 = Dog("nigga", "Labrador", 5)
print(my_dog1.spe... |
713b47b62fd9c0e12314732535b4779c58b2b49b | rbo93/mi_primer_programa | /Ejercicios Realizados/Practica de listas/listas_format_ejercicio_tres.py | 578 | 3.875 | 4 | """
Ejercicio 3
Crear un programa que cambia las vocales por su numero de aparición. Por ejemplo la string “aurora boreal” se convertiría en “12r3r4 b5r67l”
"""
string_usuario = str(input("Ingrese un texto, le reemplazaremos por I la vocales: "))
vocales = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U"]
busqueda_v... |
2b04861d0aeea5517627006cb9bcdb5c7941f15b | rbo93/mi_primer_programa | /Ejercicios Realizados/Otros/adivinanza_max_intentos.py | 1,371 | 3.921875 | 4 | print("Adivina el numero del uno al 10 que estoy pensando...")
number_to_guess = 8
intentos = 1
user_number = int(input("Dime un numero: "))
if number_to_guess == user_number :
intentos = "primer intento"
print("En hora buena has ganado en el {}".format(intentos))
else:
print("Has perdido")
intentos +=1... |
14c56338fc1b200cde474333ea36c8209a137358 | rbo93/mi_primer_programa | /Ejercicios de NATE/combate_pokemon.py | 1,857 | 3.90625 | 4 | pokemon_elegido = input("Contra que pokemon quieres combatir? (Squirtle / Charmander / Bulbasaur): ").lower()
while pokemon_elegido != "squirtle" and pokemon_elegido != "charmander" and pokemon_elegido != "bulbasaur":
print("Elige una opcion correcta")
pokemon_elegido = input("Contra que pokemon quieres combati... |
157ed724d8bfc25737612c57e228cc8408e85093 | rbo93/mi_primer_programa | /Ejercicios Realizados/Funciones/funciones_ejercicio_tres.py | 552 | 3.90625 | 4 | """
Escribe una funcion que reciba una lista de numeros y te devuelva otra pero solo con los pares
devolver_pares([1,2,3,4,5,6])
Output [2, 4, 6]
"""
# Functions
def devolver_pares(lista):
new_list = []
for index in range(len(lista)):
if lista[index] % 2 == 0:
new_list.append(lista[inde... |
e57f26d13ca7d5935e21c24a54b0fa29f5fb64bb | sewayan/Study_Python | /ex10.py | 755 | 3.6875 | 4 | #\t to create a tab (space)from the start of line
tabby_cat = "\tI'am tabbed in."
#\n new line character, "on a line" in next line
persian_cat = "I'm split\non a line."
# displays-> I'm \ a \ cat
backslash_cat = "I'm \\ a \\ cat."
# 'Boooyah' displayed below, after line-break
realest = "100 %\nBoooyah"
... |
d69a50282db0c5b538fe44e07edf1ccab179ed83 | sewayan/Study_Python | /ex15.py | 874 | 4.09375 | 4 |
from sys import argv
# execute script + filename
# python ex15.py ex15_sample.txt
script, filename = argv
#open file "txt" which has -> (name)
txt = open(filename)
#txt = raw_input("> ") -> User input req.; error when command 'txt.read'
# msg + content of txt file
print "Here's your file %r:" % filename
# "tx... |
fd721bc36a9bce2cea562e277cb8ba50a2d155d1 | sewayan/Study_Python | /ex25.py | 1,620 | 4.28125 | 4 | # function will be imported & executed in python
# """ Insert comment text """ -> 'documentation comment'
#if code is run in interpreter, documentation comment = help txt
def break_words(stuff):
"""This func will break up words for us."""
"""put a space between the sperators -> '' """
words = stuff.split(' ')
ret... |
4a9f16722f329fbb86d7caa7e20a43dcf5d12075 | PeterSlakhorst/Django_portfolio1 | /start.py | 442 | 3.59375 | 4 | import math
import pandas
import numpy as np
class Point():
def __init__(self, input_x, input_y):
self.x = input_x
self.y = input_y
# comment toegevoegd in commit 2
# comment toegevoegd in github commit 3
print("De waarde van pi: ", math.pi)
print("De waarde van e: ", math.e)
math.sin
s = se... |
502ad994f514b619ff3794732a2d914ea4324763 | rotembar6/Voice-Recognition | /Client/Recorder.py | 1,955 | 3.578125 | 4 | import pyaudio
import wave
import os
"""
Using pyaudio library in oreder to record the user say his password
and save it as a wav file.
CHUNK - how many samples are in a frame that stream will be read.
Format - Captures the audio in hexadecimal format.
Channels - Stereo
Rate - Sample rate is the number of sa... |
571893139c40e5f6ed9e82cc8925c6469af8cd4f | mhebdzynski/Rock-Paper-Scissors | /game.py | 3,711 | 3.9375 | 4 | import random as rand
class Player:
score = 0
name = None
move = None
def __init__(self, name, score):
self.name = name
self.score = int(score)
print("Hello,", self.name)
def set_move(self, move):
self.move = move
def get_move(self):
return self.m... |
f475e180166f297b5d6ef542b2d6f4c6f0ea126f | w0464750/PaintShop | /Lab1-PaintShop.py | 699 | 3.71875 | 4 | import math
def main():
# YOUR CODE STARTS HERE, each line must be indented (one tab)
#Taking input from user
firstWallWidth = int(input("How many feet wide is your first wall?: "))
secondWallWidth = int(input("How many feet wide is your second wall?: "))
wallHeight = int(input("How many feet tall is your... |
b9aa29a971fcda956d7544ff022ba955b1a3a866 | Igr1k001/Programming | /Practice/07/Python/07 PY/07 PY/_07_PY.py | 2,130 | 4.125 | 4 | import math
print('Введите число 1 или 2:')
print('1-ввод параметров треугольника через длины сторон.')
print('2-ввод параметров через координаты вершин или другое целое число по модулю.')
d = float(input())
while d != 1 and d != 2:
print('Ошибочный ввод')
print('Введите число 1 или 2:')
print('1-ввод пара... |
0f5a1b279c9d3ce25fe5a6f6176b155df3e45c78 | aluu4445/Automate-The-Boring-Stuff | /inventorycount.py | 336 | 3.890625 | 4 |
inventory={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(stuff):
print('Inventory:')
itemcount = 0
for k, v in stuff.items():
print(str(v) +' '+ k)
itemcount=itemcount + v
print ("Total number of items: " + str(itemcount))
displayInven... |
45ddd16506befea1a06a2b46f73abd88461a4a1f | shiv-konar/Python-GUI-Development | /FocusingandDisablingWidgets.py | 1,211 | 4.3125 | 4 | import tkinter as tk
from tkinter import ttk # For creating themed widgets
win = tk.Tk() # Create an instance of the Tk class
win.title("Python GUI") # Set the title of the window
win.resizable(0, 0) # Disable resizing the GUI
aLabel = ttk.Label(win, text='Enter a name:') # Create a named Label instance to be u... |
fd827a17fcf2a873a113ba0741cbdc2c89617593 | BryceT516/tech-academy-python | /Item63/PythonDrillItem63.py | 781 | 3.546875 | 4 | import shutil
import os
def moveFiles(folder):
if(folder == "a"):
source=os.listdir(os.path.abspath("./Folder A/"))
destination = os.path.abspath("./Folder B/")
folder = "./Folder A/"
else:
source=os.listdir(os.path.abspath("./Folder B/"))
destination = os.path.abspath... |
aabf8d8565bb69e4d19b45959025f649bc70390d | mgokayb/beginnerpythonprojects | /rockpaperscissors.py | 985 | 3.796875 | 4 | import random
point = 0
while True:
list = [
"rock",
"paper",
"scissors",
]
player = input("Hi Rock-Paper-Scissors's game. You have " + str(point) + " point. Start choosing one! >> ")
i = random.randint(0, 2)
if player.lower() == "rock" and list[i] == "scissors":
pr... |
0b684a9b018e7d3600ae9bdd711b8b80d2c6f44f | Jonathan-aguilar/AlgoritmosSistemas | /ago-dic-2019/Jonathan Aguilar/tarea4.py | 337 | 3.890625 | 4 | def check(string, l, r, flag):
if l>r:
return flag
else:
print(string[l],string[r])
if string[l]==string[r]:
flag=True
else:
return False
return check(string,l+1,r-1,flag)
if __name__ == '__main__':
string=input("Dame el nombre: ")
if check(string,0,len(string)-1,False):
print("palindromo")
else:... |
76a03759a267d8ec4bc4a5a2b70dada2c10fd4cb | rickyanderson/Introduction-to-programming | /TOLL 2.0.2.py | 4,786 | 4.28125 | 4 | class Car: #class car
def __init__(self,car): #initiate the class
self.c = car
def getcar (self):#make a function called getcar
return self.c #return to self.car
class Bus: #class Bus
def __init__(self,bus): #initiate the class
self.bus = bus
def getbus(self): ... |
a3df3a436519866dedd9150206ed3d5a9accf5b9 | isaeme23/complexLibrary | /ComplexTest.py | 1,156 | 3.640625 | 4 | import unittest
import Calculator as calc
class TestComplexCalculator(unittest.TestCase):
def test_sumar(self):
c1, c2 = (-6, 8), (10, -7)
self.assertEqual(calc.sumar(c1, c2), (4,1))
def test_restar(self):
c1, c2 = (-6, 8), (10, -7)
self.assertEqual(calc.restar(c1, c2), (-16,1... |
230f87638865b1be9dba969257f7cb97792e10ff | psravanthi/dsp | /math/matrix_algebra.py | 2,775 | 3.578125 | 4 | # Matrix Algebra
import numpy as np
import math
# Addition/Substraction
def add_sub(a,b,f):
if a.shape != b.shape:
return "Matrices should be of the same order"
else:
row = a.shape[0]
col = a.shape[1]
result = np.zeros((row,col))
for i in range(row):
for j in range(col):
if f == 'a':
result[i... |
14e1d23da800aadc8b16c199c77246f971461964 | Acturus2020/python_lesson_5 | /lesson3.py | 1,801 | 3.671875 | 4 | import random
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
if __name__ == '__main__':
print_hi('PyCharm')
popular_auto = [
'Audi',
'Honda',
'Suzuki',
'Nissan',
'Aston Martin',
... |
155c1b1e0fc521c3940f254975c58764777bc127 | ankit1997/Computer-Graphics-Programs-in-Python | /dda_line.py | 999 | 4.28125 | 4 | import turtle
print("DDA line drawing algorithm implementation.")
x1 = int(input("Enter x1: "))
y1 = int(input("Enter y1: "))
x2 = int(input("Enter x2: "))
y2 = int(input("Enter y2: "))
window = turtle.Screen()
pointer = turtle.Turtle()
pointer.shape("arrow")
pointer.hideturtle()
pointer.pensize(4)
def setPixel(x, ... |
5d1ffec6bcee9bedbccf214e2bd79c8eab7eb0a0 | Sayalikajale/python | /unions.py | 939 | 4.15625 | 4 | def union1(l1, l2):
l3 = []
for element in l1:
if element not in l3:
print element, 'element'
count = 0
a = l1.count(element)
print a, 'value of a'
b = l2.count(element)
print b, 'value of b'
if a >= b:
count1 = a
else:
count1 = b
print count1, 'count'
while count1 > 0:
l3.... |
63fe7ccfa5b0b00132f0031383b5fb31623c161f | sukhadagholba/Data-Structures | /binary_search_tree/binary_search_tree.py | 977 | 3.796875 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value >= self.value:
if not self.right:
self.right=BinarySearchTree(value)
else:
self.righ... |
6c5013559282bd2e7b562b4f0a8dd0a43f748e44 | RajatPrakash/Sudoku-Solver | /Sudoku_Solver.py | 1,568 | 3.859375 | 4 | board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
# Checking... |
a4f91fb29b257566e9ca0b55f916d5c597382891 | yehia1/Deep-learning | /Minist_Cnn.py | 1,453 | 3.5625 | 4 | import numpy as np
import tensorflow as tf
from keras.utils import np_utils
#getting the minist data sett from tensor flow
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
#scalling the data so it will be easier to train
x_train= x_train.reshape(x_train.shape[0],28,28,1)/255
x_test= x_test.re... |
9fcd4f79acafbac611b311b904bd5027db1b4337 | Anastasia233/Python | /Water consumption calculator.py | 75 | 3.765625 | 4 | x = int(input("Enter number of water:"))
print("Number of bottles: ", x*12) |
0a34a48cbde34be9e69d6f4ee7ae783ac242e826 | renuka-fernando/project-euler-answers | /59.py | 1,843 | 3.765625 | 4 | F = open("59(Enscryption).txt")
Enscr = F.readline().split(",")
F.close()
LowerLetters = range(97, 123) #Here 97 = 'a',122 = 'z'
As, Bs, Cs = [], [], [] #Password = ABC
#common letter in 32 - 122
Count = len(Enscr)
Break = False
def Decrypt(Place, Lst):
key = 97
while key <= 122:
for letter in range(... |
b4bf013cdea0695ec6601c733499db37f6cd9120 | renuka-fernando/project-euler-answers | /10.py | 304 | 3.890625 | 4 | Sum = 0
Num = 2
PrimeList = []
def IsPrime(Num):
return not any(Num % i == 0 for i in PrimeList)
while Num < 2000000:
if IsPrime(Num):
PrimeList.append(Num)
Sum += Num
if Num % 20000 == 0:
print 'Plz wait ' + str(Num/20000) + '% complete...'
Num += 1
print Sum
|
65a6f48b2ee89e0f5f9c48e37719746cf769e774 | renuka-fernando/project-euler-answers | /4.py | 480 | 3.71875 | 4 | def IsPalindromicNumber(Num):
Digits = []
for digit in str(Num):
Digits.append(digit)
DigitsRev = Digits[:]
DigitsRev.reverse()
return Digits == DigitsRev
#Main
Factor1 = 999
Factor2 = 999
NumLst = []
while Factor1 >= 900:
Factor2 = 999
while Factor2 >= 900:
NumLst.append(... |
95c9a20b049d12660bc7e5650efb1e07bab00c49 | gosia-su/SoftwareTests | /Intro.py | 485 | 3.828125 | 4 | # def div(a, b):
# return (a + b) ** 2
#
#
# assert div(3, 6) == 81, 'FAIL'
# print('PASS')
# assert div(2, -6) == 16, 'FAIL'
# print('PASS')
# assert div(0, 7) == 49, 'FAIL'
# print('PASS')
def factorial(n):
fact_list = 1
for i in range(1, n+1):
fact_list *= i
return fact_list
n = int(input... |
b315920c07eed5a3baa4c35ce5d583dac0e1ac23 | Chetali-3/python-coding-bootcamp | /session-9/Strings/hello.py | 450 | 4.34375 | 4 | #Types of functions
"""
# finding out length
name = input("Enter your name")
length = len(name)
print(length)
"""
"""
# capitalising
name = input("Enter your name")
new_name = name.capitalize()
print(new_name)
"""
"""
#finding out a letter
name = input("Enter your name")
new_name = name.find(input("enter the word you ... |
e246998c649d117901a20d48bfef510e303f2789 | roschart/pruebas | /apps/magic/testDeck.py | 1,775 | 3.53125 | 4 | # -*- coding: latin-1 -*-
from deck import Deck
def deckContiene(deck,deckDefLista):
''' Devuelve true if si el deck cumple tener las cartas de la lista
se puede pasar una definicion o una lista de definiciones, si es una lista
devolvera true si se cumple alguna de ellas
>>> d=Deck({'M':30,'C':30})
>>> deckContie... |
3b769d11f55500814daf7dabc8c8408cb1b5028d | vavu786/Message_Encryption_and_Decryption_Project | /Message_encryptor_and_decryptor.py | 4,866 | 4.34375 | 4 | """
input.txt is formatted as follows:
Decryption:
d or D (char)
Dimension of encoding matrix (int)
Values of encoding matrix (space-separated ints)
Number of letters in message (int)
Values of the encrypted message (space-separated ints)
Encryption:
e or E (char)
Dimension of encoding matri... |
d4231c071d05eb58cc98c88d91b8c511d1e986cf | bajpay/task_manager | /toDoListProjectV.1.py | 3,596 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[35]:
#To Do List Project
#Create GUI Elements
import tkinter as tk
import random
import datetime
#Root Window
root = tk.Tk()
#Change Title
root.title("Arnav's To Do List")
#Change window size
root.geometry("200x500")
#Create an empty list
tasks = []
#For testing purp... |
888a7700d765ce437655b746499e374a053b24b5 | ChrisMacLean/lpthw3 | /ex17.py | 931 | 3.796875 | 4 | from sys import argv
from os.path import exists
# so this time we're giving it script name but also providing from and to file variables
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# we could do these on 1 line right? indata = open(from_file).read()?
# in_file = open(from_file)
... |
eab7b1d654de2c0f148318dd34182ab7c4abd354 | ChrisMacLean/lpthw3 | /ex13.py | 481 | 3.65625 | 4 | # argv is argument variable
from sys import argv
# read the wyss section for how to run this
# this unpacks argv and assigns it to the 4 variables below
# number of arguments has to equal number of variables defined here
script, first, second, third = argv
print("The script is called:", script)
print("Your first varia... |
d49de4c1dd488284633fc4246fc228774f07248e | sonqdinh/WB_week1 | /Week1/detectCapitalUse.py | 649 | 3.578125 | 4 | class Solution:
def detectCapitalUse(self, word: str) -> bool:
if not word:
return True
# First letter is capital:
if ord('A') <= ord(word[0]) <= ord('Z'):
capital = normal = False
for ch in word[1:]:
if ord('A') <= ord(ch) <= ord(... |
0aa706848c586bec2fe702bba63ba4865ad5dd00 | sonqdinh/WB_week1 | /Week2/validSudoku.py | 983 | 3.703125 | 4 | class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
squares = [set() for _ in range(9)]
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
# Check column
if ... |
9ea5dee621ccdce9117e4c3cb15b9be5a414c876 | mallikarjuna-sharma/PythonWeb | /MyPy.py | 1,888 | 4.15625 | 4 | import sqlite3
from EmployeeClass import Employee
conn = sqlite3.connect('MyDataBase.db')
cur = conn.cursor()
# cur.execute("""CREATE TABLE employees (
# first text,
# last text,
# pay integer )""")
def insert(emp):
with conn:
cur.execute("INSERT IN... |
02ec9a89ff54114e2de1400de75bdd6d9c3f8a8e | AdamDawidKrol/algorithms-python | /quicksort.py | 573 | 3.640625 | 4 | def partition(A, p, r):
x = A[r]
i = p - 1
for j in range(p, r):
if A[j] <= x:
i = i + 1
temp = A[i]
A[i] = A[j]
A[j] = temp
temp = A[i + 1]
A[i + 1] = A[r]
A[r] = temp
return i + 1, A
def quicksort(A, p, r):
(q, A) = partition(A,... |
59bf443228d622dfe3cab82e3d1498ffbfba5dd9 | moses-mugoya/Interview-Practical | /second_largest_number.py | 802 | 4.1875 | 4 | def find_second_largest():
n = input("Enter the value of n: ")
if (int(n) > 10 or int(n) < 2):
print("The value of n should be between 2 and 10")
return
else:
numbers = input("Enter {} numbers separated by a space: ".format(n))
num_list = numbers.split(" ")
num_list =... |
c2008d433cc36b1df7026e68c5f16234825e9adf | martinezmatias0902/Python-Practices | /Python/modulos.py | 355 | 3.578125 | 4 | #Hay 3 tipos de modulos
#los que escribimos nosotros mismos
#los que podemos descargar
#los propios de Python (googlear Python modules index)
#Vamos a usar un modulo de Python, supongamos que tenemos que crear una
#aplicacion que muestre la fecha actual
import datetime
print(datetime)
print(datetime.date.today())
pr... |
28d6aa1032cefd362da7b2091bddc35714c34e46 | sikorskaewelina/Programowanie_w_data_science_podstawy | /zad12.py | 574 | 4.0625 | 4 | """
12. Utworzyć skrypt z interfejsem tekstowym obliczający n-ty element ciągu Fibonacciego
- wykonać zadanie iteracyjnie i rekurencyjnie
"""
def fib_iteracyjny(x):
pwyrazy = (0, 1)
a, b = pwyrazy
while x > 1:
a, b = b, a + b
x -= 1
return x
x = int(input('Podaj, który element ci... |
5a74967ca5c861160eeb36e0462082e584d41b5e | sikorskaewelina/Programowanie_w_data_science_podstawy | /zad13.py | 447 | 3.953125 | 4 | """
13. Utworzyć skrypt z interfejsem tekstowym obliczający symbol Newtona n po k.
Utworzyć funkcję, która będzie wywoływać inną funkcję
"""
def newton(n, k):
x = 1
for i in range(1, k + 1):
x = x * (n - i + 1) / i
return x
n = int(input('Podaj liczbę n: '))
k = int(input('Podaj liczbę k: '))
i... |
f7f90cfa013f7acc1568b26f803857cd32cfe7da | voltwu/Python-Database-Sqlite3-Encapsulation | /sqlitedbtest.py | 1,002 | 3.546875 | 4 | import unittest
from sqlitedb import sqlitedb
class MyTestCase(unittest.TestCase):
def test_sqllitedb(self):
#create
cur = sqlitedb.execute("create table if not exists Person(name,age)")
# Output: -1
print(cur.rowcount)
#insert
cur = sqlitedb.execute("ins... |
940d4e0d73404bbad66be1ded90f8d710b270d99 | goodjack/example_code | /aiobot/utils/timezone.py | 3,257 | 3.546875 | 4 | import functools
import pytz
from datetime import datetime
from settings.settings import TIME_ZONE
# utc = pytz.utc
tz_msk = pytz.timezone('Europe/Moscow')
tz_utc = pytz.utc
'''
Взято из Django
TIME_ZONE = 'Europe/Moscow'
naive - Относительное время - нет информации о временной зоне (timezone)
aware - Абсолютное... |
e21b155e369fe8ddb3fe22018091d87b8618d9d7 | 4nything/Proyectos-Python | /dados.py | 2,721 | 3.640625 | 4 | # Importamos la libreria de seleccion al azar
import random
import msvcrt
# Definimos la funcion que hara la mezcla de los dados
def tirarDados():
print("Tirando dados...") # Impresion para atractivo visual
valores = [1, 2, 3, 4, 5, 6] # Definimos los valores que poseen los dados
dado1 = random.choice(valo... |
95c8eb07986a1b9a9c5f6ff7c12f6d4bcc6a5e5a | anmol/algorithm_python | /random_problems/cube_root.py | 539 | 3.703125 | 4 | '''
Created on Jun 22, 2018
@author: agautam1
'''
def calculate_diff(n, mid_cube):
if n > mid_cube:
return n - mid_cube
else:
return mid_cube - n
def cube_root(n, e):
start = 0
end = n
while(True):
mid = (start + end) / 2.0
mid_cube = mid * mid * mid
... |
0ffba222b406c6d3bcf0e2d50c3879e6de8f2f54 | anmol/algorithm_python | /random_problems/matrix_path.py | 1,380 | 3.5625 | 4 | def FormatArr(strArr):
for i in range(len(strArr)):
strArr[i] = list(strArr[i])
return strArr
def CheckPath(strArr):
#print strArr
print id(strArr)
m = len(strArr)
n = len(strArr[0])
strArr[0][0] = '2'
for i in range(1, n):
if strArr[0][i] != '0':
strArr[0]... |
06be15bbdc3c50376550b8f9b3b049da1e5e5849 | anmol/algorithm_python | /leetcode/arrays/rotate_k_elems.py | 411 | 4.125 | 4 | #!/usr/bin/env python3
# reverse array subset in place
def rev(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def rotate(nums, k):
k %= len(nums)
rev(nums, 0, len(nums) - 1)
rev(nums, 0, k - 1)
rev(nums, k, len(nums) -... |
681c43fe57b36e028dbf4cb231acd076186bd207 | anmol/algorithm_python | /random_problems/counting_mins.py | 1,678 | 4.125 | 4 | """
count mins between the string having a
time interval
"""
def count_mins(s):
# split two times
t1_raw = s.split('-')[0]
t2_raw = s.split('-')[1]
t1_12 = get_time_tuple(t1_raw)
t2_12 = get_time_tuple(t2_raw)
t1 = convert24(t1_12)
t2 = convert24(t2_12)
# if t2[0] >= t1[0] and t2[1] >... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.