blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
f3b79544427b9e406d9c97cc8a416b3be7c1a9b7 | theelk801/pydev-psets | /pset_lists/list_ops/solutions/p2.py | 630 | 3.59375 | 4 | """
Core Statistics Calculations - SOLUTION
"""
import statistics
nums = [2, 19, 20, 12, 6, 24, 8, 30, 12, 25]
my_sum = sum(nums)
my_min = min(nums)
my_max = max(nums)
my_range = max(nums) - min(nums)
my_mean = my_sum / len(nums)
my_median = statistics.median_grouped(nums)
my_mode = statistics.mode(nums)
my_variance... |
278cfd9000b17eaf249eebad07b11d078e934c35 | theelk801/pydev-psets | /pset_classes/bank_accounts/solutions/p2.py | 1,377 | 4.21875 | 4 | """
Bank Accounts II - Deposit Money
"""
# Write and call a method "deposit()" that allows you to deposit money into the instance of Account. It should update the current account balance, record the transaction in an attribute called "transactions", and prints out a deposit confirmation message.
# Note 1: You can for... |
7a17b30d30593252e7068b88bb1703784a31b0a4 | josephrecord/ProjEuler | /p15.py | 151 | 3.59375 | 4 | # n by n grid
def countroutes(n):
result = 1
for i in range(1,n+1):
result = result * (n+i)/i
return result
print(countroutes(20)) |
8845f5e35563adadde8dcdd856416d4107063a35 | josephrecord/ProjEuler | /p27.py | 532 | 3.75 | 4 | import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
max_primes = 0
for a in range(-1000, 1000):
for b in range(-1000, 1000):
prime_count = 0
for n in range(0, 42):
y = n**2 + a*n + b
#p... |
5a7359a28180c3429abb82e0775340ea69d28ad3 | josephrecord/ProjEuler | /p12.py | 434 | 3.546875 | 4 | import math
def tri(n):
t = 0
while n > 0:
t = t + n
n = n - 1
return t
def numfactors(n):
upperlim = int(math.sqrt(n)) + 1
result = set()
for i in range(1, upperlim):
div, mod = divmod(n, i)
if mod == 0:
result |= {i, div}
return len(result)
n... |
b18f648a586c1bd45d3bc54c3795db3ea03b95f3 | KulkarniKaustubh/topspin-tracker | /server/csv_utils.py | 2,208 | 3.609375 | 4 | import pandas as pd
from scipy.signal import savgol_filter
import os
import cv2
class CSV:
"""
A class to incorporate common csv functionality used throughout the project
Attributes
----------
filename: str
name of the CSV file
columns: list
columns in the CSV file
df : pan... |
9d9d044b0bff764cc3a8f4e31634f1138f05e2b4 | Arin-py07/Python-Programms | /Problem-11.py | 888 | 4.1875 | 4 | Python Program to Check if a Number is Positive, Negative or 0
Source Code: Using if...elif...else
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Here, we have used the if...elif...else statement. We can do the same t... |
5b428c1de936255d8a787f6939528031fa3ddc9b | Arin-py07/Python-Programms | /Problem-03.py | 1,464 | 4.5 | 4 | Python Program to Find the Square Root
Example: For positive numbers
# Python Program to calculate the square root
# Note: change this value for a different result
num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(nu... |
e6dead53cca8e5bef774435616a2dd02452e6389 | ejoconnell97/Coding-Exercises | /test2.py | 1,671 | 4.15625 | 4 | def test_2(A):
# write your code in Python 3.6
'''
Loop through S once, saving each value to a new_password
When a numerical character is hit, or end of S, check the new_password
to make sure it has at least one uppercase letter
- Yes, return it
- No, reset string to null and con... |
79a19ad4d3feccee04266f38078bd95d11db1772 | smiks/database | /Example.py | 942 | 3.65625 | 4 | from Database import Database as DB
mydb = DB("example")
columns = ["first_name", "last_name", "age"]
data = [
{"first_name": "John1", "last_name": "Doe1", "age": 25},
{"first_name": "John2", "last_name": "Doe2", "age": 27},
{"first_name": "John3", "last_name": "Doe3", "age": 20}
]
mydb.load()
if mydb.s... |
b195a2560e429e3504ab63c1b4814f3dc68f6e81 | Ponkiruthika112/codeset5 | /c4.py | 83 | 3.75 | 4 | #this is my code
n=int(input())
if n>=1 and n<10:
print("yes")
else:
print("no")
|
1f76ae2510a09983ea87a263e3b00ad58e3f4805 | ShakibUddin/Scrapper-Web-Crawler-Projects | /WHO_Corona.py | 725 | 3.515625 | 4 | from urllib.error import HTTPError
from urllib.request import urlopen
from bs4 import BeautifulSoup
def get_data(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bsobj = BeautifulSoup(html,"html.parser")
data=bsobj.find_all("p")#find_all() returns a li... |
e2b9b64fbe846b2ac9b692d1a1348ec735b7d62f | mtbutler93/pythonprojects | /cars_sort.py | 412 | 3.953125 | 4 | # playing with lists, sort list
# mtb 02.27.2018
cars =['bmw','audi','porsche','vw','honda']
print (cars)
cars.sort()
print (cars)
cars.sort(reverse=True)
print (cars)
cars2 =['bmw','audi','toyota','subaru']
print (cars2)
print('Here is the original list:')
print(cars2)
print('\nHere is the sorted ... |
70186cf6c6ea222e3ef8f55df72e0be9c56f98c5 | durcak-jindrich/leet_code | /notebooks/leet/data_structures/Node.py | 315 | 3.609375 | 4 | from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def __str__(self):
return "{{val:{self.val}, left:{self.left}, right:{self.right}}}".format(self=self) |
22abe81ec53e96c59d65989cf7ae15f105fd4dc7 | ggorla/python | /algorithmsPart1/quicksort.py | 857 | 3.609375 | 4 | items = [20,6, 8, 19, 56, 23, 87, 41, 49, 53]
def quicksort(dataset, first,last):
if first <last:
pivotIdx = partition(dataset,first,last)
quicksort(dataset,first,pivotIdx-1)
quicksort(dataset,pivotIdx+1,last)
def partition(datavalues, first, last):
pivotvalue = datavalues[fi... |
387ceef3f15e66bd1c0bc8cb0474e616d15c15f6 | ggorla/python | /helloworld/nestedLoops.py | 217 | 3.9375 | 4 | for x in range(4):
for y in range(3):
print(f"{x},{y}")
number = [5,2,5,2,2]
for x_count in number:
output = ''
for count in range(x_count):
output +='X'
print(output)
|
ddd7d1d13ce679ec30417165201c593466c37937 | ggorla/python | /helloworld/calender.py | 360 | 3.578125 | 4 | import calendar
print("team meeting will be on:")
for m in range(1,13):
cal = calendar.monthcalendar(2018,m)
weekone = cal[0]
weektow = cal[1]
if weekone[calendar.FRIDAY] != 0:
meetday = weekone[calendar.FRIDAY]
else:
meetday = weektow[calendar.FRIDAY]
print("%10s %... |
5e731608256795c1f446a0a896315b7747faef94 | ggorla/python | /helloworld/arthmitic.py | 280 | 4.03125 | 4 | print(10+3) # addition
print(10/3) # devison with floting point
print(10//3) # return integer
print(10%3) # modules remider of devision
print(10**3) # this is power/exponentiation
x=10
x=x+3
print(x)
#agumented assignemnt
x += 3
x = 10 + 3 * 2 ** 2
print(x) #x=22
|
5f7b626a242b76d263ddfd6e3e031ce086f11600 | rogue-hack-lab/rhlbot | /scorbot.py | 6,812 | 3.515625 | 4 | #!/usr/bin/env python
#
# See section [Appendix-A] of the ER3-Manual.pdf for the serial command
# protocol for the arm.
#
# Ok, so, joystick on /dev/input/js0, use pygame to read the joystick stuff
#
import serial, sys, time
jointnames = ["base", "shoulder", "elbow", "wristpitch", "wristroll", "gripper"]
# the joint... |
99d55d8bddeab10787ad3bc825f9b373618ab06c | elizabethpedley/pythonAssignments | /strListPractice/practice.py | 626 | 4 | 4 | words = "It's thanksgiving day. It's my birthday,too!"
x = [2,54,-2,7,12,98]
newList = []
x2 = [19,2,54,-2,7,12,98,32,10,-3,6]
newX = []
# find the position of the first 'day'
print(words.find('day'))
# replace 'day' with 'month'
print(words.replace('day', 'month'))
# the min value of x
print(min(x))
# the max value of... |
244f33f501c1cbcfae3ad43d7eeaae47d0b5cf08 | elizabethpedley/pythonAssignments | /classes/product.py | 990 | 3.515625 | 4 | class Product(object):
def __init__(self, price, name, weight, brand):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.status = 'for sale'
def sell(self):
self.status = 'sold'
return self
def add_tax(self):
... |
8b78f22972d495d737d81b9f2ce8ad6685e5e3df | zackls/cardai | /util/card_definitions.py | 703 | 3.5625 | 4 |
'''
The purpose of this class is mainly to make querying for cards easy.
'''
class CardDefinitions:
@classmethod
def setDefinitions(cls, main, treasures, answers):
cls.definitions = []
cls.cards = {
"main": [],
"treasures": [],
"answers": []
}
for deck, name in [(main, "main"), (treasures, "treasure... |
473c184dbb24f94a07d5791c1bf24637cf7a1ced | biona001/math127 | /fizzbuzz.py | 205 | 3.90625 | 4 | def fizzbuzz(int):
for int in range(0, int + 1):
if (int % 15 == 0):
print "fizzbuzz"
elif (int % 5 == 0):
print "fizz"
elif (int % 3 == 0):
print "buzz"
else:
print int
fizzbuzz(100) |
e76e449fdb427ede73ddabe08deea4f7bea75925 | npandey15/CatenationPython_Assignments | /Task6_Python/Q7.py | 419 | 3.8125 | 4 | # defining a decorator
def hello_decorator(func):
def inner():
print("Hello, How are you? ")
func()
print("Sounds Great! ")
return inner
# defining a function, to be called inside wrapper
def function_to_be_used():
print("I am doing good !!")
functio... |
0860ed14b0d55e8a3c09aeb9e56075354d1e1298 | npandey15/CatenationPython_Assignments | /Task1-Python/Task1_Python/Q3.py | 547 | 4.15625 | 4 | Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> x=6
>>> y=10
>>>
>>> Resultname=x
>>> x=y
>>> y=Resultname
>>> print("The value of x after swapping: {}".format(x))
The value of x after swapping:... |
8a99191f6780e06be6e14501b671cc981f42bf0d | npandey15/CatenationPython_Assignments | /Passwd.py | 1,188 | 4.34375 | 4 |
# Passwd creation in python
def checker_password(Passwd):
"Check if Passwd is valid"
Specialchar=["$","#","@","*","%"]
return_val=True
if len(passwd) < 8:
print("Passwd is too short, length of the password should be at least 8")
return_val=False
if len(passwd) > 30:
print... |
1eefd1be141f522c9f27977256ec9ed9d6a3ef77 | npandey15/CatenationPython_Assignments | /Task2_Python/Q7.py | 88 | 3.90625 | 4 | for x in range(6):
if x == 3 or x == 6:
continue
else:
print(x)
|
4f0be1102f0ff0abd51855a45fa3d07bf088ffd7 | iam-abhijha/Quiz-Python-Project | /calco1.py | 3,379 | 3.796875 | 4 | from tkinter import *
from math import *
window=Tk()
window.geometry("230x400")
window.minsize(230,400)
window.maxsize(230,400)
window.title("Calculator")
txt=StringVar()
expression=""
def sqroot():
add=sqrt(int(expression))
txt.set(add)
def click(num):
global expression
expression=e... |
371285746053c7dbb2298a7aa093dc26a21e9ea3 | Diegou2304/python-for-everybody | /RegularExpressions,XML,JSON/JavaScriptObjectNotation(JSON).py | 476 | 3.625 | 4 | import json
data = '''
[
{
"name" : "Diego",
"phone" : {
"type" : "intl",
"number" : "+59172698564"
}
},
{
"name" : "Dylan",
"phone" : {
"type" : "intl",
"number" : "++596285477"
}
}
]
'''
#It return a python dictionary
in... |
7c9c79dd3bf28edc526d1919a518734e61e47e1d | Blakely/DragonGame | /dragon.001.py | 3,069 | 4.15625 | 4 | import random
import time
def displayIntro():
print ('You are on a planet full of dragons. In front of you,')
print ('you see two caves. In one cave, the dragon is friendly')
print ('and will share his treasure with you. The other dragon')
print ('is greedy and hungry, and will eat you on sight.')
print
def cho... |
21529df3e0c9a7a3ed6514b99905d3c322aab8fc | youxi0011983/python_study | /crawler/Demo.py | 957 | 3.515625 | 4 | import urllib.request
if __name__ == '__main__':
# 爬取一个网页
file = urllib.request.urlopen("http://www.baidu.com")
data = file.read()
dataLine = file.readline()
# print(dataLine)
# print(data)
# 返回环境相关信息
print(file.info())
# 爬取网页的状态码
print(file.getcode())
# 爬取网页的URL地址
print... |
a40fb24485fd60b8e44fb0ee5c1976579e60a2be | kshimo69/euler | /euler20.py | 446 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# http://projecteuler.net/index.php?section=problems&id=20
factorial_nums = {}
def factorial(n):
if n == 1:
factorial_nums[1] = 1
return 1
elif n in factorial_nums:
print "has data"
return factorial_nums[n]
else:
factorial_nums[... |
16cfc5f6d1bebd9a26135a931a5cb9e12b02d3ce | kshimo69/euler | /euler12.py | 1,517 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Triangle(object):
"""
f(T1) = f(1) * f(2/2) => 1(1)
f(T2) = f(2/2) * f(3) => 2(1,2)
f(T3) = f(3) * f(4/2) => 4(1,2,3,6)
f(T4) = f(4/2) * f(5) => 4(1,2,5,10)
f(T5) = f(5) * f(6/2) => 4(1,3,5,15)
f(T6) = f(6/2) * f(7) => 4(1,3,7,21)
f(T7... |
bd9368bb7f6e3e936632f17550ae6cf0d4361c6c | qiny9492/ML-Algorithms | /Assignment-2/logistic.py | 12,537 | 3.5625 | 4 | from __future__ import division, print_function
import numpy as np
import scipy as sp
from matplotlib import pyplot as plt
from matplotlib import cm
#######################################################################
# DO NOT MODIFY THE CODE BELOW
###############################################################... |
8000f3cfe4db79488854619dde9de42cc0a6773a | aparna-narasimhan/python_examples | /Heap/heap_example.py | 427 | 3.765625 | 4 | >>> def heapsort(iterable):
... h = []
... for value in iterable:
... heappush(h, value)
... return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'... |
2255001526278b22c7cb99594f4f5274b399371a | aparna-narasimhan/python_examples | /Matrix/sort_2d_matrix.py | 1,281 | 4.28125 | 4 | #Approach 1: Sort 2D matrix in place
def sort_2d_matrix(A, m, n):
t=0
for x in range(m):
for y in range(n):
for i in range(m):
for j in range(n):
if(A[i][j]>A[x][y]):
print("Swapping %d with %d"%(A[i][j], A[x][y]))
t=A[x][y]
A[x][y]=A[i][j]
... |
6da25701a40c8e6fce75d9ab89aaf63a45e2ecfe | aparna-narasimhan/python_examples | /Strings/shortest_unique_substr.py | 1,322 | 4.15625 | 4 | '''
Smallest Substring of All Characters
Given an array of unique characters arr and a string str, Implement a function getShortestUniqueSubstring that finds the smallest substring of str containing all the characters in arr. Return "" (empty string) if such a substring doesn’t exist.
Come up with an asymptotically op... |
bb464259c098133aff720edafc73e5addaf9d693 | aparna-narasimhan/python_examples | /Strings/strstr_impl.py | 721 | 3.8125 | 4 | class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
#Search for 1st char in needle in haystack, if that matches, store the position and search for entire word by slicing. If it matches, return position, return ... |
926805abc9340bc48669b619b5e4b87db2a9a6a3 | aparna-narasimhan/python_examples | /Matrix/matrix_operations.py | 2,429 | 4.09375 | 4 | original=[
[1,2,3],
[6,7,6],
[3,2,1]
]
#print(original)
transpose = zip(*original)
print(transpose)
last_to_first = zip(original[::-1]) #last to first
print(last_to_first)
rotated = zip(*original[::-1]) #rotates 90 degrees
print(rotated)
rotated_180_deg = zip(*rotated[::-1])
print(rot... |
0111fd00103f42a032074e0c3b4d40006f1029f9 | aparna-narasimhan/python_examples | /Arrays/missing_number.py | 866 | 4.28125 | 4 | '''
If elements are in range of 1 to N, then we can find the missing number is a few ways:
Option 1 #: Convert arr to set, for num from 0 to n+1, find and return the number that does not exist in set.
Converting into set is better for lookup than using original list itself. However, space complexity is also O(N).
Opti... |
87e8c3dbfe7280667c7267bf9410ef1f7ac2ba4f | aparna-narasimhan/python_examples | /Arrays/is_sub_array.py | 297 | 3.71875 | 4 | class Solution:
def intersect(self, nums1, nums2):
if len(nums1) < len(nums2):
nums1, nums2 = nums2, nums1
for i in range(len(nums1)):
if nums1[i] == nums2[0] and nums1[i : i + len(nums2)] == nums2[::]:
return(True)
return(False) |
186ef277ad8fd8d3938ae3d4caefbb276ddcfc0b | aparna-narasimhan/python_examples | /Arrays/increasing_triplet.py | 560 | 3.859375 | 4 | #Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
#Eg: [12,11,10,5,6,2,30] -> True(5,6,30)
class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
min_num, a, b = float("inf"), float... |
60d52cf0986de89bfa495034b25eb059c1a599ab | aparna-narasimhan/python_examples | /Strings/multiply_strings.py | 718 | 3.765625 | 4 | '''
Multiply strings
"12","10" -> "120"
'''
result = ""
def multiply(A,B):
#Convert the given strings to numbers
#Calculate the product
#return the product
num_A = atoi(A)
num_B = atoi(B)
result = str(num_A * num_B)
print(result)
def atoi(s):
#Use a dictionary
atoi_str = "0123456789... |
9f9a367786ed71cf45c9c644cf524fb3ac493d0b | aparna-narasimhan/python_examples | /Recursion_examples/sum_of_numbers.py | 192 | 3.890625 | 4 | sum=0
def sum_of_nums(num_list):
if len(num_list) == 1:
return(num_list[0])
else:
return(num_list[0]+sum_of_nums(num_list[1:]))
sum=sum_of_nums([1,2,3,4,5])
print(sum) |
8159bd54c571130694263df0aa4aba4541f0e60d | aparna-narasimhan/python_examples | /Recursion_examples/pow_using_rec.py | 142 | 3.65625 | 4 | def calc_pow(base,exp):
if(exp==1):
return(base)
else:
return(base*calc_pow(base,exp-1))
res=calc_pow(9,2)
print(res) |
8d401a11b4ea284f9bb08c2e2615b9414fd3d3ac | aparna-narasimhan/python_examples | /Misc/regex.py | 2,008 | 4.625 | 5 | #https://www.tutorialspoint.com/python/python_reg_expressions.htm
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.grou... |
ac26b98728ecf7d49aa79f70aa5dd5e3238ef10d | aparna-narasimhan/python_examples | /pramp_solutions/get_different_number.py | 1,319 | 4.125 | 4 | '''
Getting a Different Number
Given an array arr of unique nonnegative integers, implement a function getDifferentNumber that finds the smallest nonnegative integer that is NOT in the array.
Even if your programming language of choice doesn’t have that restriction (like Python), assume that the maximum value an integ... |
200766f27792849ef17b1e83bebe3f846d42a83b | aparna-narasimhan/python_examples | /Recursion_examples/pow_using_recursion.py | 67 | 3.8125 | 4 | base=2
exp=3
pow=1
for i in range(exp):
pow=pow*base
print(pow) |
404c0bba3b32f4b778ef4de96dafd15a0f506535 | cesarzc/HackerRank | /Contests/WeekOfCode25/appendanddelete.py | 1,564 | 3.640625 | 4 | #!/bin/python3
string_A = input().strip()
string_B = input().strip()
number_of_operations = int(input().strip())
string_A_size = len(string_A)
string_B_size = len(string_B)
min_string_size = min(string_A_size, string_B_size)
common_string_size = 0
for (char_A, char_B) in zip(string_A[0:min_string_size], string_B[0:min... |
73c31af75550a6aa05317ffacb9c27ef0e335292 | cesarzc/HackerRank | /Contests/WeekOfCode30/melodiouspasswords.py | 2,951 | 4.09375 | 4 | #!/bin/python3
import re
import sys
import string
# Get the required data for the problem.
NUMBER_OF_LETTERS = int(input().strip())
VALID_VOWELS = "aeiou"
all_vowels_rx = '[' + re.escape(VALID_VOWELS + "y") + ']'
VALID_CONSONANTS = re.sub(all_vowels_rx, "", string.ascii_lowercase)
# This function returns a string ba... |
e0a859b10c1ea8481c6ee65a9acb6db0d445168f | jshapiro314/NLP | /Assignment2/BigramWordLangId-AO.py | 5,245 | 3.53125 | 4 | import re
from calculatePerplexity import calcPerplexityBigram
#Removing some punctuation (not including - or ') and splitting words on whitespace. Not changing uppercase letters to lowercase
#I am not using the start or end of sentences as tokens
#Open files, read in data, remove punctuation not including - or '
en... |
928513dc035a802013a8c235e45cb371131a313d | nadimmajed/Neural_crypto | /Code/2-experiment/Xor.py | 2,661 | 3.546875 | 4 | def plot(s,j,accuracy,loss):
"""s = with bias or s = without bias"""
from matplotlib import pyplot as plt
plt.figure(1)
fig1 = plt.figure(1)
fig1.canvas.set_window_title('XOR_1')
plt.subplot(2,2,j)
plt.ylabel('accuracy')
plt.xlabel('nb_hidden_units')
xlabel = [2,3,4,5]
plt.p... |
16590a36013f8cbe1997dc7c627a1c937b3c5c74 | hauphanlvc/CS114 | /tuan2.1/LinkedList.py | 5,008 | 3.59375 | 4 | import io,os,sys
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import time
class Node:
def __init__(self,value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def ThemDau(self,new_data)... |
2b0740af2a4c8083bdedb35a35afd7d3255f8277 | hauphanlvc/CS114 | /CodeGiup/Thoa_ChieuCaoCuaCay.py | 967 | 3.75 | 4 |
import collections
class Node:
def __init__(self,data):
self.left=None
self.right=None
self.val=data
def insert_tree(root,data):
if root is None:
return Node(data)
else:
if root.val==data:
return root
elif root.val<data:
root.right=insert_tree(root.right,data)
... |
d34a44e38b68b3e8ece36127cdc657fbab131cb7 | lita/friday_job_prep | /recursion/recursion_word_play.py | 960 | 3.953125 | 4 | """
Generate all the reorderings of a set of letters.
Get this code reviewed...
"""
def word_ordering(word):
if len(word)==1:
return [word]
newWords = []
for i in range(len(word)):
char = word[i]
newlist = word[0:i]+word[i+1:]
list = word_ordering(newlist)
for i in r... |
f8caf5d4acb484d7c76ce4e6f661a03441d026ed | mng990/Data-Structure-HW | /Struct 02 - 로보캅(2)/open01 (1)/gen_robocop.py | 1,549 | 3.5 | 4 | #-------------------------------------------------------------------------------
# Purpose: 2020 Prof. Zoh's Work
# Author: Cho
# Created: 2020-09-01
#-------------------------------------------------------------------------------
import random
import PIL
N= 14 # 꼭지점의 갯수
Mleng = 2000
random.s... |
a78baed96c8b0623c69637ffee7695ec59e8095f | EdMan1022/design-patterns | /examples/interface_example.py | 641 | 3.578125 | 4 |
class Dog(object):
def __init__(self, name, fur):
self.name = name
self.fur = fur
def speak(self, content, tone):
if tone == 'good':
return 'Bark!'
elif tone == 'bad':
return 'Growl'
class Person(object):
def __init__(self, name, mood):
... |
8cb974298a8b087f0d8b018143b6a16c2f661188 | YagoAlves/Funcional-POO-Prolog | /TrabalhoFinal/6.py | 158 | 3.984375 | 4 | #-*- coding: UTF-8-*-
s = raw_input() #= ["matam"]
def palindroma (string) :
if string[::-1] == string:
return "sim"
return "nao"
print palindroma(s) |
c43914b4bb7ba705d92a13f7612a07860118d7f6 | Akshitthapar/python-codes | /nestedfor.py | 91 | 3.859375 | 4 | for y in range(2,5):
for x in range (1,11):
k=x*y
print('table of',k,'is:')
print(k) |
d831d1256ea9114135dabc0b3675821ae8db947a | Akshitthapar/python-codes | /function.py | 129 | 3.6875 | 4 | def add(a,b):
k=a+b
print('total is',k)
x=(int) (input('enter no'))
y=(int) (input('enter no'))
add(x,y) #calling of function |
30f4c20cf32771629d6cba628f59ceaad3245e8c | Akshitthapar/python-codes | /control statements/ifelse/compare2.py | 223 | 4.03125 | 4 | print('welcome to 2 digit number compare program')
a=(int)(input('enter 1st number'))
b=(int)(input('enter 2nd number'))
if a>b:
print('a is greater than b')
else:
print('b is greater than a')
print('******thank u******') |
4b55400c1856ec78c959f6347aea7651304a60f4 | gokulramanaa/React_app | /AI_System/python_source/preorganizer.py | 203 | 3.75 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
def changedf(df):
new_df = pd.DataFrame()
for i in df.columns:
new_df[str(i)] = '* ' + df[str(i)].map(str) + ' *'
return new_df
|
11c820221362adf56e7a24cb4e7bd986ab111336 | doingsomethingrandom/fantastic-winner | /SayHello.py | 257 | 3.734375 | 4 | import random
age = random.randrange(0, 100)
fname = "Tharun"
lname = "Pandiyan"
fullName = f"{fname} {lname}"
greet = f"Hello {fullName}"
println(f"""{fname} is {age}-years-old.
His last name is {lname}.
He's {age}-year-old.
Say hello to him.
{greet}.""")
|
19494b279fa68cc3bb9a33f28e8311234ea0a86f | jin6818236/all_sgz | /学习/sanguo.py | 1,600 | 3.90625 | 4 | print('''东汉建安五年,
曹操与袁绍军相持官渡。
曹操:
袁绍兵多将广,该如何取胜之?甚是烦恼啊。。。。
那么该进攻哪里呢?1.延津 2.乌巢''')
a=input("")
input('曹操:谁愿前往?')
if a=="1":
input('关羽:关羽愿战以报曹公厚德')
elif a=="2":
input('徐晃:末将,徐晃愿往。')
else:
print('尔等依计袭敌粮道,断其后援')
#===========================================
input('''却说袁绍兴兵,望官渡进发。夏侯□发书告急。
曹操起军七万,前往迎敌,留荀□守许都。''')
... |
a8b52e3515b006ff00e5fb6084e85f63ecd2de15 | idan0610/intro2cs-ex11 | /priority_queue.py | 7,561 | 4.15625 | 4 | from node import Node
from priority_queue_iterator import PriorityQueueIterator
class PriorityQueue():
def __init__(self, tasks=[]):
"""
The function initiates a new PriorityQueue object, creation new Node
objects for each task on tasks list and putting them on the queue
:param ta... |
aee2ab470da613d1b8c5063302cfa7e7bfff032b | anandsagar7707/ict_fullstack | /html_css/python/lists.py | 186 | 3.671875 | 4 | myList=["rahul","ammu",",raj",9,6,2.7]
#print(myList)
# print(myList[3])
# print(myList[1:4])
# print(myList[3:])
# print(myList*3)
myselectedlist=["vishnu"]
print(myselectedlist+myList) |
cea48523a986c80e142932b472157753c1d9ea88 | anandsagar7707/ict_fullstack | /html_css/python/employ_class.py | 487 | 3.8125 | 4 | class Employee:
def __init__(self,w,x,y,z):
self.name=w
self.age=x
self.salary=y
self.code=z
def printdata(self):
print("employee name :",self.name)
print("employee age :",self.age)
print("employee.salary :",self.salary)
print("employee.code :",sel... |
e1fffb5f4ff3b4842710e316391122782ae93e85 | FrostGreg/coin-flip | /coin-flip.py | 526 | 3.859375 | 4 | import random
import sys
import time
print("========Welcome to the Coin Flip Sim========")
while 1:
a = random.randrange(0, 2)
s = '.'
sys.stdout.write("Flipping")
for i in range(5):
sys.stdout.write(s)
time.sleep(0.5)
if a == 1:
print("\nHeads!")
time.sleep(1)
... |
028d965ad442bc376f0da178b5c99fa5c8db16b4 | linh194093/DAS-with-Python | /dfs.py | 492 | 3.5625 | 4 | graph = {
'A': ['B', 'C', "D"],
'B': ['E', "F"],
'C': ['G', "I"],
'D': ["I"],
'E': [],
"F": [],
'G': [],
"I": []
}
#dfs without recursion
def dfs(visited, graph, currentNode):
stack = []
stack.append(currentNode)
while stack:
s = stack.pop()
if s in visited:... |
4dd0a4dc776c2fc2bc01d5e033e53941f7a65719 | mohammadsawas/python | /exmaples.py/mario clean/preparator.py | 251 | 3.640625 | 4 | from cs50 import get_int
class Preparator:
def get_height_in_range(self,minnum,maxnum):
while True:
number = get_int("Height: ")
if number >=minnum and number <=maxnum:
break
return number
|
ebce887b4918e015da4ffa2c2c643bec84ad4e88 | mohammadsawas/python | /exmaples.py/char.py | 129 | 3.609375 | 4 | import cs50
name = cs50.get_string()
number = 0;
for letter in name:
number = number + 1
print(number,end="")
print("") |
7aa7299780ba9f8100d8d15b41544f2bd227eddc | mohammadsawas/python | /exmaples.py/substring.py | 804 | 3.703125 | 4 | import cs50
def main():
number = cs50.get_int("number: ")
something = "what about us what about the life"
somethin2 = "how can i live how can breath what"
liste = []
liste2 = []
# قاك قاك
for i in range(len(somethin2) - number + 1 ):
liste.append(somethin2[i:i+number])
liste = l... |
93354f664979d327f700a7f5ed4a28d92b978b16 | premraval-pr/ds-algo-python | /data-structures/queue.py | 1,040 | 4.34375 | 4 | # FIFO Structure: First In First Out
class Queue:
def __init__(self):
self.queue = []
# Insert the data at the end / O(1)
def enqueue(self, data):
self.queue.append(data)
# remove and return the first item in queue / O(n) Linear time complexity
def dequeue(self):
if self.... |
df5afbce39d40a7ae6d7177524ecd13ab8327ee1 | yalotfi/torontoD3 | /data/clean_data.py | 892 | 3.578125 | 4 | '''
Author: Yaseen Lotfi
Date: 2/9/2016
Program: Query and prepare toronto city data for D3 visualizations
- Convert timestamps
- Count parking tickets by the day of the week
'''
# Import Dependencies
import pandas as pd
import datetime as dt
def weekdays(df, col_name, date_format='%Y%m%d'):
''' Pull wee... |
d73c7a9bec4f30251d31d42a17dfa7fde9a48f8e | danieltapp/fcc-python-solutions | /Basic Algorithm Scripting Challenges/caesars-cipher.py | 848 | 4.21875 | 4 | #One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.
#A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
#W... |
2248f6b4e815240d85ee37a6af3dc6c58d44d2d7 | danieltapp/fcc-python-solutions | /Basic Algorithm Scripting Challenges/reverse-a-string.py | 313 | 4.4375 | 4 | #Reverse the provided string.
#You may need to turn the string into an array before you can reverse it.
#Your result must be a string.
def reverse_string(str):
return ''.join(list(reversed(str)))
print(reverse_string('hello'))
print(reverse_string('Howdy'))
print(reverse_string('Greetings from Earth'))
|
b6c8ebac38345d119461ca2801a211c015b65e7b | Sofia-Ortega/mathDiscordBot | /math_game/generator.py | 2,456 | 3.953125 | 4 | """
Contains Generators for the equations
"""
from random import randint
def add_gen(rangeArray):
"""Takes array of min and max values. Returns str of unique 2 num equation and their sum"""
num1 = randint(rangeArray[0], rangeArray[1])
num2 = randint(rangeArray[0], rangeArray[1])
sum = num1 + num2
... |
b4daae8d6713a849ef293b6eae2d0f4d31ef6997 | qamk/data-analysis-ML-models-cc | /funnel.py | 1,476 | 3.640625 | 4 | #import codecademylib
import pandas as pd
visits = pd.read_csv('visits.csv',
parse_dates=[1])
cart = pd.read_csv('cart.csv',
parse_dates=[1])
checkout = pd.read_csv('checkout.csv',
parse_dates=[1])
purchase = pd.read_csv('purchase.csv',
... |
04385751593fef2998358c37c95362957e461d13 | darpanrajput/Instagram_Bot_In_Python | /Instagram_Bot/Insta_bot.py | 3,003 | 3.59375 | 4 | from selenium import webdriver
import os
import time
class InstagramBot:
def __init__(self,username,password):
'''
Initializes an instance of the InstagramBot
call login method
Args:
username:str:username of instagram
password:str:password of instagram
... |
7cec30bcfbf90b4ec8d8647fa1e7ab8929620440 | oluwaseunolusanya/al-n-ds-py | /chapter_6_searching_sorting/search.py | 281 | 3.734375 | 4 | def sequential_search(a_list, item):
item_pos = 0
while item_pos < len(a_list):
print(a_list[item_pos])
if(a_list[item_pos] == item):
return True
else:
item_pos += 1
return False
print(sequential_search([1, 2, 4, 3], 8)) |
759f39154fc321a20f84850be8482262b21b427e | oluwaseunolusanya/al-n-ds-py | /chapter_4_basic_data_structures/stackDS.py | 967 | 4.375 | 4 | class Stack:
#Stack implementation as a list.
def __init__(self):
self._items = [] #new stack
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.append(item)
def pop(self):
return self._items.pop()
def peek(self):
... |
4c575fe8e401140f6f86dade492fe6ae1af165db | OLEGIM/Ex1 | /Lesson-9-list2.py | 694 | 4.03125 | 4 | cars = ['bmw', 'vw', 'seat', 'skoda', 'lada']
print (cars)
for x in cars:
print(x.upper())
for x in range(1,6):
print(x)
mynumber_list = list(range(0, 10))
print(mynumber_list)
for x in mynumber_list:
x= x*2
print (x)
mynumber_list.sort(reverse=True)
print(mynumber_list)
print ("Max Numberis :" +... |
768c5e31ab91109674a03deb0fe1b489c00d0de2 | OLEGIM/Ex1 | /Lesson14-funcion.py | 510 | 3.640625 | 4 |
def napeshatat_privestvie(name):
"""PRIV"""
print(" CONGRAT " + name + " best ")
def summa(x,y):
return x + y
def factorial(x):
"""CALC FACTORIAL"""
otvet = 1
for i in range(1, x+1):
otvet = otvet *i
return otvet
napeshatat_privestvie("DENIS")
napeshatat_privestvie("OLEG")
#... |
4507614f7bc7f85942bd012461925a8611280bdb | Ben47happyday/ben | /Recursive.py | 159 | 3.5 | 4 | # n! = 1 * 2 * 3 * 4 ......(N-1) * N
def MyRecursiveTest(n):
if n == 1:
return n
return n * MyRecursiveTest(n-1)
print(MyRecursiveTest(10))
|
3223f8359db098322c5e55bd62d3b37c420670ac | CiaranSanders/CodingPractice | /leetcode/566/reshape.py | 772 | 3.546875 | 4 | from typing import List
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
# convert nxm matrix into rxc
n = len(mat[0]) # columns TODO handle if matrix is empty
m = len(mat) # rows
if n * m != r * c:
return mat
els... |
88d75d4590b354d437d8924faba26168fddc0440 | gdmgent-IoT-1920/labo-1-python-WouterJanssens98 | /Python oefening/reversewords.py | 324 | 3.9375 | 4 | import array
import collections
user = input("Geef een zin in! : ")
def reverseWords(input):
woordenarray = []
inputWoorden = input.split(" ")
for woord in inputWoorden:
woordenarray.append(woord)
for i in reversed(woordenarray):
print(i, end = " ")
reverseWords(user)
... |
56e6c4962ba2d1b6e167007facdb123fae5851ce | d42kw01f/NanoCoin | /TransectionRecording.py | 2,325 | 3.53125 | 4 | import string
import random
def Transaction():
SenderName = ''
#asking user to enter the sender's name
while SenderName.isalpha() is False:
SenderName = input("Enter the sender\'s name\n(make sure only to use letters and the maximum length is 10): ").strip().casefold()
RealSender = SenderN... |
6eeaf28db7712b70d7ada9c3632b832c0fdeec74 | melany202/programaci-n-2020 | /talleres/tallerCondicional.py | 1,918 | 4.125 | 4 | #Ejercicio 1 condicionales
print('ejercicio 1')
preguntaNumero1='Ingrese un numero entero : '
preguntaNumero2='Ingrese otro numero entero : '
numero1=int(input(preguntaNumero1))
numero2=int(input(preguntaNumero2))
if(numero1>numero2):
print(f'el {numero1} es mayor que el {numero2}')
elif(numero1==numero2):
p... |
a8a3b5ffad6ea8869c547da8d67b6c1bb500f01b | melany202/programaci-n-2020 | /examenes/parcial1.py | 3,094 | 3.75 | 4 | #primera parte
def elevar2(valor) :
return valor**2
def elevar3(valor):
return valor**3
def elevar4(valor):
return valor**4
def elevar5 (valor):
return valor**5
def calculadora (accion,valor):
print(accion(valor))
calculadora (elevar2,5)
calculadora (elevar3,3)
calculadora(elevar4,2)
calculado... |
44497cb95fbd26ae64fe24d9ed79f093f316f4a7 | melany202/programaci-n-2020 | /talleres/tallerHerencia.py | 2,576 | 3.6875 | 4 | #ejercicio 1
print('Ejercicio1')
class Persona:
def __init__(self,idIngresado,nombreIngresado,edadIngresada):
self.id = idIngresado
self.nombre = nombreIngresado
self.edad = edadIngresada
def hablar (self,mensaje):
print(f'la persona llamada {self.nombre} escribio: {mensaje}')
... |
9d05057f5d297ad2f0615cf15ad27db9a55eeaac | melany202/programaci-n-2020 | /clases/funciones/util/main.py | 739 | 3.5 | 4 | import operaciones_matematicas as opm
import operaciones_strings as ops
#mensajes
mensajeOperacion='{} las dos entradas'
ops.lineDesignC(12)
valor1= int(input('Ingrese el valor 1 : '))
valor2= int(input('Ingrese el valor 2 : '))
ops.lineDesignC(12)
print(mensajeOperacion.format('sumando'))
opm.calculadora(opm.sumar,val... |
07624fa04ac057f79221474e706242b6d5ebecb7 | Philipp1297/Project-Euler | /src/problem5.py | 351 | 3.5 | 4 | #Problem 5 Smallest multiple
for x in range(21,1000000000):
if x%10==0 and x%9==0 and x%8==0 and x%7==0 and x%6==0 and x%5==0 and x%4==0 and x%3==0 and x%2==0 and x%1==0:
if x%11==0 and x%12==0 and x%13==0 and x%14==0 and x%15==0 and x%16==0 and x%17==0 and x%18==0 and x%19==0 and x%20==0:
#pri... |
2027371ce11aec55ca9a7b5347b0ce0c2c01a8aa | EthanVG/FizzBuzz | /FizzBuzz.py | 542 | 3.71875 | 4 | import sys
c = 1
if (len(sys.argv) > 1):
n = sys.argv[1]
else:
n = input("Type a number: ")
try:
n = int(n)
except ValueError:
print("NAN: Input invalid")
n = input("Type a number: ")
print("Fizz buzz counting up to {0}".format(n))
for c in range (n +... |
8e50a0b4cac6ac7399fdd65d02796d9e2e14a73e | userzz15/- | /力扣/demo10-2.py | 808 | 3.75 | 4 | """
剑指 Offer 10- II. 青蛙跳台阶问题
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2
输出:2
示例 2:
输入:n = 7
输出:21
示例 3:
输入:n = 0
输出:1
提示:
0 <= n <= 100
"""
class Solution:
def numWays(self, n):
fibonacci_list = [1, 1]
if n < 2:
... |
12c60f5ae394f343056619738299f0d2a68e9bbb | userzz15/- | /力扣/Mysort.py | 2,774 | 4.125 | 4 | import random
def bubble_sort(arr, size):
"""冒泡排序"""
for i in range(size - 1):
for j in range(size - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
def select_sort(arr, size):
"""选择排序"""
for i in range(size - 1):
temp = i
f... |
fb887aed705b38b73b8fe58e3ff5facd44a6299d | userzz15/- | /力扣/demo12.py | 1,956 | 3.796875 | 4 | """
剑指 Offer 12. 矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
[["a","b","c","e"],
["s","f","c","s"],
["a","d","e","e"]]
但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
示例 1:
输入:board =... |
6cdaf4d4eed653266eebcc6caa8ed16b9b731c2b | carsugar/BananaMonkey | /bananamonkey.py | 647 | 3.703125 | 4 | # Hello Startup Institute Team
# Thanks for checking out my code!
# Use tweepy module to access Twitter API from Python
import tweepy
# Save OAth Information
CONSUMER_KEY = 'CSwQx9t9IEhgxM84jUyfzA'
CONSUMER_SECRET = 'yVYvZaBJIuerH5nipG1zipMJDd0fNNQT4UU28v7QeM'
ACCESS_TOKEN = '2318037230-XVVmvoPLPGGeEs9P1PmxN4rlrlB1... |
5850dc58615621241bc9fbea53a63a72145cc43b | NawaNae/CloudTestPython | /8.py | 122 | 3.921875 | 4 | m=2
n=3
arr=[[i for i in range(j)]for j in range(1,n)]
print(arr[0])
print(arr[1])
x=[i for i in range(m)]
print(x[0]) |
3d5fb08eb1226cf62fa041300befb41117538f88 | ananthphyton/Phyton-practice | /While loop exercise.py | 399 | 3.8125 | 4 | #while loop quiz question from telusuko.
#Question print all numbers from 1 to 100 except which are divisable by 3 or 5.
i = 1
while i <= 100:
if (i%3!=0) and (i%5!=0):
print(i)
i = i +1
#print # 5 times in each line in 4 lines.
j=1
while j <= 4:
print("#",end="")
k=1
while... |
a12a8dfe121542a6ac1d25c267072e33babc2df5 | Zhang21/DevOps | /py/tryExcept.py | 546 | 3.703125 | 4 |
'''
while True:
try:
x = int(input('Input a number: '))
break
except:
#except ValueError:
print('Error,Try again...')
'''
'''
import sys
try:
f = open('/tmp/1.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print('OS error: {}'.format(err))
except ValueE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.